View.java revision cd1af32eda2172ac73396b6336e358a0c9711187
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.os.Build;
65import android.os.Bundle;
66import android.os.Handler;
67import android.os.IBinder;
68import android.os.Parcel;
69import android.os.Parcelable;
70import android.os.RemoteException;
71import android.os.SystemClock;
72import android.os.SystemProperties;
73import android.os.Trace;
74import android.text.TextUtils;
75import android.util.AttributeSet;
76import android.util.FloatProperty;
77import android.util.LayoutDirection;
78import android.util.Log;
79import android.util.LongSparseLongArray;
80import android.util.Pools.SynchronizedPool;
81import android.util.Property;
82import android.util.SparseArray;
83import android.util.StateSet;
84import android.util.SuperNotCalledException;
85import android.util.TypedValue;
86import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
87import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
88import android.view.AccessibilityIterators.TextSegmentIterator;
89import android.view.AccessibilityIterators.WordTextSegmentIterator;
90import android.view.ContextMenu.ContextMenuInfo;
91import android.view.accessibility.AccessibilityEvent;
92import android.view.accessibility.AccessibilityEventSource;
93import android.view.accessibility.AccessibilityManager;
94import android.view.accessibility.AccessibilityNodeInfo;
95import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
96import android.view.accessibility.AccessibilityNodeProvider;
97import android.view.animation.Animation;
98import android.view.animation.AnimationUtils;
99import android.view.animation.Transformation;
100import android.view.autofill.AutoFillManager;
101import android.view.autofill.AutoFillType;
102import android.view.autofill.AutoFillValue;
103import android.view.inputmethod.EditorInfo;
104import android.view.inputmethod.InputConnection;
105import android.view.inputmethod.InputMethodManager;
106import android.widget.Checkable;
107import android.widget.FrameLayout;
108import android.widget.ScrollBarDrawable;
109
110import com.android.internal.R;
111import com.android.internal.util.Preconditions;
112import com.android.internal.view.TooltipPopup;
113import com.android.internal.view.menu.MenuBuilder;
114import com.android.internal.widget.ScrollBarUtils;
115
116import com.google.android.collect.Lists;
117import com.google.android.collect.Maps;
118
119import java.lang.annotation.Retention;
120import java.lang.annotation.RetentionPolicy;
121import java.lang.ref.WeakReference;
122import java.lang.reflect.Field;
123import java.lang.reflect.InvocationTargetException;
124import java.lang.reflect.Method;
125import java.lang.reflect.Modifier;
126import java.util.ArrayList;
127import java.util.Arrays;
128import java.util.Collection;
129import java.util.Collections;
130import java.util.HashMap;
131import java.util.List;
132import java.util.Locale;
133import java.util.Map;
134import java.util.concurrent.CopyOnWriteArrayList;
135import java.util.concurrent.atomic.AtomicInteger;
136import java.util.function.Predicate;
137
138/**
139 * <p>
140 * This class represents the basic building block for user interface components. A View
141 * occupies a rectangular area on the screen and is responsible for drawing and
142 * event handling. View is the base class for <em>widgets</em>, which are
143 * used to create interactive UI components (buttons, text fields, etc.). The
144 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
145 * are invisible containers that hold other Views (or other ViewGroups) and define
146 * their layout properties.
147 * </p>
148 *
149 * <div class="special reference">
150 * <h3>Developer Guides</h3>
151 * <p>For information about using this class to develop your application's user interface,
152 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
153 * </div>
154 *
155 * <a name="Using"></a>
156 * <h3>Using Views</h3>
157 * <p>
158 * All of the views in a window are arranged in a single tree. You can add views
159 * either from code or by specifying a tree of views in one or more XML layout
160 * files. There are many specialized subclasses of views that act as controls or
161 * are capable of displaying text, images, or other content.
162 * </p>
163 * <p>
164 * Once you have created a tree of views, there are typically a few types of
165 * common operations you may wish to perform:
166 * <ul>
167 * <li><strong>Set properties:</strong> for example setting the text of a
168 * {@link android.widget.TextView}. The available properties and the methods
169 * that set them will vary among the different subclasses of views. Note that
170 * properties that are known at build time can be set in the XML layout
171 * files.</li>
172 * <li><strong>Set focus:</strong> The framework will handle moving focus in
173 * response to user input. To force focus to a specific view, call
174 * {@link #requestFocus}.</li>
175 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
176 * that will be notified when something interesting happens to the view. For
177 * example, all views will let you set a listener to be notified when the view
178 * gains or loses focus. You can register such a listener using
179 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
180 * Other view subclasses offer more specialized listeners. For example, a Button
181 * exposes a listener to notify clients when the button is clicked.</li>
182 * <li><strong>Set visibility:</strong> You can hide or show views using
183 * {@link #setVisibility(int)}.</li>
184 * </ul>
185 * </p>
186 * <p><em>
187 * Note: The Android framework is responsible for measuring, laying out and
188 * drawing views. You should not call methods that perform these actions on
189 * views yourself unless you are actually implementing a
190 * {@link android.view.ViewGroup}.
191 * </em></p>
192 *
193 * <a name="Lifecycle"></a>
194 * <h3>Implementing a Custom View</h3>
195 *
196 * <p>
197 * To implement a custom view, you will usually begin by providing overrides for
198 * some of the standard methods that the framework calls on all views. You do
199 * not need to override all of these methods. In fact, you can start by just
200 * overriding {@link #onDraw(android.graphics.Canvas)}.
201 * <table border="2" width="85%" align="center" cellpadding="5">
202 *     <thead>
203 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
204 *     </thead>
205 *
206 *     <tbody>
207 *     <tr>
208 *         <td rowspan="2">Creation</td>
209 *         <td>Constructors</td>
210 *         <td>There is a form of the constructor that are called when the view
211 *         is created from code and a form that is called when the view is
212 *         inflated from a layout file. The second form should parse and apply
213 *         any attributes defined in the layout file.
214 *         </td>
215 *     </tr>
216 *     <tr>
217 *         <td><code>{@link #onFinishInflate()}</code></td>
218 *         <td>Called after a view and all of its children has been inflated
219 *         from XML.</td>
220 *     </tr>
221 *
222 *     <tr>
223 *         <td rowspan="3">Layout</td>
224 *         <td><code>{@link #onMeasure(int, int)}</code></td>
225 *         <td>Called to determine the size requirements for this view and all
226 *         of its children.
227 *         </td>
228 *     </tr>
229 *     <tr>
230 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
231 *         <td>Called when this view should assign a size and position to all
232 *         of its children.
233 *         </td>
234 *     </tr>
235 *     <tr>
236 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
237 *         <td>Called when the size of this view has changed.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td>Drawing</td>
243 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
244 *         <td>Called when the view should render its content.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td rowspan="4">Event processing</td>
250 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
251 *         <td>Called when a new hardware key event occurs.
252 *         </td>
253 *     </tr>
254 *     <tr>
255 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
256 *         <td>Called when a hardware key up event occurs.
257 *         </td>
258 *     </tr>
259 *     <tr>
260 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
261 *         <td>Called when a trackball motion event occurs.
262 *         </td>
263 *     </tr>
264 *     <tr>
265 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
266 *         <td>Called when a touch screen motion event occurs.
267 *         </td>
268 *     </tr>
269 *
270 *     <tr>
271 *         <td rowspan="2">Focus</td>
272 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
273 *         <td>Called when the view gains or loses focus.
274 *         </td>
275 *     </tr>
276 *
277 *     <tr>
278 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
279 *         <td>Called when the window containing the view gains or loses focus.
280 *         </td>
281 *     </tr>
282 *
283 *     <tr>
284 *         <td rowspan="3">Attaching</td>
285 *         <td><code>{@link #onAttachedToWindow()}</code></td>
286 *         <td>Called when the view is attached to a window.
287 *         </td>
288 *     </tr>
289 *
290 *     <tr>
291 *         <td><code>{@link #onDetachedFromWindow}</code></td>
292 *         <td>Called when the view is detached from its window.
293 *         </td>
294 *     </tr>
295 *
296 *     <tr>
297 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
298 *         <td>Called when the visibility of the window containing the view
299 *         has changed.
300 *         </td>
301 *     </tr>
302 *     </tbody>
303 *
304 * </table>
305 * </p>
306 *
307 * <a name="IDs"></a>
308 * <h3>IDs</h3>
309 * Views may have an integer id associated with them. These ids are typically
310 * assigned in the layout XML files, and are used to find specific views within
311 * the view tree. A common pattern is to:
312 * <ul>
313 * <li>Define a Button in the layout file and assign it a unique ID.
314 * <pre>
315 * &lt;Button
316 *     android:id="@+id/my_button"
317 *     android:layout_width="wrap_content"
318 *     android:layout_height="wrap_content"
319 *     android:text="@string/my_button_text"/&gt;
320 * </pre></li>
321 * <li>From the onCreate method of an Activity, find the Button
322 * <pre class="prettyprint">
323 *      Button myButton = (Button) findViewById(R.id.my_button);
324 * </pre></li>
325 * </ul>
326 * <p>
327 * View IDs need not be unique throughout the tree, but it is good practice to
328 * ensure that they are at least unique within the part of the tree you are
329 * searching.
330 * </p>
331 *
332 * <a name="Position"></a>
333 * <h3>Position</h3>
334 * <p>
335 * The geometry of a view is that of a rectangle. A view has a location,
336 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
337 * two dimensions, expressed as a width and a height. The unit for location
338 * and dimensions is the pixel.
339 * </p>
340 *
341 * <p>
342 * It is possible to retrieve the location of a view by invoking the methods
343 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
344 * coordinate of the rectangle representing the view. The latter returns the
345 * top, or Y, coordinate of the rectangle representing the view. These methods
346 * both return the location of the view relative to its parent. For instance,
347 * when getLeft() returns 20, that means the view is located 20 pixels to the
348 * right of the left edge of its direct parent.
349 * </p>
350 *
351 * <p>
352 * In addition, several convenience methods are offered to avoid unnecessary
353 * computations, namely {@link #getRight()} and {@link #getBottom()}.
354 * These methods return the coordinates of the right and bottom edges of the
355 * rectangle representing the view. For instance, calling {@link #getRight()}
356 * is similar to the following computation: <code>getLeft() + getWidth()</code>
357 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
358 * </p>
359 *
360 * <a name="SizePaddingMargins"></a>
361 * <h3>Size, padding and margins</h3>
362 * <p>
363 * The size of a view is expressed with a width and a height. A view actually
364 * possess two pairs of width and height values.
365 * </p>
366 *
367 * <p>
368 * The first pair is known as <em>measured width</em> and
369 * <em>measured height</em>. These dimensions define how big a view wants to be
370 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
371 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
372 * and {@link #getMeasuredHeight()}.
373 * </p>
374 *
375 * <p>
376 * The second pair is simply known as <em>width</em> and <em>height</em>, or
377 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
378 * dimensions define the actual size of the view on screen, at drawing time and
379 * after layout. These values may, but do not have to, be different from the
380 * measured width and height. The width and height can be obtained by calling
381 * {@link #getWidth()} and {@link #getHeight()}.
382 * </p>
383 *
384 * <p>
385 * To measure its dimensions, a view takes into account its padding. The padding
386 * is expressed in pixels for the left, top, right and bottom parts of the view.
387 * Padding can be used to offset the content of the view by a specific amount of
388 * pixels. For instance, a left padding of 2 will push the view's content by
389 * 2 pixels to the right of the left edge. Padding can be set using the
390 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
391 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
392 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
393 * {@link #getPaddingEnd()}.
394 * </p>
395 *
396 * <p>
397 * Even though a view can define a padding, it does not provide any support for
398 * margins. However, view groups provide such a support. Refer to
399 * {@link android.view.ViewGroup} and
400 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
401 * </p>
402 *
403 * <a name="Layout"></a>
404 * <h3>Layout</h3>
405 * <p>
406 * Layout is a two pass process: a measure pass and a layout pass. The measuring
407 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
408 * of the view tree. Each view pushes dimension specifications down the tree
409 * during the recursion. At the end of the measure pass, every view has stored
410 * its measurements. The second pass happens in
411 * {@link #layout(int,int,int,int)} and is also top-down. During
412 * this pass each parent is responsible for positioning all of its children
413 * using the sizes computed in the measure pass.
414 * </p>
415 *
416 * <p>
417 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
418 * {@link #getMeasuredHeight()} values must be set, along with those for all of
419 * that view's descendants. A view's measured width and measured height values
420 * must respect the constraints imposed by the view's parents. This guarantees
421 * that at the end of the measure pass, all parents accept all of their
422 * children's measurements. A parent view may call measure() more than once on
423 * its children. For example, the parent may measure each child once with
424 * unspecified dimensions to find out how big they want to be, then call
425 * measure() on them again with actual numbers if the sum of all the children's
426 * unconstrained sizes is too big or too small.
427 * </p>
428 *
429 * <p>
430 * The measure pass uses two classes to communicate dimensions. The
431 * {@link MeasureSpec} class is used by views to tell their parents how they
432 * want to be measured and positioned. The base LayoutParams class just
433 * describes how big the view wants to be for both width and height. For each
434 * dimension, it can specify one of:
435 * <ul>
436 * <li> an exact number
437 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
438 * (minus padding)
439 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
440 * enclose its content (plus padding).
441 * </ul>
442 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
443 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
444 * an X and Y value.
445 * </p>
446 *
447 * <p>
448 * MeasureSpecs are used to push requirements down the tree from parent to
449 * child. A MeasureSpec can be in one of three modes:
450 * <ul>
451 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
452 * of a child view. For example, a LinearLayout may call measure() on its child
453 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
454 * tall the child view wants to be given a width of 240 pixels.
455 * <li>EXACTLY: This is used by the parent to impose an exact size on the
456 * child. The child must use this size, and guarantee that all of its
457 * descendants will fit within this size.
458 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
459 * child. The child must guarantee that it and all of its descendants will fit
460 * within this size.
461 * </ul>
462 * </p>
463 *
464 * <p>
465 * To initiate a layout, call {@link #requestLayout}. This method is typically
466 * called by a view on itself when it believes that is can no longer fit within
467 * its current bounds.
468 * </p>
469 *
470 * <a name="Drawing"></a>
471 * <h3>Drawing</h3>
472 * <p>
473 * Drawing is handled by walking the tree and recording the drawing commands of
474 * any View that needs to update. After this, the drawing commands of the
475 * entire tree are issued to screen, clipped to the newly damaged area.
476 * </p>
477 *
478 * <p>
479 * The tree is largely recorded and drawn in order, with parents drawn before
480 * (i.e., behind) their children, with siblings drawn in the order they appear
481 * in the tree. If you set a background drawable for a View, then the View will
482 * draw it before calling back to its <code>onDraw()</code> method. The child
483 * drawing order can be overridden with
484 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
485 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
486 * </p>
487 *
488 * <p>
489 * To force a view to draw, call {@link #invalidate()}.
490 * </p>
491 *
492 * <a name="EventHandlingThreading"></a>
493 * <h3>Event Handling and Threading</h3>
494 * <p>
495 * The basic cycle of a view is as follows:
496 * <ol>
497 * <li>An event comes in and is dispatched to the appropriate view. The view
498 * handles the event and notifies any listeners.</li>
499 * <li>If in the course of processing the event, the view's bounds may need
500 * to be changed, the view will call {@link #requestLayout()}.</li>
501 * <li>Similarly, if in the course of processing the event the view's appearance
502 * may need to be changed, the view will call {@link #invalidate()}.</li>
503 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
504 * the framework will take care of measuring, laying out, and drawing the tree
505 * as appropriate.</li>
506 * </ol>
507 * </p>
508 *
509 * <p><em>Note: The entire view tree is single threaded. You must always be on
510 * the UI thread when calling any method on any view.</em>
511 * If you are doing work on other threads and want to update the state of a view
512 * from that thread, you should use a {@link Handler}.
513 * </p>
514 *
515 * <a name="FocusHandling"></a>
516 * <h3>Focus Handling</h3>
517 * <p>
518 * The framework will handle routine focus movement in response to user input.
519 * This includes changing the focus as views are removed or hidden, or as new
520 * views become available. Views indicate their willingness to take focus
521 * through the {@link #isFocusable} method. To change whether a view can take
522 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
523 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
524 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
525 * </p>
526 * <p>
527 * Focus movement is based on an algorithm which finds the nearest neighbor in a
528 * given direction. In rare cases, the default algorithm may not match the
529 * intended behavior of the developer. In these situations, you can provide
530 * explicit overrides by using these XML attributes in the layout file:
531 * <pre>
532 * nextFocusDown
533 * nextFocusLeft
534 * nextFocusRight
535 * nextFocusUp
536 * </pre>
537 * </p>
538 *
539 *
540 * <p>
541 * To get a particular view to take focus, call {@link #requestFocus()}.
542 * </p>
543 *
544 * <a name="TouchMode"></a>
545 * <h3>Touch Mode</h3>
546 * <p>
547 * When a user is navigating a user interface via directional keys such as a D-pad, it is
548 * necessary to give focus to actionable items such as buttons so the user can see
549 * what will take input.  If the device has touch capabilities, however, and the user
550 * begins interacting with the interface by touching it, it is no longer necessary to
551 * always highlight, or give focus to, a particular view.  This motivates a mode
552 * for interaction named 'touch mode'.
553 * </p>
554 * <p>
555 * For a touch capable device, once the user touches the screen, the device
556 * will enter touch mode.  From this point onward, only views for which
557 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
558 * Other views that are touchable, like buttons, will not take focus when touched; they will
559 * only fire the on click listeners.
560 * </p>
561 * <p>
562 * Any time a user hits a directional key, such as a D-pad direction, the view device will
563 * exit touch mode, and find a view to take focus, so that the user may resume interacting
564 * with the user interface without touching the screen again.
565 * </p>
566 * <p>
567 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
568 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
569 * </p>
570 *
571 * <a name="Scrolling"></a>
572 * <h3>Scrolling</h3>
573 * <p>
574 * The framework provides basic support for views that wish to internally
575 * scroll their content. This includes keeping track of the X and Y scroll
576 * offset as well as mechanisms for drawing scrollbars. See
577 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
578 * {@link #awakenScrollBars()} for more details.
579 * </p>
580 *
581 * <a name="Tags"></a>
582 * <h3>Tags</h3>
583 * <p>
584 * Unlike IDs, tags are not used to identify views. Tags are essentially an
585 * extra piece of information that can be associated with a view. They are most
586 * often used as a convenience to store data related to views in the views
587 * themselves rather than by putting them in a separate structure.
588 * </p>
589 * <p>
590 * Tags may be specified with character sequence values in layout XML as either
591 * a single tag using the {@link android.R.styleable#View_tag android:tag}
592 * attribute or multiple tags using the {@code <tag>} child element:
593 * <pre>
594 *     &ltView ...
595 *           android:tag="@string/mytag_value" /&gt;
596 *     &ltView ...&gt;
597 *         &lttag android:id="@+id/mytag"
598 *              android:value="@string/mytag_value" /&gt;
599 *     &lt/View>
600 * </pre>
601 * </p>
602 * <p>
603 * Tags may also be specified with arbitrary objects from code using
604 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
605 * </p>
606 *
607 * <a name="Themes"></a>
608 * <h3>Themes</h3>
609 * <p>
610 * By default, Views are created using the theme of the Context object supplied
611 * to their constructor; however, a different theme may be specified by using
612 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
613 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
614 * code.
615 * </p>
616 * <p>
617 * When the {@link android.R.styleable#View_theme android:theme} attribute is
618 * used in XML, the specified theme is applied on top of the inflation
619 * context's theme (see {@link LayoutInflater}) and used for the view itself as
620 * well as any child elements.
621 * </p>
622 * <p>
623 * In the following example, both views will be created using the Material dark
624 * color scheme; however, because an overlay theme is used which only defines a
625 * subset of attributes, the value of
626 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
627 * the inflation context's theme (e.g. the Activity theme) will be preserved.
628 * <pre>
629 *     &ltLinearLayout
630 *             ...
631 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
632 *         &ltView ...&gt;
633 *     &lt/LinearLayout&gt;
634 * </pre>
635 * </p>
636 *
637 * <a name="Properties"></a>
638 * <h3>Properties</h3>
639 * <p>
640 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
641 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
642 * available both in the {@link Property} form as well as in similarly-named setter/getter
643 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
644 * be used to set persistent state associated with these rendering-related properties on the view.
645 * The properties and methods can also be used in conjunction with
646 * {@link android.animation.Animator Animator}-based animations, described more in the
647 * <a href="#Animation">Animation</a> section.
648 * </p>
649 *
650 * <a name="Animation"></a>
651 * <h3>Animation</h3>
652 * <p>
653 * Starting with Android 3.0, the preferred way of animating views is to use the
654 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
655 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
656 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
657 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
658 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
659 * makes animating these View properties particularly easy and efficient.
660 * </p>
661 * <p>
662 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
663 * You can attach an {@link Animation} object to a view using
664 * {@link #setAnimation(Animation)} or
665 * {@link #startAnimation(Animation)}. The animation can alter the scale,
666 * rotation, translation and alpha of a view over time. If the animation is
667 * attached to a view that has children, the animation will affect the entire
668 * subtree rooted by that node. When an animation is started, the framework will
669 * take care of redrawing the appropriate views until the animation completes.
670 * </p>
671 *
672 * <a name="Security"></a>
673 * <h3>Security</h3>
674 * <p>
675 * Sometimes it is essential that an application be able to verify that an action
676 * is being performed with the full knowledge and consent of the user, such as
677 * granting a permission request, making a purchase or clicking on an advertisement.
678 * Unfortunately, a malicious application could try to spoof the user into
679 * performing these actions, unaware, by concealing the intended purpose of the view.
680 * As a remedy, the framework offers a touch filtering mechanism that can be used to
681 * improve the security of views that provide access to sensitive functionality.
682 * </p><p>
683 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
684 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
685 * will discard touches that are received whenever the view's window is obscured by
686 * another visible window.  As a result, the view will not receive touches whenever a
687 * toast, dialog or other window appears above the view's window.
688 * </p><p>
689 * For more fine-grained control over security, consider overriding the
690 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
691 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
692 * </p>
693 *
694 * @attr ref android.R.styleable#View_alpha
695 * @attr ref android.R.styleable#View_background
696 * @attr ref android.R.styleable#View_clickable
697 * @attr ref android.R.styleable#View_contentDescription
698 * @attr ref android.R.styleable#View_drawingCacheQuality
699 * @attr ref android.R.styleable#View_duplicateParentState
700 * @attr ref android.R.styleable#View_id
701 * @attr ref android.R.styleable#View_requiresFadingEdge
702 * @attr ref android.R.styleable#View_fadeScrollbars
703 * @attr ref android.R.styleable#View_fadingEdgeLength
704 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
705 * @attr ref android.R.styleable#View_fitsSystemWindows
706 * @attr ref android.R.styleable#View_isScrollContainer
707 * @attr ref android.R.styleable#View_focusable
708 * @attr ref android.R.styleable#View_focusableInTouchMode
709 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
710 * @attr ref android.R.styleable#View_keepScreenOn
711 * @attr ref android.R.styleable#View_layerType
712 * @attr ref android.R.styleable#View_layoutDirection
713 * @attr ref android.R.styleable#View_longClickable
714 * @attr ref android.R.styleable#View_minHeight
715 * @attr ref android.R.styleable#View_minWidth
716 * @attr ref android.R.styleable#View_nextFocusDown
717 * @attr ref android.R.styleable#View_nextFocusLeft
718 * @attr ref android.R.styleable#View_nextFocusRight
719 * @attr ref android.R.styleable#View_nextFocusUp
720 * @attr ref android.R.styleable#View_onClick
721 * @attr ref android.R.styleable#View_padding
722 * @attr ref android.R.styleable#View_paddingBottom
723 * @attr ref android.R.styleable#View_paddingLeft
724 * @attr ref android.R.styleable#View_paddingRight
725 * @attr ref android.R.styleable#View_paddingTop
726 * @attr ref android.R.styleable#View_paddingStart
727 * @attr ref android.R.styleable#View_paddingEnd
728 * @attr ref android.R.styleable#View_saveEnabled
729 * @attr ref android.R.styleable#View_rotation
730 * @attr ref android.R.styleable#View_rotationX
731 * @attr ref android.R.styleable#View_rotationY
732 * @attr ref android.R.styleable#View_scaleX
733 * @attr ref android.R.styleable#View_scaleY
734 * @attr ref android.R.styleable#View_scrollX
735 * @attr ref android.R.styleable#View_scrollY
736 * @attr ref android.R.styleable#View_scrollbarSize
737 * @attr ref android.R.styleable#View_scrollbarStyle
738 * @attr ref android.R.styleable#View_scrollbars
739 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
740 * @attr ref android.R.styleable#View_scrollbarFadeDuration
741 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
742 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
743 * @attr ref android.R.styleable#View_scrollbarThumbVertical
744 * @attr ref android.R.styleable#View_scrollbarTrackVertical
745 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
746 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
747 * @attr ref android.R.styleable#View_stateListAnimator
748 * @attr ref android.R.styleable#View_transitionName
749 * @attr ref android.R.styleable#View_soundEffectsEnabled
750 * @attr ref android.R.styleable#View_tag
751 * @attr ref android.R.styleable#View_textAlignment
752 * @attr ref android.R.styleable#View_textDirection
753 * @attr ref android.R.styleable#View_transformPivotX
754 * @attr ref android.R.styleable#View_transformPivotY
755 * @attr ref android.R.styleable#View_translationX
756 * @attr ref android.R.styleable#View_translationY
757 * @attr ref android.R.styleable#View_translationZ
758 * @attr ref android.R.styleable#View_visibility
759 * @attr ref android.R.styleable#View_theme
760 *
761 * @see android.view.ViewGroup
762 */
763@UiThread
764public class View implements Drawable.Callback, KeyEvent.Callback,
765        AccessibilityEventSource {
766    private static final boolean DBG = false;
767
768    /** @hide */
769    public static boolean DEBUG_DRAW = false;
770
771    /**
772     * The logging tag used by this class with android.util.Log.
773     */
774    protected static final String VIEW_LOG_TAG = "View";
775
776    /**
777     * When set to true, apps will draw debugging information about their layouts.
778     *
779     * @hide
780     */
781    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
782
783    /**
784     * When set to true, this view will save its attribute data.
785     *
786     * @hide
787     */
788    public static boolean mDebugViewAttributes = false;
789
790    /**
791     * Used to mark a View that has no ID.
792     */
793    public static final int NO_ID = -1;
794
795    /**
796     * Signals that compatibility booleans have been initialized according to
797     * target SDK versions.
798     */
799    private static boolean sCompatibilityDone = false;
800
801    /**
802     * Use the old (broken) way of building MeasureSpecs.
803     */
804    private static boolean sUseBrokenMakeMeasureSpec = false;
805
806    /**
807     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
808     */
809    static boolean sUseZeroUnspecifiedMeasureSpec = false;
810
811    /**
812     * Ignore any optimizations using the measure cache.
813     */
814    private static boolean sIgnoreMeasureCache = false;
815
816    /**
817     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
818     */
819    private static boolean sAlwaysRemeasureExactly = false;
820
821    /**
822     * Relax constraints around whether setLayoutParams() must be called after
823     * modifying the layout params.
824     */
825    private static boolean sLayoutParamsAlwaysChanged = false;
826
827    /**
828     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
829     * without throwing
830     */
831    static boolean sTextureViewIgnoresDrawableSetters = false;
832
833    /**
834     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
835     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
836     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
837     * check is implemented for backwards compatibility.
838     *
839     * {@hide}
840     */
841    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
842
843    /**
844     * Prior to N, when drag enters into child of a view that has already received an
845     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
846     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
847     * false from its event handler for these events.
848     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
849     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
850     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
851     */
852    static boolean sCascadedDragDrop;
853
854    /**
855     * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable
856     * to determine things like whether or not to permit item click events. We can't break
857     * apps that do this just because more things (clickable things) are now auto-focusable
858     * and they would get different results, so give old behavior to old apps.
859     */
860    static boolean sHasFocusableExcludeAutoFocusable;
861
862    /**
863     * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly
864     * made focusable by default. As a result, apps could (incorrectly) change the clickable
865     * setting of views off the UI thread. Now that clickable can effect the focusable state,
866     * changing the clickable attribute off the UI thread will cause an exception (since changing
867     * the focusable state checks). In order to prevent apps from crashing, we will handle this
868     * specific case and just not notify parents on new focusables resulting from marking views
869     * clickable from outside the UI thread.
870     */
871    private static boolean sAutoFocusableOffUIThreadWontNotifyParents;
872
873    /** @hide */
874    @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
875    @Retention(RetentionPolicy.SOURCE)
876    public @interface Focusable {}
877
878    /**
879     * This view does not want keystrokes.
880     * <p>
881     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
882     * android:focusable}.
883     */
884    public static final int NOT_FOCUSABLE = 0x00000000;
885
886    /**
887     * This view wants keystrokes.
888     * <p>
889     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
890     * android:focusable}.
891     */
892    public static final int FOCUSABLE = 0x00000001;
893
894    /**
895     * This view determines focusability automatically. This is the default.
896     * <p>
897     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
898     * android:focusable}.
899     */
900    public static final int FOCUSABLE_AUTO = 0x00000010;
901
902    /**
903     * Mask for use with setFlags indicating bits used for focus.
904     */
905    private static final int FOCUSABLE_MASK = 0x00000011;
906
907    /**
908     * This view will adjust its padding to fit sytem windows (e.g. status bar)
909     */
910    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
911
912    /** @hide */
913    @IntDef({VISIBLE, INVISIBLE, GONE})
914    @Retention(RetentionPolicy.SOURCE)
915    public @interface Visibility {}
916
917    /**
918     * This view is visible.
919     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
920     * android:visibility}.
921     */
922    public static final int VISIBLE = 0x00000000;
923
924    /**
925     * This view is invisible, but it still takes up space for layout purposes.
926     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
927     * android:visibility}.
928     */
929    public static final int INVISIBLE = 0x00000004;
930
931    /**
932     * This view is invisible, and it doesn't take any space for layout
933     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
934     * android:visibility}.
935     */
936    public static final int GONE = 0x00000008;
937
938    /**
939     * Mask for use with setFlags indicating bits used for visibility.
940     * {@hide}
941     */
942    static final int VISIBILITY_MASK = 0x0000000C;
943
944    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
945
946    /** @hide */
947    @IntDef({
948            AUTO_FILL_MODE_INHERIT,
949            AUTO_FILL_MODE_AUTO,
950            AUTO_FILL_MODE_MANUAL
951    })
952    @Retention(RetentionPolicy.SOURCE)
953    public @interface AutoFillMode {}
954
955    /**
956     * This view inherits the autofill state from it's parent. If there is no parent it is
957     * {@link #AUTO_FILL_MODE_AUTO}.
958     * Use with {@link #setAutoFillMode(int)} and <a href="#attr_android:autoFillMode">
959     * {@code android:autoFillMode}.
960     */
961    public static final int AUTO_FILL_MODE_INHERIT = 0;
962
963    /**
964     * Allows this view to automatically trigger an auto-fill request when it get focus.
965     * Use with {@link #setAutoFillMode(int)} and <a href="#attr_android:autoFillMode">
966     * {@code android:autoFillMode}.
967     */
968    public static final int AUTO_FILL_MODE_AUTO = 1;
969
970    /**
971     * Require the user to manually force an auto-fill request.
972     * Use with {@link #setAutoFillMode(int)} and <a href="#attr_android:autoFillMode">{@code
973     * android:autoFillMode}.
974     */
975    public static final int AUTO_FILL_MODE_MANUAL = 2;
976
977    /**
978     * This view is enabled. Interpretation varies by subclass.
979     * Use with ENABLED_MASK when calling setFlags.
980     * {@hide}
981     */
982    static final int ENABLED = 0x00000000;
983
984    /**
985     * This view is disabled. Interpretation varies by subclass.
986     * Use with ENABLED_MASK when calling setFlags.
987     * {@hide}
988     */
989    static final int DISABLED = 0x00000020;
990
991   /**
992    * Mask for use with setFlags indicating bits used for indicating whether
993    * this view is enabled
994    * {@hide}
995    */
996    static final int ENABLED_MASK = 0x00000020;
997
998    /**
999     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
1000     * called and further optimizations will be performed. It is okay to have
1001     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
1002     * {@hide}
1003     */
1004    static final int WILL_NOT_DRAW = 0x00000080;
1005
1006    /**
1007     * Mask for use with setFlags indicating bits used for indicating whether
1008     * this view is will draw
1009     * {@hide}
1010     */
1011    static final int DRAW_MASK = 0x00000080;
1012
1013    /**
1014     * <p>This view doesn't show scrollbars.</p>
1015     * {@hide}
1016     */
1017    static final int SCROLLBARS_NONE = 0x00000000;
1018
1019    /**
1020     * <p>This view shows horizontal scrollbars.</p>
1021     * {@hide}
1022     */
1023    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
1024
1025    /**
1026     * <p>This view shows vertical scrollbars.</p>
1027     * {@hide}
1028     */
1029    static final int SCROLLBARS_VERTICAL = 0x00000200;
1030
1031    /**
1032     * <p>Mask for use with setFlags indicating bits used for indicating which
1033     * scrollbars are enabled.</p>
1034     * {@hide}
1035     */
1036    static final int SCROLLBARS_MASK = 0x00000300;
1037
1038    /**
1039     * Indicates that the view should filter touches when its window is obscured.
1040     * Refer to the class comments for more information about this security feature.
1041     * {@hide}
1042     */
1043    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1044
1045    /**
1046     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1047     * that they are optional and should be skipped if the window has
1048     * requested system UI flags that ignore those insets for layout.
1049     */
1050    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1051
1052    /**
1053     * <p>This view doesn't show fading edges.</p>
1054     * {@hide}
1055     */
1056    static final int FADING_EDGE_NONE = 0x00000000;
1057
1058    /**
1059     * <p>This view shows horizontal fading edges.</p>
1060     * {@hide}
1061     */
1062    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1063
1064    /**
1065     * <p>This view shows vertical fading edges.</p>
1066     * {@hide}
1067     */
1068    static final int FADING_EDGE_VERTICAL = 0x00002000;
1069
1070    /**
1071     * <p>Mask for use with setFlags indicating bits used for indicating which
1072     * fading edges are enabled.</p>
1073     * {@hide}
1074     */
1075    static final int FADING_EDGE_MASK = 0x00003000;
1076
1077    /**
1078     * <p>Indicates this view can be clicked. When clickable, a View reacts
1079     * to clicks by notifying the OnClickListener.<p>
1080     * {@hide}
1081     */
1082    static final int CLICKABLE = 0x00004000;
1083
1084    /**
1085     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1086     * {@hide}
1087     */
1088    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1089
1090    /**
1091     * <p>Indicates that no icicle should be saved for this view.<p>
1092     * {@hide}
1093     */
1094    static final int SAVE_DISABLED = 0x000010000;
1095
1096    /**
1097     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1098     * property.</p>
1099     * {@hide}
1100     */
1101    static final int SAVE_DISABLED_MASK = 0x000010000;
1102
1103    /**
1104     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1105     * {@hide}
1106     */
1107    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1108
1109    /**
1110     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1111     * {@hide}
1112     */
1113    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1114
1115    /** @hide */
1116    @Retention(RetentionPolicy.SOURCE)
1117    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1118    public @interface DrawingCacheQuality {}
1119
1120    /**
1121     * <p>Enables low quality mode for the drawing cache.</p>
1122     */
1123    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1124
1125    /**
1126     * <p>Enables high quality mode for the drawing cache.</p>
1127     */
1128    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1129
1130    /**
1131     * <p>Enables automatic quality mode for the drawing cache.</p>
1132     */
1133    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1134
1135    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1136            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1137    };
1138
1139    /**
1140     * <p>Mask for use with setFlags indicating bits used for the cache
1141     * quality property.</p>
1142     * {@hide}
1143     */
1144    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1145
1146    /**
1147     * <p>
1148     * Indicates this view can be long clicked. When long clickable, a View
1149     * reacts to long clicks by notifying the OnLongClickListener or showing a
1150     * context menu.
1151     * </p>
1152     * {@hide}
1153     */
1154    static final int LONG_CLICKABLE = 0x00200000;
1155
1156    /**
1157     * <p>Indicates that this view gets its drawable states from its direct parent
1158     * and ignores its original internal states.</p>
1159     *
1160     * @hide
1161     */
1162    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1163
1164    /**
1165     * <p>
1166     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1167     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1168     * OnContextClickListener.
1169     * </p>
1170     * {@hide}
1171     */
1172    static final int CONTEXT_CLICKABLE = 0x00800000;
1173
1174
1175    /** @hide */
1176    @IntDef({
1177        SCROLLBARS_INSIDE_OVERLAY,
1178        SCROLLBARS_INSIDE_INSET,
1179        SCROLLBARS_OUTSIDE_OVERLAY,
1180        SCROLLBARS_OUTSIDE_INSET
1181    })
1182    @Retention(RetentionPolicy.SOURCE)
1183    public @interface ScrollBarStyle {}
1184
1185    /**
1186     * The scrollbar style to display the scrollbars inside the content area,
1187     * without increasing the padding. The scrollbars will be overlaid with
1188     * translucency on the view's content.
1189     */
1190    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1191
1192    /**
1193     * The scrollbar style to display the scrollbars inside the padded area,
1194     * increasing the padding of the view. The scrollbars will not overlap the
1195     * content area of the view.
1196     */
1197    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1198
1199    /**
1200     * The scrollbar style to display the scrollbars at the edge of the view,
1201     * without increasing the padding. The scrollbars will be overlaid with
1202     * translucency.
1203     */
1204    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1205
1206    /**
1207     * The scrollbar style to display the scrollbars at the edge of the view,
1208     * increasing the padding of the view. The scrollbars will only overlap the
1209     * background, if any.
1210     */
1211    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1212
1213    /**
1214     * Mask to check if the scrollbar style is overlay or inset.
1215     * {@hide}
1216     */
1217    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1218
1219    /**
1220     * Mask to check if the scrollbar style is inside or outside.
1221     * {@hide}
1222     */
1223    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1224
1225    /**
1226     * Mask for scrollbar style.
1227     * {@hide}
1228     */
1229    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1230
1231    /**
1232     * View flag indicating that the screen should remain on while the
1233     * window containing this view is visible to the user.  This effectively
1234     * takes care of automatically setting the WindowManager's
1235     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1236     */
1237    public static final int KEEP_SCREEN_ON = 0x04000000;
1238
1239    /**
1240     * View flag indicating whether this view should have sound effects enabled
1241     * for events such as clicking and touching.
1242     */
1243    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1244
1245    /**
1246     * View flag indicating whether this view should have haptic feedback
1247     * enabled for events such as long presses.
1248     */
1249    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1250
1251    /**
1252     * <p>Indicates that the view hierarchy should stop saving state when
1253     * it reaches this view.  If state saving is initiated immediately at
1254     * the view, it will be allowed.
1255     * {@hide}
1256     */
1257    static final int PARENT_SAVE_DISABLED = 0x20000000;
1258
1259    /**
1260     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1261     * {@hide}
1262     */
1263    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1264
1265    private static Paint sDebugPaint;
1266
1267    /**
1268     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1269     * {@hide}
1270     */
1271    static final int TOOLTIP = 0x40000000;
1272
1273    /** @hide */
1274    @IntDef(flag = true,
1275            value = {
1276                FOCUSABLES_ALL,
1277                FOCUSABLES_TOUCH_MODE
1278            })
1279    @Retention(RetentionPolicy.SOURCE)
1280    public @interface FocusableMode {}
1281
1282    /**
1283     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1284     * should add all focusable Views regardless if they are focusable in touch mode.
1285     */
1286    public static final int FOCUSABLES_ALL = 0x00000000;
1287
1288    /**
1289     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1290     * should add only Views focusable in touch mode.
1291     */
1292    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1293
1294    /** @hide */
1295    @IntDef({
1296            FOCUS_BACKWARD,
1297            FOCUS_FORWARD,
1298            FOCUS_LEFT,
1299            FOCUS_UP,
1300            FOCUS_RIGHT,
1301            FOCUS_DOWN
1302    })
1303    @Retention(RetentionPolicy.SOURCE)
1304    public @interface FocusDirection {}
1305
1306    /** @hide */
1307    @IntDef({
1308            FOCUS_LEFT,
1309            FOCUS_UP,
1310            FOCUS_RIGHT,
1311            FOCUS_DOWN
1312    })
1313    @Retention(RetentionPolicy.SOURCE)
1314    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1315
1316    /**
1317     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1318     * item.
1319     */
1320    public static final int FOCUS_BACKWARD = 0x00000001;
1321
1322    /**
1323     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1324     * item.
1325     */
1326    public static final int FOCUS_FORWARD = 0x00000002;
1327
1328    /**
1329     * Use with {@link #focusSearch(int)}. Move focus to the left.
1330     */
1331    public static final int FOCUS_LEFT = 0x00000011;
1332
1333    /**
1334     * Use with {@link #focusSearch(int)}. Move focus up.
1335     */
1336    public static final int FOCUS_UP = 0x00000021;
1337
1338    /**
1339     * Use with {@link #focusSearch(int)}. Move focus to the right.
1340     */
1341    public static final int FOCUS_RIGHT = 0x00000042;
1342
1343    /**
1344     * Use with {@link #focusSearch(int)}. Move focus down.
1345     */
1346    public static final int FOCUS_DOWN = 0x00000082;
1347
1348    /**
1349     * Bits of {@link #getMeasuredWidthAndState()} and
1350     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1351     */
1352    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1353
1354    /**
1355     * Bits of {@link #getMeasuredWidthAndState()} and
1356     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1357     */
1358    public static final int MEASURED_STATE_MASK = 0xff000000;
1359
1360    /**
1361     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1362     * for functions that combine both width and height into a single int,
1363     * such as {@link #getMeasuredState()} and the childState argument of
1364     * {@link #resolveSizeAndState(int, int, int)}.
1365     */
1366    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1367
1368    /**
1369     * Bit of {@link #getMeasuredWidthAndState()} and
1370     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1371     * is smaller that the space the view would like to have.
1372     */
1373    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1374
1375    /**
1376     * Base View state sets
1377     */
1378    // Singles
1379    /**
1380     * Indicates the view has no states set. States are used with
1381     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1382     * view depending on its state.
1383     *
1384     * @see android.graphics.drawable.Drawable
1385     * @see #getDrawableState()
1386     */
1387    protected static final int[] EMPTY_STATE_SET;
1388    /**
1389     * Indicates the view is enabled. States are used with
1390     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1391     * view depending on its state.
1392     *
1393     * @see android.graphics.drawable.Drawable
1394     * @see #getDrawableState()
1395     */
1396    protected static final int[] ENABLED_STATE_SET;
1397    /**
1398     * Indicates the view is focused. States are used with
1399     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1400     * view depending on its state.
1401     *
1402     * @see android.graphics.drawable.Drawable
1403     * @see #getDrawableState()
1404     */
1405    protected static final int[] FOCUSED_STATE_SET;
1406    /**
1407     * Indicates the view is selected. States are used with
1408     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1409     * view depending on its state.
1410     *
1411     * @see android.graphics.drawable.Drawable
1412     * @see #getDrawableState()
1413     */
1414    protected static final int[] SELECTED_STATE_SET;
1415    /**
1416     * Indicates the view is pressed. States are used with
1417     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1418     * view depending on its state.
1419     *
1420     * @see android.graphics.drawable.Drawable
1421     * @see #getDrawableState()
1422     */
1423    protected static final int[] PRESSED_STATE_SET;
1424    /**
1425     * Indicates the view's window has focus. States are used with
1426     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1427     * view depending on its state.
1428     *
1429     * @see android.graphics.drawable.Drawable
1430     * @see #getDrawableState()
1431     */
1432    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1433    // Doubles
1434    /**
1435     * Indicates the view is enabled and has the focus.
1436     *
1437     * @see #ENABLED_STATE_SET
1438     * @see #FOCUSED_STATE_SET
1439     */
1440    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1441    /**
1442     * Indicates the view is enabled and selected.
1443     *
1444     * @see #ENABLED_STATE_SET
1445     * @see #SELECTED_STATE_SET
1446     */
1447    protected static final int[] ENABLED_SELECTED_STATE_SET;
1448    /**
1449     * Indicates the view is enabled and that its window has focus.
1450     *
1451     * @see #ENABLED_STATE_SET
1452     * @see #WINDOW_FOCUSED_STATE_SET
1453     */
1454    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1455    /**
1456     * Indicates the view is focused and selected.
1457     *
1458     * @see #FOCUSED_STATE_SET
1459     * @see #SELECTED_STATE_SET
1460     */
1461    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1462    /**
1463     * Indicates the view has the focus and that its window has the focus.
1464     *
1465     * @see #FOCUSED_STATE_SET
1466     * @see #WINDOW_FOCUSED_STATE_SET
1467     */
1468    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1469    /**
1470     * Indicates the view is selected and that its window has the focus.
1471     *
1472     * @see #SELECTED_STATE_SET
1473     * @see #WINDOW_FOCUSED_STATE_SET
1474     */
1475    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1476    // Triples
1477    /**
1478     * Indicates the view is enabled, focused and selected.
1479     *
1480     * @see #ENABLED_STATE_SET
1481     * @see #FOCUSED_STATE_SET
1482     * @see #SELECTED_STATE_SET
1483     */
1484    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1485    /**
1486     * Indicates the view is enabled, focused and its window has the focus.
1487     *
1488     * @see #ENABLED_STATE_SET
1489     * @see #FOCUSED_STATE_SET
1490     * @see #WINDOW_FOCUSED_STATE_SET
1491     */
1492    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1493    /**
1494     * Indicates the view is enabled, selected and its window has the focus.
1495     *
1496     * @see #ENABLED_STATE_SET
1497     * @see #SELECTED_STATE_SET
1498     * @see #WINDOW_FOCUSED_STATE_SET
1499     */
1500    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1501    /**
1502     * Indicates the view is focused, selected and its window has the focus.
1503     *
1504     * @see #FOCUSED_STATE_SET
1505     * @see #SELECTED_STATE_SET
1506     * @see #WINDOW_FOCUSED_STATE_SET
1507     */
1508    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1509    /**
1510     * Indicates the view is enabled, focused, selected and its window
1511     * has the focus.
1512     *
1513     * @see #ENABLED_STATE_SET
1514     * @see #FOCUSED_STATE_SET
1515     * @see #SELECTED_STATE_SET
1516     * @see #WINDOW_FOCUSED_STATE_SET
1517     */
1518    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1519    /**
1520     * Indicates the view is pressed and its window has the focus.
1521     *
1522     * @see #PRESSED_STATE_SET
1523     * @see #WINDOW_FOCUSED_STATE_SET
1524     */
1525    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1526    /**
1527     * Indicates the view is pressed and selected.
1528     *
1529     * @see #PRESSED_STATE_SET
1530     * @see #SELECTED_STATE_SET
1531     */
1532    protected static final int[] PRESSED_SELECTED_STATE_SET;
1533    /**
1534     * Indicates the view is pressed, selected and its window has the focus.
1535     *
1536     * @see #PRESSED_STATE_SET
1537     * @see #SELECTED_STATE_SET
1538     * @see #WINDOW_FOCUSED_STATE_SET
1539     */
1540    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1541    /**
1542     * Indicates the view is pressed and focused.
1543     *
1544     * @see #PRESSED_STATE_SET
1545     * @see #FOCUSED_STATE_SET
1546     */
1547    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1548    /**
1549     * Indicates the view is pressed, focused and its window has the focus.
1550     *
1551     * @see #PRESSED_STATE_SET
1552     * @see #FOCUSED_STATE_SET
1553     * @see #WINDOW_FOCUSED_STATE_SET
1554     */
1555    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1556    /**
1557     * Indicates the view is pressed, focused and selected.
1558     *
1559     * @see #PRESSED_STATE_SET
1560     * @see #SELECTED_STATE_SET
1561     * @see #FOCUSED_STATE_SET
1562     */
1563    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1564    /**
1565     * Indicates the view is pressed, focused, selected and its window has the focus.
1566     *
1567     * @see #PRESSED_STATE_SET
1568     * @see #FOCUSED_STATE_SET
1569     * @see #SELECTED_STATE_SET
1570     * @see #WINDOW_FOCUSED_STATE_SET
1571     */
1572    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1573    /**
1574     * Indicates the view is pressed and enabled.
1575     *
1576     * @see #PRESSED_STATE_SET
1577     * @see #ENABLED_STATE_SET
1578     */
1579    protected static final int[] PRESSED_ENABLED_STATE_SET;
1580    /**
1581     * Indicates the view is pressed, enabled and its window has the focus.
1582     *
1583     * @see #PRESSED_STATE_SET
1584     * @see #ENABLED_STATE_SET
1585     * @see #WINDOW_FOCUSED_STATE_SET
1586     */
1587    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1588    /**
1589     * Indicates the view is pressed, enabled and selected.
1590     *
1591     * @see #PRESSED_STATE_SET
1592     * @see #ENABLED_STATE_SET
1593     * @see #SELECTED_STATE_SET
1594     */
1595    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1596    /**
1597     * Indicates the view is pressed, enabled, selected and its window has the
1598     * focus.
1599     *
1600     * @see #PRESSED_STATE_SET
1601     * @see #ENABLED_STATE_SET
1602     * @see #SELECTED_STATE_SET
1603     * @see #WINDOW_FOCUSED_STATE_SET
1604     */
1605    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1606    /**
1607     * Indicates the view is pressed, enabled and focused.
1608     *
1609     * @see #PRESSED_STATE_SET
1610     * @see #ENABLED_STATE_SET
1611     * @see #FOCUSED_STATE_SET
1612     */
1613    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1614    /**
1615     * Indicates the view is pressed, enabled, focused and its window has the
1616     * focus.
1617     *
1618     * @see #PRESSED_STATE_SET
1619     * @see #ENABLED_STATE_SET
1620     * @see #FOCUSED_STATE_SET
1621     * @see #WINDOW_FOCUSED_STATE_SET
1622     */
1623    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1624    /**
1625     * Indicates the view is pressed, enabled, focused and selected.
1626     *
1627     * @see #PRESSED_STATE_SET
1628     * @see #ENABLED_STATE_SET
1629     * @see #SELECTED_STATE_SET
1630     * @see #FOCUSED_STATE_SET
1631     */
1632    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1633    /**
1634     * Indicates the view is pressed, enabled, focused, selected and its window
1635     * has the focus.
1636     *
1637     * @see #PRESSED_STATE_SET
1638     * @see #ENABLED_STATE_SET
1639     * @see #SELECTED_STATE_SET
1640     * @see #FOCUSED_STATE_SET
1641     * @see #WINDOW_FOCUSED_STATE_SET
1642     */
1643    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1644
1645    static {
1646        EMPTY_STATE_SET = StateSet.get(0);
1647
1648        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1649
1650        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1651        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1652                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1653
1654        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1655        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1656                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1657        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1658                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1659        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1660                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1661                        | StateSet.VIEW_STATE_FOCUSED);
1662
1663        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1664        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1665                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1666        ENABLED_SELECTED_STATE_SET = StateSet.get(
1667                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1668        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1669                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1670                        | StateSet.VIEW_STATE_ENABLED);
1671        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1672                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1673        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1674                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1675                        | StateSet.VIEW_STATE_ENABLED);
1676        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1677                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1678                        | StateSet.VIEW_STATE_ENABLED);
1679        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1680                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1681                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1682
1683        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1684        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1685                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1686        PRESSED_SELECTED_STATE_SET = StateSet.get(
1687                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1688        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1689                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1690                        | StateSet.VIEW_STATE_PRESSED);
1691        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1692                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1693        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1694                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1695                        | StateSet.VIEW_STATE_PRESSED);
1696        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1697                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1698                        | StateSet.VIEW_STATE_PRESSED);
1699        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1700                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1701                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1702        PRESSED_ENABLED_STATE_SET = StateSet.get(
1703                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1704        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1705                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1706                        | StateSet.VIEW_STATE_PRESSED);
1707        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1708                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1709                        | StateSet.VIEW_STATE_PRESSED);
1710        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1711                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1712                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1713        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1714                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1715                        | StateSet.VIEW_STATE_PRESSED);
1716        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1717                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1718                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1719        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1720                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1721                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1722        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1723                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1724                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1725                        | StateSet.VIEW_STATE_PRESSED);
1726    }
1727
1728    /**
1729     * Accessibility event types that are dispatched for text population.
1730     */
1731    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1732            AccessibilityEvent.TYPE_VIEW_CLICKED
1733            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1734            | AccessibilityEvent.TYPE_VIEW_SELECTED
1735            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1736            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1737            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1738            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1739            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1740            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1741            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1742            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1743
1744    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
1745
1746    static final int DEBUG_CORNERS_SIZE_DIP = 8;
1747
1748    /**
1749     * Temporary Rect currently for use in setBackground().  This will probably
1750     * be extended in the future to hold our own class with more than just
1751     * a Rect. :)
1752     */
1753    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1754
1755    /**
1756     * Map used to store views' tags.
1757     */
1758    private SparseArray<Object> mKeyedTags;
1759
1760    /**
1761     * The next available accessibility id.
1762     */
1763    private static int sNextAccessibilityViewId;
1764
1765    /**
1766     * The animation currently associated with this view.
1767     * @hide
1768     */
1769    protected Animation mCurrentAnimation = null;
1770
1771    /**
1772     * Width as measured during measure pass.
1773     * {@hide}
1774     */
1775    @ViewDebug.ExportedProperty(category = "measurement")
1776    int mMeasuredWidth;
1777
1778    /**
1779     * Height as measured during measure pass.
1780     * {@hide}
1781     */
1782    @ViewDebug.ExportedProperty(category = "measurement")
1783    int mMeasuredHeight;
1784
1785    /**
1786     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1787     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1788     * its display list. This flag, used only when hw accelerated, allows us to clear the
1789     * flag while retaining this information until it's needed (at getDisplayList() time and
1790     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1791     *
1792     * {@hide}
1793     */
1794    boolean mRecreateDisplayList = false;
1795
1796    /**
1797     * The view's identifier.
1798     * {@hide}
1799     *
1800     * @see #setId(int)
1801     * @see #getId()
1802     */
1803    @IdRes
1804    @ViewDebug.ExportedProperty(resolveId = true)
1805    int mID = NO_ID;
1806
1807    /**
1808     * The stable ID of this view for accessibility purposes.
1809     */
1810    int mAccessibilityViewId = NO_ID;
1811
1812    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1813
1814    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1815
1816    /**
1817     * The view's tag.
1818     * {@hide}
1819     *
1820     * @see #setTag(Object)
1821     * @see #getTag()
1822     */
1823    protected Object mTag = null;
1824
1825    // for mPrivateFlags:
1826    /** {@hide} */
1827    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1828    /** {@hide} */
1829    static final int PFLAG_FOCUSED                     = 0x00000002;
1830    /** {@hide} */
1831    static final int PFLAG_SELECTED                    = 0x00000004;
1832    /** {@hide} */
1833    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1834    /** {@hide} */
1835    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1836    /** {@hide} */
1837    static final int PFLAG_DRAWN                       = 0x00000020;
1838    /**
1839     * When this flag is set, this view is running an animation on behalf of its
1840     * children and should therefore not cancel invalidate requests, even if they
1841     * lie outside of this view's bounds.
1842     *
1843     * {@hide}
1844     */
1845    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1846    /** {@hide} */
1847    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1848    /** {@hide} */
1849    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1850    /** {@hide} */
1851    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1852    /** {@hide} */
1853    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1854    /** {@hide} */
1855    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1856    /** {@hide} */
1857    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1858
1859    private static final int PFLAG_PRESSED             = 0x00004000;
1860
1861    /** {@hide} */
1862    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1863    /**
1864     * Flag used to indicate that this view should be drawn once more (and only once
1865     * more) after its animation has completed.
1866     * {@hide}
1867     */
1868    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1869
1870    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1871
1872    /**
1873     * Indicates that the View returned true when onSetAlpha() was called and that
1874     * the alpha must be restored.
1875     * {@hide}
1876     */
1877    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1878
1879    /**
1880     * Set by {@link #setScrollContainer(boolean)}.
1881     */
1882    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1883
1884    /**
1885     * Set by {@link #setScrollContainer(boolean)}.
1886     */
1887    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1888
1889    /**
1890     * View flag indicating whether this view was invalidated (fully or partially.)
1891     *
1892     * @hide
1893     */
1894    static final int PFLAG_DIRTY                       = 0x00200000;
1895
1896    /**
1897     * View flag indicating whether this view was invalidated by an opaque
1898     * invalidate request.
1899     *
1900     * @hide
1901     */
1902    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1903
1904    /**
1905     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1906     *
1907     * @hide
1908     */
1909    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1910
1911    /**
1912     * Indicates whether the background is opaque.
1913     *
1914     * @hide
1915     */
1916    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1917
1918    /**
1919     * Indicates whether the scrollbars are opaque.
1920     *
1921     * @hide
1922     */
1923    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1924
1925    /**
1926     * Indicates whether the view is opaque.
1927     *
1928     * @hide
1929     */
1930    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1931
1932    /**
1933     * Indicates a prepressed state;
1934     * the short time between ACTION_DOWN and recognizing
1935     * a 'real' press. Prepressed is used to recognize quick taps
1936     * even when they are shorter than ViewConfiguration.getTapTimeout().
1937     *
1938     * @hide
1939     */
1940    private static final int PFLAG_PREPRESSED          = 0x02000000;
1941
1942    /**
1943     * Indicates whether the view is temporarily detached.
1944     *
1945     * @hide
1946     */
1947    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1948
1949    /**
1950     * Indicates that we should awaken scroll bars once attached
1951     *
1952     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1953     * during window attachment and it is no longer needed. Feel free to repurpose it.
1954     *
1955     * @hide
1956     */
1957    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1958
1959    /**
1960     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1961     * @hide
1962     */
1963    private static final int PFLAG_HOVERED             = 0x10000000;
1964
1965    /**
1966     * no longer needed, should be reused
1967     */
1968    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1969
1970    /** {@hide} */
1971    static final int PFLAG_ACTIVATED                   = 0x40000000;
1972
1973    /**
1974     * Indicates that this view was specifically invalidated, not just dirtied because some
1975     * child view was invalidated. The flag is used to determine when we need to recreate
1976     * a view's display list (as opposed to just returning a reference to its existing
1977     * display list).
1978     *
1979     * @hide
1980     */
1981    static final int PFLAG_INVALIDATED                 = 0x80000000;
1982
1983    /**
1984     * Masks for mPrivateFlags2, as generated by dumpFlags():
1985     *
1986     * |-------|-------|-------|-------|
1987     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1988     *                                1  PFLAG2_DRAG_HOVERED
1989     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1990     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1991     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1992     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1993     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1994     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1995     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1996     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1997     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1998     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1999     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
2000     *                         111       PFLAG2_TEXT_DIRECTION_MASK
2001     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
2002     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
2003     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
2004     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
2005     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
2006     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
2007     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
2008     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
2009     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
2010     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
2011     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
2012     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
2013     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
2014     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
2015     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
2016     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
2017     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
2018     *     1                             PFLAG2_VIEW_QUICK_REJECTED
2019     *    1                              PFLAG2_PADDING_RESOLVED
2020     *   1                               PFLAG2_DRAWABLE_RESOLVED
2021     *  1                                PFLAG2_HAS_TRANSIENT_STATE
2022     * |-------|-------|-------|-------|
2023     */
2024
2025    /**
2026     * Indicates that this view has reported that it can accept the current drag's content.
2027     * Cleared when the drag operation concludes.
2028     * @hide
2029     */
2030    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
2031
2032    /**
2033     * Indicates that this view is currently directly under the drag location in a
2034     * drag-and-drop operation involving content that it can accept.  Cleared when
2035     * the drag exits the view, or when the drag operation concludes.
2036     * @hide
2037     */
2038    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
2039
2040    /** @hide */
2041    @IntDef({
2042        LAYOUT_DIRECTION_LTR,
2043        LAYOUT_DIRECTION_RTL,
2044        LAYOUT_DIRECTION_INHERIT,
2045        LAYOUT_DIRECTION_LOCALE
2046    })
2047    @Retention(RetentionPolicy.SOURCE)
2048    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2049    public @interface LayoutDir {}
2050
2051    /** @hide */
2052    @IntDef({
2053        LAYOUT_DIRECTION_LTR,
2054        LAYOUT_DIRECTION_RTL
2055    })
2056    @Retention(RetentionPolicy.SOURCE)
2057    public @interface ResolvedLayoutDir {}
2058
2059    /**
2060     * A flag to indicate that the layout direction of this view has not been defined yet.
2061     * @hide
2062     */
2063    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2064
2065    /**
2066     * Horizontal layout direction of this view is from Left to Right.
2067     * Use with {@link #setLayoutDirection}.
2068     */
2069    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2070
2071    /**
2072     * Horizontal layout direction of this view is from Right to Left.
2073     * Use with {@link #setLayoutDirection}.
2074     */
2075    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2076
2077    /**
2078     * Horizontal layout direction of this view is inherited from its parent.
2079     * Use with {@link #setLayoutDirection}.
2080     */
2081    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2082
2083    /**
2084     * Horizontal layout direction of this view is from deduced from the default language
2085     * script for the locale. Use with {@link #setLayoutDirection}.
2086     */
2087    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2088
2089    /**
2090     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2091     * @hide
2092     */
2093    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2094
2095    /**
2096     * Mask for use with private flags indicating bits used for horizontal layout direction.
2097     * @hide
2098     */
2099    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2100
2101    /**
2102     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2103     * right-to-left direction.
2104     * @hide
2105     */
2106    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2107
2108    /**
2109     * Indicates whether the view horizontal layout direction has been resolved.
2110     * @hide
2111     */
2112    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2113
2114    /**
2115     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2116     * @hide
2117     */
2118    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2119            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2120
2121    /*
2122     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2123     * flag value.
2124     * @hide
2125     */
2126    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2127            LAYOUT_DIRECTION_LTR,
2128            LAYOUT_DIRECTION_RTL,
2129            LAYOUT_DIRECTION_INHERIT,
2130            LAYOUT_DIRECTION_LOCALE
2131    };
2132
2133    /**
2134     * Default horizontal layout direction.
2135     */
2136    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2137
2138    /**
2139     * Default horizontal layout direction.
2140     * @hide
2141     */
2142    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2143
2144    /**
2145     * Text direction is inherited through {@link ViewGroup}
2146     */
2147    public static final int TEXT_DIRECTION_INHERIT = 0;
2148
2149    /**
2150     * Text direction is using "first strong algorithm". The first strong directional character
2151     * determines the paragraph direction. If there is no strong directional character, the
2152     * paragraph direction is the view's resolved layout direction.
2153     */
2154    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2155
2156    /**
2157     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2158     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2159     * If there are neither, the paragraph direction is the view's resolved layout direction.
2160     */
2161    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2162
2163    /**
2164     * Text direction is forced to LTR.
2165     */
2166    public static final int TEXT_DIRECTION_LTR = 3;
2167
2168    /**
2169     * Text direction is forced to RTL.
2170     */
2171    public static final int TEXT_DIRECTION_RTL = 4;
2172
2173    /**
2174     * Text direction is coming from the system Locale.
2175     */
2176    public static final int TEXT_DIRECTION_LOCALE = 5;
2177
2178    /**
2179     * Text direction is using "first strong algorithm". The first strong directional character
2180     * determines the paragraph direction. If there is no strong directional character, the
2181     * paragraph direction is LTR.
2182     */
2183    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2184
2185    /**
2186     * Text direction is using "first strong algorithm". The first strong directional character
2187     * determines the paragraph direction. If there is no strong directional character, the
2188     * paragraph direction is RTL.
2189     */
2190    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2191
2192    /**
2193     * Default text direction is inherited
2194     */
2195    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2196
2197    /**
2198     * Default resolved text direction
2199     * @hide
2200     */
2201    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2202
2203    /**
2204     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2205     * @hide
2206     */
2207    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2208
2209    /**
2210     * Mask for use with private flags indicating bits used for text direction.
2211     * @hide
2212     */
2213    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2214            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2215
2216    /**
2217     * Array of text direction flags for mapping attribute "textDirection" to correct
2218     * flag value.
2219     * @hide
2220     */
2221    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2222            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2223            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2224            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2225            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2226            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2227            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2228            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2229            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2230    };
2231
2232    /**
2233     * Indicates whether the view text direction has been resolved.
2234     * @hide
2235     */
2236    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2237            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2238
2239    /**
2240     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2241     * @hide
2242     */
2243    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2244
2245    /**
2246     * Mask for use with private flags indicating bits used for resolved text direction.
2247     * @hide
2248     */
2249    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2250            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2251
2252    /**
2253     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2254     * @hide
2255     */
2256    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2257            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2258
2259    /** @hide */
2260    @IntDef({
2261        TEXT_ALIGNMENT_INHERIT,
2262        TEXT_ALIGNMENT_GRAVITY,
2263        TEXT_ALIGNMENT_CENTER,
2264        TEXT_ALIGNMENT_TEXT_START,
2265        TEXT_ALIGNMENT_TEXT_END,
2266        TEXT_ALIGNMENT_VIEW_START,
2267        TEXT_ALIGNMENT_VIEW_END
2268    })
2269    @Retention(RetentionPolicy.SOURCE)
2270    public @interface TextAlignment {}
2271
2272    /**
2273     * Default text alignment. The text alignment of this View is inherited from its parent.
2274     * Use with {@link #setTextAlignment(int)}
2275     */
2276    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2277
2278    /**
2279     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2280     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2281     *
2282     * Use with {@link #setTextAlignment(int)}
2283     */
2284    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2285
2286    /**
2287     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2288     *
2289     * Use with {@link #setTextAlignment(int)}
2290     */
2291    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2292
2293    /**
2294     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2295     *
2296     * Use with {@link #setTextAlignment(int)}
2297     */
2298    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2299
2300    /**
2301     * Center the paragraph, e.g. ALIGN_CENTER.
2302     *
2303     * Use with {@link #setTextAlignment(int)}
2304     */
2305    public static final int TEXT_ALIGNMENT_CENTER = 4;
2306
2307    /**
2308     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2309     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2310     *
2311     * Use with {@link #setTextAlignment(int)}
2312     */
2313    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2314
2315    /**
2316     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2317     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2318     *
2319     * Use with {@link #setTextAlignment(int)}
2320     */
2321    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2322
2323    /**
2324     * Default text alignment is inherited
2325     */
2326    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2327
2328    /**
2329     * Default resolved text alignment
2330     * @hide
2331     */
2332    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2333
2334    /**
2335      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2336      * @hide
2337      */
2338    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2339
2340    /**
2341      * Mask for use with private flags indicating bits used for text alignment.
2342      * @hide
2343      */
2344    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2345
2346    /**
2347     * Array of text direction flags for mapping attribute "textAlignment" to correct
2348     * flag value.
2349     * @hide
2350     */
2351    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2352            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2353            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2354            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2355            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2356            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2357            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2358            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2359    };
2360
2361    /**
2362     * Indicates whether the view text alignment has been resolved.
2363     * @hide
2364     */
2365    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2366
2367    /**
2368     * Bit shift to get the resolved text alignment.
2369     * @hide
2370     */
2371    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2372
2373    /**
2374     * Mask for use with private flags indicating bits used for text alignment.
2375     * @hide
2376     */
2377    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2378            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2379
2380    /**
2381     * Indicates whether if the view text alignment has been resolved to gravity
2382     */
2383    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2384            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2385
2386    // Accessiblity constants for mPrivateFlags2
2387
2388    /**
2389     * Shift for the bits in {@link #mPrivateFlags2} related to the
2390     * "importantForAccessibility" attribute.
2391     */
2392    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2393
2394    /**
2395     * Automatically determine whether a view is important for accessibility.
2396     */
2397    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2398
2399    /**
2400     * The view is important for accessibility.
2401     */
2402    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2403
2404    /**
2405     * The view is not important for accessibility.
2406     */
2407    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2408
2409    /**
2410     * The view is not important for accessibility, nor are any of its
2411     * descendant views.
2412     */
2413    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2414
2415    /**
2416     * The default whether the view is important for accessibility.
2417     */
2418    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2419
2420    /**
2421     * Mask for obtaining the bits which specify how to determine
2422     * whether a view is important for accessibility.
2423     */
2424    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2425        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2426        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2427        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2428
2429    /**
2430     * Shift for the bits in {@link #mPrivateFlags2} related to the
2431     * "accessibilityLiveRegion" attribute.
2432     */
2433    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2434
2435    /**
2436     * Live region mode specifying that accessibility services should not
2437     * automatically announce changes to this view. This is the default live
2438     * region mode for most views.
2439     * <p>
2440     * Use with {@link #setAccessibilityLiveRegion(int)}.
2441     */
2442    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2443
2444    /**
2445     * Live region mode specifying that accessibility services should announce
2446     * changes to this view.
2447     * <p>
2448     * Use with {@link #setAccessibilityLiveRegion(int)}.
2449     */
2450    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2451
2452    /**
2453     * Live region mode specifying that accessibility services should interrupt
2454     * ongoing speech to immediately announce changes to this view.
2455     * <p>
2456     * Use with {@link #setAccessibilityLiveRegion(int)}.
2457     */
2458    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2459
2460    /**
2461     * The default whether the view is important for accessibility.
2462     */
2463    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2464
2465    /**
2466     * Mask for obtaining the bits which specify a view's accessibility live
2467     * region mode.
2468     */
2469    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2470            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2471            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2472
2473    /**
2474     * Flag indicating whether a view has accessibility focus.
2475     */
2476    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2477
2478    /**
2479     * Flag whether the accessibility state of the subtree rooted at this view changed.
2480     */
2481    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2482
2483    /**
2484     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2485     * is used to check whether later changes to the view's transform should invalidate the
2486     * view to force the quickReject test to run again.
2487     */
2488    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2489
2490    /**
2491     * Flag indicating that start/end padding has been resolved into left/right padding
2492     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2493     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2494     * during measurement. In some special cases this is required such as when an adapter-based
2495     * view measures prospective children without attaching them to a window.
2496     */
2497    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2498
2499    /**
2500     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2501     */
2502    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2503
2504    /**
2505     * Indicates that the view is tracking some sort of transient state
2506     * that the app should not need to be aware of, but that the framework
2507     * should take special care to preserve.
2508     */
2509    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2510
2511    /**
2512     * Group of bits indicating that RTL properties resolution is done.
2513     */
2514    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2515            PFLAG2_TEXT_DIRECTION_RESOLVED |
2516            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2517            PFLAG2_PADDING_RESOLVED |
2518            PFLAG2_DRAWABLE_RESOLVED;
2519
2520    // There are a couple of flags left in mPrivateFlags2
2521
2522    /* End of masks for mPrivateFlags2 */
2523
2524    /**
2525     * Masks for mPrivateFlags3, as generated by dumpFlags():
2526     *
2527     * |-------|-------|-------|-------|
2528     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2529     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2530     *                               1   PFLAG3_IS_LAID_OUT
2531     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2532     *                             1     PFLAG3_CALLED_SUPER
2533     *                            1      PFLAG3_APPLYING_INSETS
2534     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2535     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2536     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2537     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2538     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2539     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2540     *                     1             PFLAG3_SCROLL_INDICATOR_START
2541     *                    1              PFLAG3_SCROLL_INDICATOR_END
2542     *                   1               PFLAG3_ASSIST_BLOCKED
2543     *                  1                PFLAG3_CLUSTER
2544     *                 x                 * NO LONGER NEEDED, SHOULD BE REUSED *
2545     *                1                  PFLAG3_FINGER_DOWN
2546     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2547     *             11                    PFLAG3_AUTO_FILL_MODE_MASK
2548     *           xx                      * NO LONGER NEEDED, SHOULD BE REUSED *
2549     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2550     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2551     *        1                          PFLAG3_TEMPORARY_DETACH
2552     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2553     * |-------|-------|-------|-------|
2554     */
2555
2556    /**
2557     * Flag indicating that view has a transform animation set on it. This is used to track whether
2558     * an animation is cleared between successive frames, in order to tell the associated
2559     * DisplayList to clear its animation matrix.
2560     */
2561    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2562
2563    /**
2564     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2565     * animation is cleared between successive frames, in order to tell the associated
2566     * DisplayList to restore its alpha value.
2567     */
2568    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2569
2570    /**
2571     * Flag indicating that the view has been through at least one layout since it
2572     * was last attached to a window.
2573     */
2574    static final int PFLAG3_IS_LAID_OUT = 0x4;
2575
2576    /**
2577     * Flag indicating that a call to measure() was skipped and should be done
2578     * instead when layout() is invoked.
2579     */
2580    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2581
2582    /**
2583     * Flag indicating that an overridden method correctly called down to
2584     * the superclass implementation as required by the API spec.
2585     */
2586    static final int PFLAG3_CALLED_SUPER = 0x10;
2587
2588    /**
2589     * Flag indicating that we're in the process of applying window insets.
2590     */
2591    static final int PFLAG3_APPLYING_INSETS = 0x20;
2592
2593    /**
2594     * Flag indicating that we're in the process of fitting system windows using the old method.
2595     */
2596    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2597
2598    /**
2599     * Flag indicating that nested scrolling is enabled for this view.
2600     * The view will optionally cooperate with views up its parent chain to allow for
2601     * integrated nested scrolling along the same axis.
2602     */
2603    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2604
2605    /**
2606     * Flag indicating that the bottom scroll indicator should be displayed
2607     * when this view can scroll up.
2608     */
2609    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2610
2611    /**
2612     * Flag indicating that the bottom scroll indicator should be displayed
2613     * when this view can scroll down.
2614     */
2615    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2616
2617    /**
2618     * Flag indicating that the left scroll indicator should be displayed
2619     * when this view can scroll left.
2620     */
2621    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2622
2623    /**
2624     * Flag indicating that the right scroll indicator should be displayed
2625     * when this view can scroll right.
2626     */
2627    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2628
2629    /**
2630     * Flag indicating that the start scroll indicator should be displayed
2631     * when this view can scroll in the start direction.
2632     */
2633    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2634
2635    /**
2636     * Flag indicating that the end scroll indicator should be displayed
2637     * when this view can scroll in the end direction.
2638     */
2639    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2640
2641    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2642
2643    static final int SCROLL_INDICATORS_NONE = 0x0000;
2644
2645    /**
2646     * Mask for use with setFlags indicating bits used for indicating which
2647     * scroll indicators are enabled.
2648     */
2649    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2650            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2651            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2652            | PFLAG3_SCROLL_INDICATOR_END;
2653
2654    /**
2655     * Left-shift required to translate between public scroll indicator flags
2656     * and internal PFLAGS3 flags. When used as a right-shift, translates
2657     * PFLAGS3 flags to public flags.
2658     */
2659    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2660
2661    /** @hide */
2662    @Retention(RetentionPolicy.SOURCE)
2663    @IntDef(flag = true,
2664            value = {
2665                    SCROLL_INDICATOR_TOP,
2666                    SCROLL_INDICATOR_BOTTOM,
2667                    SCROLL_INDICATOR_LEFT,
2668                    SCROLL_INDICATOR_RIGHT,
2669                    SCROLL_INDICATOR_START,
2670                    SCROLL_INDICATOR_END,
2671            })
2672    public @interface ScrollIndicators {}
2673
2674    /**
2675     * Scroll indicator direction for the top edge of the view.
2676     *
2677     * @see #setScrollIndicators(int)
2678     * @see #setScrollIndicators(int, int)
2679     * @see #getScrollIndicators()
2680     */
2681    public static final int SCROLL_INDICATOR_TOP =
2682            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2683
2684    /**
2685     * Scroll indicator direction for the bottom edge of the view.
2686     *
2687     * @see #setScrollIndicators(int)
2688     * @see #setScrollIndicators(int, int)
2689     * @see #getScrollIndicators()
2690     */
2691    public static final int SCROLL_INDICATOR_BOTTOM =
2692            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2693
2694    /**
2695     * Scroll indicator direction for the left edge of the view.
2696     *
2697     * @see #setScrollIndicators(int)
2698     * @see #setScrollIndicators(int, int)
2699     * @see #getScrollIndicators()
2700     */
2701    public static final int SCROLL_INDICATOR_LEFT =
2702            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2703
2704    /**
2705     * Scroll indicator direction for the right edge of the view.
2706     *
2707     * @see #setScrollIndicators(int)
2708     * @see #setScrollIndicators(int, int)
2709     * @see #getScrollIndicators()
2710     */
2711    public static final int SCROLL_INDICATOR_RIGHT =
2712            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2713
2714    /**
2715     * Scroll indicator direction for the starting edge of the view.
2716     * <p>
2717     * Resolved according to the view's layout direction, see
2718     * {@link #getLayoutDirection()} for more information.
2719     *
2720     * @see #setScrollIndicators(int)
2721     * @see #setScrollIndicators(int, int)
2722     * @see #getScrollIndicators()
2723     */
2724    public static final int SCROLL_INDICATOR_START =
2725            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2726
2727    /**
2728     * Scroll indicator direction for the ending edge of the view.
2729     * <p>
2730     * Resolved according to the view's layout direction, see
2731     * {@link #getLayoutDirection()} for more information.
2732     *
2733     * @see #setScrollIndicators(int)
2734     * @see #setScrollIndicators(int, int)
2735     * @see #getScrollIndicators()
2736     */
2737    public static final int SCROLL_INDICATOR_END =
2738            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2739
2740    /**
2741     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2742     * into this view.<p>
2743     */
2744    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2745
2746    /**
2747     * Flag indicating that the view is a root of a keyboard navigation cluster.
2748     *
2749     * @see #isKeyboardNavigationCluster()
2750     * @see #setKeyboardNavigationCluster(boolean)
2751     */
2752    private static final int PFLAG3_CLUSTER = 0x8000;
2753
2754    /**
2755     * Indicates that the user is currently touching the screen.
2756     * Currently used for the tooltip positioning only.
2757     */
2758    private static final int PFLAG3_FINGER_DOWN = 0x20000;
2759
2760    /**
2761     * Flag indicating that this view is the default-focus view.
2762     *
2763     * @see #isFocusedByDefault()
2764     * @see #setFocusedByDefault(boolean)
2765     */
2766    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
2767
2768    /**
2769     * Shift for the place where the auto-fill mode is stored in the pflags
2770     *
2771     * @see #getAutoFillMode()
2772     * @see #setAutoFillMode(int)
2773     */
2774    private static final int PFLAG3_AUTO_FILL_MODE_SHIFT = 19;
2775
2776    /**
2777     * Mask for auto-fill modes
2778     *
2779     * @see #getAutoFillMode()
2780     * @see #setAutoFillMode(int)
2781     */
2782    private static final int PFLAG3_AUTO_FILL_MODE_MASK = (AUTO_FILL_MODE_INHERIT
2783            | AUTO_FILL_MODE_AUTO | AUTO_FILL_MODE_MANUAL) << PFLAG3_AUTO_FILL_MODE_SHIFT;
2784
2785    /**
2786     * Whether this view has rendered elements that overlap (see {@link
2787     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2788     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2789     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2790     * determined by whatever {@link #hasOverlappingRendering()} returns.
2791     */
2792    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2793
2794    /**
2795     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2796     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2797     */
2798    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2799
2800    /**
2801     * Flag indicating that the view is temporarily detached from the parent view.
2802     *
2803     * @see #onStartTemporaryDetach()
2804     * @see #onFinishTemporaryDetach()
2805     */
2806    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2807
2808    /**
2809     * Flag indicating that the view does not wish to be revealed within its parent
2810     * hierarchy when it gains focus. Expressed in the negative since the historical
2811     * default behavior is to reveal on focus; this flag suppresses that behavior.
2812     *
2813     * @see #setRevealOnFocusHint(boolean)
2814     * @see #getRevealOnFocusHint()
2815     */
2816    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
2817
2818    /* End of masks for mPrivateFlags3 */
2819
2820    /**
2821     * Always allow a user to over-scroll this view, provided it is a
2822     * view that can scroll.
2823     *
2824     * @see #getOverScrollMode()
2825     * @see #setOverScrollMode(int)
2826     */
2827    public static final int OVER_SCROLL_ALWAYS = 0;
2828
2829    /**
2830     * Allow a user to over-scroll this view only if the content is large
2831     * enough to meaningfully scroll, provided it is a view that can scroll.
2832     *
2833     * @see #getOverScrollMode()
2834     * @see #setOverScrollMode(int)
2835     */
2836    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2837
2838    /**
2839     * Never allow a user to over-scroll this view.
2840     *
2841     * @see #getOverScrollMode()
2842     * @see #setOverScrollMode(int)
2843     */
2844    public static final int OVER_SCROLL_NEVER = 2;
2845
2846    /**
2847     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2848     * requested the system UI (status bar) to be visible (the default).
2849     *
2850     * @see #setSystemUiVisibility(int)
2851     */
2852    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2853
2854    /**
2855     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2856     * system UI to enter an unobtrusive "low profile" mode.
2857     *
2858     * <p>This is for use in games, book readers, video players, or any other
2859     * "immersive" application where the usual system chrome is deemed too distracting.
2860     *
2861     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2862     *
2863     * @see #setSystemUiVisibility(int)
2864     */
2865    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2866
2867    /**
2868     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2869     * system navigation be temporarily hidden.
2870     *
2871     * <p>This is an even less obtrusive state than that called for by
2872     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2873     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2874     * those to disappear. This is useful (in conjunction with the
2875     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2876     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2877     * window flags) for displaying content using every last pixel on the display.
2878     *
2879     * <p>There is a limitation: because navigation controls are so important, the least user
2880     * interaction will cause them to reappear immediately.  When this happens, both
2881     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2882     * so that both elements reappear at the same time.
2883     *
2884     * @see #setSystemUiVisibility(int)
2885     */
2886    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2887
2888    /**
2889     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2890     * into the normal fullscreen mode so that its content can take over the screen
2891     * while still allowing the user to interact with the application.
2892     *
2893     * <p>This has the same visual effect as
2894     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2895     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2896     * meaning that non-critical screen decorations (such as the status bar) will be
2897     * hidden while the user is in the View's window, focusing the experience on
2898     * that content.  Unlike the window flag, if you are using ActionBar in
2899     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2900     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2901     * hide the action bar.
2902     *
2903     * <p>This approach to going fullscreen is best used over the window flag when
2904     * it is a transient state -- that is, the application does this at certain
2905     * points in its user interaction where it wants to allow the user to focus
2906     * on content, but not as a continuous state.  For situations where the application
2907     * would like to simply stay full screen the entire time (such as a game that
2908     * wants to take over the screen), the
2909     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2910     * is usually a better approach.  The state set here will be removed by the system
2911     * in various situations (such as the user moving to another application) like
2912     * the other system UI states.
2913     *
2914     * <p>When using this flag, the application should provide some easy facility
2915     * for the user to go out of it.  A common example would be in an e-book
2916     * reader, where tapping on the screen brings back whatever screen and UI
2917     * decorations that had been hidden while the user was immersed in reading
2918     * the book.
2919     *
2920     * @see #setSystemUiVisibility(int)
2921     */
2922    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2923
2924    /**
2925     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2926     * flags, we would like a stable view of the content insets given to
2927     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2928     * will always represent the worst case that the application can expect
2929     * as a continuous state.  In the stock Android UI this is the space for
2930     * the system bar, nav bar, and status bar, but not more transient elements
2931     * such as an input method.
2932     *
2933     * The stable layout your UI sees is based on the system UI modes you can
2934     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2935     * then you will get a stable layout for changes of the
2936     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2937     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2938     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2939     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2940     * with a stable layout.  (Note that you should avoid using
2941     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2942     *
2943     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2944     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2945     * then a hidden status bar will be considered a "stable" state for purposes
2946     * here.  This allows your UI to continually hide the status bar, while still
2947     * using the system UI flags to hide the action bar while still retaining
2948     * a stable layout.  Note that changing the window fullscreen flag will never
2949     * provide a stable layout for a clean transition.
2950     *
2951     * <p>If you are using ActionBar in
2952     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2953     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2954     * insets it adds to those given to the application.
2955     */
2956    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2957
2958    /**
2959     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2960     * to be laid out as if it has requested
2961     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2962     * allows it to avoid artifacts when switching in and out of that mode, at
2963     * the expense that some of its user interface may be covered by screen
2964     * decorations when they are shown.  You can perform layout of your inner
2965     * UI elements to account for the navigation system UI through the
2966     * {@link #fitSystemWindows(Rect)} method.
2967     */
2968    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2969
2970    /**
2971     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2972     * to be laid out as if it has requested
2973     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2974     * allows it to avoid artifacts when switching in and out of that mode, at
2975     * the expense that some of its user interface may be covered by screen
2976     * decorations when they are shown.  You can perform layout of your inner
2977     * UI elements to account for non-fullscreen system UI through the
2978     * {@link #fitSystemWindows(Rect)} method.
2979     */
2980    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2981
2982    /**
2983     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2984     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2985     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2986     * user interaction.
2987     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2988     * has an effect when used in combination with that flag.</p>
2989     */
2990    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2991
2992    /**
2993     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2994     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2995     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2996     * experience while also hiding the system bars.  If this flag is not set,
2997     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2998     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2999     * if the user swipes from the top of the screen.
3000     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
3001     * system gestures, such as swiping from the top of the screen.  These transient system bars
3002     * will overlay app’s content, may have some degree of transparency, and will automatically
3003     * hide after a short timeout.
3004     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
3005     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
3006     * with one or both of those flags.</p>
3007     */
3008    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
3009
3010    /**
3011     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
3012     * is compatible with light status bar backgrounds.
3013     *
3014     * <p>For this to take effect, the window must request
3015     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3016     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3017     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
3018     *         FLAG_TRANSLUCENT_STATUS}.
3019     *
3020     * @see android.R.attr#windowLightStatusBar
3021     */
3022    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
3023
3024    /**
3025     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3026     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3027     */
3028    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
3029
3030    /**
3031     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3032     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3033     */
3034    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
3035
3036    /**
3037     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
3038     * that is compatible with light navigation bar backgrounds.
3039     *
3040     * <p>For this to take effect, the window must request
3041     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3042     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3043     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
3044     *         FLAG_TRANSLUCENT_NAVIGATION}.
3045     */
3046    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
3047
3048    /**
3049     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
3050     */
3051    @Deprecated
3052    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
3053
3054    /**
3055     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
3056     */
3057    @Deprecated
3058    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
3059
3060    /**
3061     * @hide
3062     *
3063     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3064     * out of the public fields to keep the undefined bits out of the developer's way.
3065     *
3066     * Flag to make the status bar not expandable.  Unless you also
3067     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3068     */
3069    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3070
3071    /**
3072     * @hide
3073     *
3074     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3075     * out of the public fields to keep the undefined bits out of the developer's way.
3076     *
3077     * Flag to hide notification icons and scrolling ticker text.
3078     */
3079    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3080
3081    /**
3082     * @hide
3083     *
3084     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3085     * out of the public fields to keep the undefined bits out of the developer's way.
3086     *
3087     * Flag to disable incoming notification alerts.  This will not block
3088     * icons, but it will block sound, vibrating and other visual or aural notifications.
3089     */
3090    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3091
3092    /**
3093     * @hide
3094     *
3095     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3096     * out of the public fields to keep the undefined bits out of the developer's way.
3097     *
3098     * Flag to hide only the scrolling ticker.  Note that
3099     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3100     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3101     */
3102    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3103
3104    /**
3105     * @hide
3106     *
3107     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3108     * out of the public fields to keep the undefined bits out of the developer's way.
3109     *
3110     * Flag to hide the center system info area.
3111     */
3112    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3113
3114    /**
3115     * @hide
3116     *
3117     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3118     * out of the public fields to keep the undefined bits out of the developer's way.
3119     *
3120     * Flag to hide only the home button.  Don't use this
3121     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3122     */
3123    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3124
3125    /**
3126     * @hide
3127     *
3128     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3129     * out of the public fields to keep the undefined bits out of the developer's way.
3130     *
3131     * Flag to hide only the back button. Don't use this
3132     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3133     */
3134    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3135
3136    /**
3137     * @hide
3138     *
3139     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3140     * out of the public fields to keep the undefined bits out of the developer's way.
3141     *
3142     * Flag to hide only the clock.  You might use this if your activity has
3143     * its own clock making the status bar's clock redundant.
3144     */
3145    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3146
3147    /**
3148     * @hide
3149     *
3150     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3151     * out of the public fields to keep the undefined bits out of the developer's way.
3152     *
3153     * Flag to hide only the recent apps button. Don't use this
3154     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3155     */
3156    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3157
3158    /**
3159     * @hide
3160     *
3161     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3162     * out of the public fields to keep the undefined bits out of the developer's way.
3163     *
3164     * Flag to disable the global search gesture. Don't use this
3165     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3166     */
3167    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3168
3169    /**
3170     * @hide
3171     *
3172     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3173     * out of the public fields to keep the undefined bits out of the developer's way.
3174     *
3175     * Flag to specify that the status bar is displayed in transient mode.
3176     */
3177    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3178
3179    /**
3180     * @hide
3181     *
3182     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3183     * out of the public fields to keep the undefined bits out of the developer's way.
3184     *
3185     * Flag to specify that the navigation bar is displayed in transient mode.
3186     */
3187    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3188
3189    /**
3190     * @hide
3191     *
3192     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3193     * out of the public fields to keep the undefined bits out of the developer's way.
3194     *
3195     * Flag to specify that the hidden status bar would like to be shown.
3196     */
3197    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3198
3199    /**
3200     * @hide
3201     *
3202     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3203     * out of the public fields to keep the undefined bits out of the developer's way.
3204     *
3205     * Flag to specify that the hidden navigation bar would like to be shown.
3206     */
3207    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3208
3209    /**
3210     * @hide
3211     *
3212     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3213     * out of the public fields to keep the undefined bits out of the developer's way.
3214     *
3215     * Flag to specify that the status bar is displayed in translucent mode.
3216     */
3217    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3218
3219    /**
3220     * @hide
3221     *
3222     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3223     * out of the public fields to keep the undefined bits out of the developer's way.
3224     *
3225     * Flag to specify that the navigation bar is displayed in translucent mode.
3226     */
3227    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3228
3229    /**
3230     * @hide
3231     *
3232     * Makes navigation bar transparent (but not the status bar).
3233     */
3234    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3235
3236    /**
3237     * @hide
3238     *
3239     * Makes status bar transparent (but not the navigation bar).
3240     */
3241    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3242
3243    /**
3244     * @hide
3245     *
3246     * Makes both status bar and navigation bar transparent.
3247     */
3248    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3249            | STATUS_BAR_TRANSPARENT;
3250
3251    /**
3252     * @hide
3253     */
3254    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3255
3256    /**
3257     * These are the system UI flags that can be cleared by events outside
3258     * of an application.  Currently this is just the ability to tap on the
3259     * screen while hiding the navigation bar to have it return.
3260     * @hide
3261     */
3262    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3263            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3264            | SYSTEM_UI_FLAG_FULLSCREEN;
3265
3266    /**
3267     * Flags that can impact the layout in relation to system UI.
3268     */
3269    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3270            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3271            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3272
3273    /** @hide */
3274    @IntDef(flag = true,
3275            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3276    @Retention(RetentionPolicy.SOURCE)
3277    public @interface FindViewFlags {}
3278
3279    /**
3280     * Find views that render the specified text.
3281     *
3282     * @see #findViewsWithText(ArrayList, CharSequence, int)
3283     */
3284    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3285
3286    /**
3287     * Find find views that contain the specified content description.
3288     *
3289     * @see #findViewsWithText(ArrayList, CharSequence, int)
3290     */
3291    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3292
3293    /**
3294     * Find views that contain {@link AccessibilityNodeProvider}. Such
3295     * a View is a root of virtual view hierarchy and may contain the searched
3296     * text. If this flag is set Views with providers are automatically
3297     * added and it is a responsibility of the client to call the APIs of
3298     * the provider to determine whether the virtual tree rooted at this View
3299     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3300     * representing the virtual views with this text.
3301     *
3302     * @see #findViewsWithText(ArrayList, CharSequence, int)
3303     *
3304     * @hide
3305     */
3306    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3307
3308    /**
3309     * The undefined cursor position.
3310     *
3311     * @hide
3312     */
3313    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3314
3315    /**
3316     * Indicates that the screen has changed state and is now off.
3317     *
3318     * @see #onScreenStateChanged(int)
3319     */
3320    public static final int SCREEN_STATE_OFF = 0x0;
3321
3322    /**
3323     * Indicates that the screen has changed state and is now on.
3324     *
3325     * @see #onScreenStateChanged(int)
3326     */
3327    public static final int SCREEN_STATE_ON = 0x1;
3328
3329    /**
3330     * Indicates no axis of view scrolling.
3331     */
3332    public static final int SCROLL_AXIS_NONE = 0;
3333
3334    /**
3335     * Indicates scrolling along the horizontal axis.
3336     */
3337    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3338
3339    /**
3340     * Indicates scrolling along the vertical axis.
3341     */
3342    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3343
3344    /**
3345     * Controls the over-scroll mode for this view.
3346     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3347     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3348     * and {@link #OVER_SCROLL_NEVER}.
3349     */
3350    private int mOverScrollMode;
3351
3352    /**
3353     * The parent this view is attached to.
3354     * {@hide}
3355     *
3356     * @see #getParent()
3357     */
3358    protected ViewParent mParent;
3359
3360    /**
3361     * {@hide}
3362     */
3363    AttachInfo mAttachInfo;
3364
3365    /**
3366     * {@hide}
3367     */
3368    @ViewDebug.ExportedProperty(flagMapping = {
3369        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3370                name = "FORCE_LAYOUT"),
3371        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3372                name = "LAYOUT_REQUIRED"),
3373        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3374            name = "DRAWING_CACHE_INVALID", outputIf = false),
3375        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3376        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3377        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3378        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3379    }, formatToHexString = true)
3380
3381    /* @hide */
3382    public int mPrivateFlags;
3383    int mPrivateFlags2;
3384    int mPrivateFlags3;
3385
3386    /**
3387     * This view's request for the visibility of the status bar.
3388     * @hide
3389     */
3390    @ViewDebug.ExportedProperty(flagMapping = {
3391        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3392                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3393                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3394        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3395                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3396                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3397        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3398                                equals = SYSTEM_UI_FLAG_VISIBLE,
3399                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3400    }, formatToHexString = true)
3401    int mSystemUiVisibility;
3402
3403    /**
3404     * Reference count for transient state.
3405     * @see #setHasTransientState(boolean)
3406     */
3407    int mTransientStateCount = 0;
3408
3409    /**
3410     * Count of how many windows this view has been attached to.
3411     */
3412    int mWindowAttachCount;
3413
3414    /**
3415     * The layout parameters associated with this view and used by the parent
3416     * {@link android.view.ViewGroup} to determine how this view should be
3417     * laid out.
3418     * {@hide}
3419     */
3420    protected ViewGroup.LayoutParams mLayoutParams;
3421
3422    /**
3423     * The view flags hold various views states.
3424     * {@hide}
3425     */
3426    @ViewDebug.ExportedProperty(formatToHexString = true)
3427    int mViewFlags;
3428
3429    static class TransformationInfo {
3430        /**
3431         * The transform matrix for the View. This transform is calculated internally
3432         * based on the translation, rotation, and scale properties.
3433         *
3434         * Do *not* use this variable directly; instead call getMatrix(), which will
3435         * load the value from the View's RenderNode.
3436         */
3437        private final Matrix mMatrix = new Matrix();
3438
3439        /**
3440         * The inverse transform matrix for the View. This transform is calculated
3441         * internally based on the translation, rotation, and scale properties.
3442         *
3443         * Do *not* use this variable directly; instead call getInverseMatrix(),
3444         * which will load the value from the View's RenderNode.
3445         */
3446        private Matrix mInverseMatrix;
3447
3448        /**
3449         * The opacity of the View. This is a value from 0 to 1, where 0 means
3450         * completely transparent and 1 means completely opaque.
3451         */
3452        @ViewDebug.ExportedProperty
3453        float mAlpha = 1f;
3454
3455        /**
3456         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3457         * property only used by transitions, which is composited with the other alpha
3458         * values to calculate the final visual alpha value.
3459         */
3460        float mTransitionAlpha = 1f;
3461    }
3462
3463    /** @hide */
3464    public TransformationInfo mTransformationInfo;
3465
3466    /**
3467     * Current clip bounds. to which all drawing of this view are constrained.
3468     */
3469    Rect mClipBounds = null;
3470
3471    private boolean mLastIsOpaque;
3472
3473    /**
3474     * The distance in pixels from the left edge of this view's parent
3475     * to the left edge of this view.
3476     * {@hide}
3477     */
3478    @ViewDebug.ExportedProperty(category = "layout")
3479    protected int mLeft;
3480    /**
3481     * The distance in pixels from the left edge of this view's parent
3482     * to the right edge of this view.
3483     * {@hide}
3484     */
3485    @ViewDebug.ExportedProperty(category = "layout")
3486    protected int mRight;
3487    /**
3488     * The distance in pixels from the top edge of this view's parent
3489     * to the top edge of this view.
3490     * {@hide}
3491     */
3492    @ViewDebug.ExportedProperty(category = "layout")
3493    protected int mTop;
3494    /**
3495     * The distance in pixels from the top edge of this view's parent
3496     * to the bottom edge of this view.
3497     * {@hide}
3498     */
3499    @ViewDebug.ExportedProperty(category = "layout")
3500    protected int mBottom;
3501
3502    /**
3503     * The offset, in pixels, by which the content of this view is scrolled
3504     * horizontally.
3505     * {@hide}
3506     */
3507    @ViewDebug.ExportedProperty(category = "scrolling")
3508    protected int mScrollX;
3509    /**
3510     * The offset, in pixels, by which the content of this view is scrolled
3511     * vertically.
3512     * {@hide}
3513     */
3514    @ViewDebug.ExportedProperty(category = "scrolling")
3515    protected int mScrollY;
3516
3517    /**
3518     * The left padding in pixels, that is the distance in pixels between the
3519     * left edge of this view and the left edge of its content.
3520     * {@hide}
3521     */
3522    @ViewDebug.ExportedProperty(category = "padding")
3523    protected int mPaddingLeft = 0;
3524    /**
3525     * The right padding in pixels, that is the distance in pixels between the
3526     * right edge of this view and the right edge of its content.
3527     * {@hide}
3528     */
3529    @ViewDebug.ExportedProperty(category = "padding")
3530    protected int mPaddingRight = 0;
3531    /**
3532     * The top padding in pixels, that is the distance in pixels between the
3533     * top edge of this view and the top edge of its content.
3534     * {@hide}
3535     */
3536    @ViewDebug.ExportedProperty(category = "padding")
3537    protected int mPaddingTop;
3538    /**
3539     * The bottom padding in pixels, that is the distance in pixels between the
3540     * bottom edge of this view and the bottom edge of its content.
3541     * {@hide}
3542     */
3543    @ViewDebug.ExportedProperty(category = "padding")
3544    protected int mPaddingBottom;
3545
3546    /**
3547     * The layout insets in pixels, that is the distance in pixels between the
3548     * visible edges of this view its bounds.
3549     */
3550    private Insets mLayoutInsets;
3551
3552    /**
3553     * Briefly describes the view and is primarily used for accessibility support.
3554     */
3555    private CharSequence mContentDescription;
3556
3557    /**
3558     * Specifies the id of a view for which this view serves as a label for
3559     * accessibility purposes.
3560     */
3561    private int mLabelForId = View.NO_ID;
3562
3563    /**
3564     * Predicate for matching labeled view id with its label for
3565     * accessibility purposes.
3566     */
3567    private MatchLabelForPredicate mMatchLabelForPredicate;
3568
3569    /**
3570     * Specifies a view before which this one is visited in accessibility traversal.
3571     */
3572    private int mAccessibilityTraversalBeforeId = NO_ID;
3573
3574    /**
3575     * Specifies a view after which this one is visited in accessibility traversal.
3576     */
3577    private int mAccessibilityTraversalAfterId = NO_ID;
3578
3579    /**
3580     * Predicate for matching a view by its id.
3581     */
3582    private MatchIdPredicate mMatchIdPredicate;
3583
3584    /**
3585     * Cache the paddingRight set by the user to append to the scrollbar's size.
3586     *
3587     * @hide
3588     */
3589    @ViewDebug.ExportedProperty(category = "padding")
3590    protected int mUserPaddingRight;
3591
3592    /**
3593     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3594     *
3595     * @hide
3596     */
3597    @ViewDebug.ExportedProperty(category = "padding")
3598    protected int mUserPaddingBottom;
3599
3600    /**
3601     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3602     *
3603     * @hide
3604     */
3605    @ViewDebug.ExportedProperty(category = "padding")
3606    protected int mUserPaddingLeft;
3607
3608    /**
3609     * Cache the paddingStart set by the user to append to the scrollbar's size.
3610     *
3611     */
3612    @ViewDebug.ExportedProperty(category = "padding")
3613    int mUserPaddingStart;
3614
3615    /**
3616     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3617     *
3618     */
3619    @ViewDebug.ExportedProperty(category = "padding")
3620    int mUserPaddingEnd;
3621
3622    /**
3623     * Cache initial left padding.
3624     *
3625     * @hide
3626     */
3627    int mUserPaddingLeftInitial;
3628
3629    /**
3630     * Cache initial right padding.
3631     *
3632     * @hide
3633     */
3634    int mUserPaddingRightInitial;
3635
3636    /**
3637     * Default undefined padding
3638     */
3639    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3640
3641    /**
3642     * Cache if a left padding has been defined
3643     */
3644    private boolean mLeftPaddingDefined = false;
3645
3646    /**
3647     * Cache if a right padding has been defined
3648     */
3649    private boolean mRightPaddingDefined = false;
3650
3651    /**
3652     * @hide
3653     */
3654    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3655    /**
3656     * @hide
3657     */
3658    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3659
3660    private LongSparseLongArray mMeasureCache;
3661
3662    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3663    private Drawable mBackground;
3664    private TintInfo mBackgroundTint;
3665
3666    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3667    private ForegroundInfo mForegroundInfo;
3668
3669    private Drawable mScrollIndicatorDrawable;
3670
3671    /**
3672     * RenderNode used for backgrounds.
3673     * <p>
3674     * When non-null and valid, this is expected to contain an up-to-date copy
3675     * of the background drawable. It is cleared on temporary detach, and reset
3676     * on cleanup.
3677     */
3678    private RenderNode mBackgroundRenderNode;
3679
3680    private int mBackgroundResource;
3681    private boolean mBackgroundSizeChanged;
3682
3683    private String mTransitionName;
3684
3685    static class TintInfo {
3686        ColorStateList mTintList;
3687        PorterDuff.Mode mTintMode;
3688        boolean mHasTintMode;
3689        boolean mHasTintList;
3690    }
3691
3692    private static class ForegroundInfo {
3693        private Drawable mDrawable;
3694        private TintInfo mTintInfo;
3695        private int mGravity = Gravity.FILL;
3696        private boolean mInsidePadding = true;
3697        private boolean mBoundsChanged = true;
3698        private final Rect mSelfBounds = new Rect();
3699        private final Rect mOverlayBounds = new Rect();
3700    }
3701
3702    static class ListenerInfo {
3703        /**
3704         * Listener used to dispatch focus change events.
3705         * This field should be made private, so it is hidden from the SDK.
3706         * {@hide}
3707         */
3708        protected OnFocusChangeListener mOnFocusChangeListener;
3709
3710        /**
3711         * Listeners for layout change events.
3712         */
3713        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3714
3715        protected OnScrollChangeListener mOnScrollChangeListener;
3716
3717        /**
3718         * Listeners for attach events.
3719         */
3720        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3721
3722        /**
3723         * Listener used to dispatch click events.
3724         * This field should be made private, so it is hidden from the SDK.
3725         * {@hide}
3726         */
3727        public OnClickListener mOnClickListener;
3728
3729        /**
3730         * Listener used to dispatch long click events.
3731         * This field should be made private, so it is hidden from the SDK.
3732         * {@hide}
3733         */
3734        protected OnLongClickListener mOnLongClickListener;
3735
3736        /**
3737         * Listener used to dispatch context click events. This field should be made private, so it
3738         * is hidden from the SDK.
3739         * {@hide}
3740         */
3741        protected OnContextClickListener mOnContextClickListener;
3742
3743        /**
3744         * Listener used to build the context menu.
3745         * This field should be made private, so it is hidden from the SDK.
3746         * {@hide}
3747         */
3748        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3749
3750        private OnKeyListener mOnKeyListener;
3751
3752        private OnTouchListener mOnTouchListener;
3753
3754        private OnHoverListener mOnHoverListener;
3755
3756        private OnGenericMotionListener mOnGenericMotionListener;
3757
3758        private OnDragListener mOnDragListener;
3759
3760        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3761
3762        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3763
3764        OnCapturedPointerListener mOnCapturedPointerListener;
3765    }
3766
3767    ListenerInfo mListenerInfo;
3768
3769    private static class TooltipInfo {
3770        /**
3771         * Text to be displayed in a tooltip popup.
3772         */
3773        @Nullable
3774        CharSequence mTooltipText;
3775
3776        /**
3777         * View-relative position of the tooltip anchor point.
3778         */
3779        int mAnchorX;
3780        int mAnchorY;
3781
3782        /**
3783         * The tooltip popup.
3784         */
3785        @Nullable
3786        TooltipPopup mTooltipPopup;
3787
3788        /**
3789         * Set to true if the tooltip was shown as a result of a long click.
3790         */
3791        boolean mTooltipFromLongClick;
3792
3793        /**
3794         * Keep these Runnables so that they can be used to reschedule.
3795         */
3796        Runnable mShowTooltipRunnable;
3797        Runnable mHideTooltipRunnable;
3798    }
3799
3800    TooltipInfo mTooltipInfo;
3801
3802    // Temporary values used to hold (x,y) coordinates when delegating from the
3803    // two-arg performLongClick() method to the legacy no-arg version.
3804    private float mLongClickX = Float.NaN;
3805    private float mLongClickY = Float.NaN;
3806
3807    /**
3808     * The application environment this view lives in.
3809     * This field should be made private, so it is hidden from the SDK.
3810     * {@hide}
3811     */
3812    @ViewDebug.ExportedProperty(deepExport = true)
3813    protected Context mContext;
3814
3815    private final Resources mResources;
3816
3817    private ScrollabilityCache mScrollCache;
3818
3819    private int[] mDrawableState = null;
3820
3821    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3822
3823    /**
3824     * Animator that automatically runs based on state changes.
3825     */
3826    private StateListAnimator mStateListAnimator;
3827
3828    /**
3829     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3830     * the user may specify which view to go to next.
3831     */
3832    private int mNextFocusLeftId = View.NO_ID;
3833
3834    /**
3835     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3836     * the user may specify which view to go to next.
3837     */
3838    private int mNextFocusRightId = View.NO_ID;
3839
3840    /**
3841     * When this view has focus and the next focus is {@link #FOCUS_UP},
3842     * the user may specify which view to go to next.
3843     */
3844    private int mNextFocusUpId = View.NO_ID;
3845
3846    /**
3847     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3848     * the user may specify which view to go to next.
3849     */
3850    private int mNextFocusDownId = View.NO_ID;
3851
3852    /**
3853     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3854     * the user may specify which view to go to next.
3855     */
3856    int mNextFocusForwardId = View.NO_ID;
3857
3858    /**
3859     * User-specified next keyboard navigation cluster.
3860     */
3861    int mNextClusterForwardId = View.NO_ID;
3862
3863    private CheckForLongPress mPendingCheckForLongPress;
3864    private CheckForTap mPendingCheckForTap = null;
3865    private PerformClick mPerformClick;
3866    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3867
3868    private UnsetPressedState mUnsetPressedState;
3869
3870    /**
3871     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3872     * up event while a long press is invoked as soon as the long press duration is reached, so
3873     * a long press could be performed before the tap is checked, in which case the tap's action
3874     * should not be invoked.
3875     */
3876    private boolean mHasPerformedLongPress;
3877
3878    /**
3879     * Whether a context click button is currently pressed down. This is true when the stylus is
3880     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3881     * pressed. This is false once the button is released or if the stylus has been lifted.
3882     */
3883    private boolean mInContextButtonPress;
3884
3885    /**
3886     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3887     * true after a stylus button press has occured, when the next up event should not be recognized
3888     * as a tap.
3889     */
3890    private boolean mIgnoreNextUpEvent;
3891
3892    /**
3893     * The minimum height of the view. We'll try our best to have the height
3894     * of this view to at least this amount.
3895     */
3896    @ViewDebug.ExportedProperty(category = "measurement")
3897    private int mMinHeight;
3898
3899    /**
3900     * The minimum width of the view. We'll try our best to have the width
3901     * of this view to at least this amount.
3902     */
3903    @ViewDebug.ExportedProperty(category = "measurement")
3904    private int mMinWidth;
3905
3906    /**
3907     * The delegate to handle touch events that are physically in this view
3908     * but should be handled by another view.
3909     */
3910    private TouchDelegate mTouchDelegate = null;
3911
3912    /**
3913     * Solid color to use as a background when creating the drawing cache. Enables
3914     * the cache to use 16 bit bitmaps instead of 32 bit.
3915     */
3916    private int mDrawingCacheBackgroundColor = 0;
3917
3918    /**
3919     * Special tree observer used when mAttachInfo is null.
3920     */
3921    private ViewTreeObserver mFloatingTreeObserver;
3922
3923    /**
3924     * Cache the touch slop from the context that created the view.
3925     */
3926    private int mTouchSlop;
3927
3928    /**
3929     * Object that handles automatic animation of view properties.
3930     */
3931    private ViewPropertyAnimator mAnimator = null;
3932
3933    /**
3934     * List of registered FrameMetricsObservers.
3935     */
3936    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3937
3938    /**
3939     * Flag indicating that a drag can cross window boundaries.  When
3940     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3941     * with this flag set, all visible applications with targetSdkVersion >=
3942     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3943     * in the drag operation and receive the dragged content.
3944     *
3945     * <p>If this is the only flag set, then the drag recipient will only have access to text data
3946     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3947     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
3948     */
3949    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3950
3951    /**
3952     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3953     * request read access to the content URI(s) contained in the {@link ClipData} object.
3954     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3955     */
3956    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3957
3958    /**
3959     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3960     * request write access to the content URI(s) contained in the {@link ClipData} object.
3961     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3962     */
3963    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3964
3965    /**
3966     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3967     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3968     * reboots until explicitly revoked with
3969     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3970     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3971     */
3972    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3973            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3974
3975    /**
3976     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3977     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3978     * match against the original granted URI.
3979     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3980     */
3981    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3982            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3983
3984    /**
3985     * Flag indicating that the drag shadow will be opaque.  When
3986     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3987     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3988     */
3989    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3990
3991    /**
3992     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3993     */
3994    private float mVerticalScrollFactor;
3995
3996    /**
3997     * Position of the vertical scroll bar.
3998     */
3999    private int mVerticalScrollbarPosition;
4000
4001    /**
4002     * Position the scroll bar at the default position as determined by the system.
4003     */
4004    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
4005
4006    /**
4007     * Position the scroll bar along the left edge.
4008     */
4009    public static final int SCROLLBAR_POSITION_LEFT = 1;
4010
4011    /**
4012     * Position the scroll bar along the right edge.
4013     */
4014    public static final int SCROLLBAR_POSITION_RIGHT = 2;
4015
4016    /**
4017     * Indicates that the view does not have a layer.
4018     *
4019     * @see #getLayerType()
4020     * @see #setLayerType(int, android.graphics.Paint)
4021     * @see #LAYER_TYPE_SOFTWARE
4022     * @see #LAYER_TYPE_HARDWARE
4023     */
4024    public static final int LAYER_TYPE_NONE = 0;
4025
4026    /**
4027     * <p>Indicates that the view has a software layer. A software layer is backed
4028     * by a bitmap and causes the view to be rendered using Android's software
4029     * rendering pipeline, even if hardware acceleration is enabled.</p>
4030     *
4031     * <p>Software layers have various usages:</p>
4032     * <p>When the application is not using hardware acceleration, a software layer
4033     * is useful to apply a specific color filter and/or blending mode and/or
4034     * translucency to a view and all its children.</p>
4035     * <p>When the application is using hardware acceleration, a software layer
4036     * is useful to render drawing primitives not supported by the hardware
4037     * accelerated pipeline. It can also be used to cache a complex view tree
4038     * into a texture and reduce the complexity of drawing operations. For instance,
4039     * when animating a complex view tree with a translation, a software layer can
4040     * be used to render the view tree only once.</p>
4041     * <p>Software layers should be avoided when the affected view tree updates
4042     * often. Every update will require to re-render the software layer, which can
4043     * potentially be slow (particularly when hardware acceleration is turned on
4044     * since the layer will have to be uploaded into a hardware texture after every
4045     * update.)</p>
4046     *
4047     * @see #getLayerType()
4048     * @see #setLayerType(int, android.graphics.Paint)
4049     * @see #LAYER_TYPE_NONE
4050     * @see #LAYER_TYPE_HARDWARE
4051     */
4052    public static final int LAYER_TYPE_SOFTWARE = 1;
4053
4054    /**
4055     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
4056     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
4057     * OpenGL hardware) and causes the view to be rendered using Android's hardware
4058     * rendering pipeline, but only if hardware acceleration is turned on for the
4059     * view hierarchy. When hardware acceleration is turned off, hardware layers
4060     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
4061     *
4062     * <p>A hardware layer is useful to apply a specific color filter and/or
4063     * blending mode and/or translucency to a view and all its children.</p>
4064     * <p>A hardware layer can be used to cache a complex view tree into a
4065     * texture and reduce the complexity of drawing operations. For instance,
4066     * when animating a complex view tree with a translation, a hardware layer can
4067     * be used to render the view tree only once.</p>
4068     * <p>A hardware layer can also be used to increase the rendering quality when
4069     * rotation transformations are applied on a view. It can also be used to
4070     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4071     *
4072     * @see #getLayerType()
4073     * @see #setLayerType(int, android.graphics.Paint)
4074     * @see #LAYER_TYPE_NONE
4075     * @see #LAYER_TYPE_SOFTWARE
4076     */
4077    public static final int LAYER_TYPE_HARDWARE = 2;
4078
4079    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4080            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4081            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4082            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4083    })
4084    int mLayerType = LAYER_TYPE_NONE;
4085    Paint mLayerPaint;
4086
4087    /**
4088     * Set to true when drawing cache is enabled and cannot be created.
4089     *
4090     * @hide
4091     */
4092    public boolean mCachingFailed;
4093    private Bitmap mDrawingCache;
4094    private Bitmap mUnscaledDrawingCache;
4095
4096    /**
4097     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4098     * <p>
4099     * When non-null and valid, this is expected to contain an up-to-date copy
4100     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4101     * cleanup.
4102     */
4103    final RenderNode mRenderNode;
4104
4105    /**
4106     * Set to true when the view is sending hover accessibility events because it
4107     * is the innermost hovered view.
4108     */
4109    private boolean mSendingHoverAccessibilityEvents;
4110
4111    /**
4112     * Delegate for injecting accessibility functionality.
4113     */
4114    AccessibilityDelegate mAccessibilityDelegate;
4115
4116    /**
4117     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4118     * and add/remove objects to/from the overlay directly through the Overlay methods.
4119     */
4120    ViewOverlay mOverlay;
4121
4122    /**
4123     * The currently active parent view for receiving delegated nested scrolling events.
4124     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4125     * by {@link #stopNestedScroll()} at the same point where we clear
4126     * requestDisallowInterceptTouchEvent.
4127     */
4128    private ViewParent mNestedScrollingParent;
4129
4130    /**
4131     * Consistency verifier for debugging purposes.
4132     * @hide
4133     */
4134    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4135            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4136                    new InputEventConsistencyVerifier(this, 0) : null;
4137
4138    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4139
4140    private int[] mTempNestedScrollConsumed;
4141
4142    /**
4143     * An overlay is going to draw this View instead of being drawn as part of this
4144     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4145     * when this view is invalidated.
4146     */
4147    GhostView mGhostView;
4148
4149    /**
4150     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4151     * @hide
4152     */
4153    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4154    public String[] mAttributes;
4155
4156    /**
4157     * Maps a Resource id to its name.
4158     */
4159    private static SparseArray<String> mAttributeMap;
4160
4161    /**
4162     * Queue of pending runnables. Used to postpone calls to post() until this
4163     * view is attached and has a handler.
4164     */
4165    private HandlerActionQueue mRunQueue;
4166
4167    /**
4168     * The pointer icon when the mouse hovers on this view. The default is null.
4169     */
4170    private PointerIcon mPointerIcon;
4171
4172    /**
4173     * @hide
4174     */
4175    String mStartActivityRequestWho;
4176
4177    @Nullable
4178    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4179
4180    /**
4181     * Simple constructor to use when creating a view from code.
4182     *
4183     * @param context The Context the view is running in, through which it can
4184     *        access the current theme, resources, etc.
4185     */
4186    public View(Context context) {
4187        mContext = context;
4188        mResources = context != null ? context.getResources() : null;
4189        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
4190        // Set some flags defaults
4191        mPrivateFlags2 =
4192                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4193                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4194                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4195                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4196                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4197                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4198        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4199        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4200        mUserPaddingStart = UNDEFINED_PADDING;
4201        mUserPaddingEnd = UNDEFINED_PADDING;
4202        mRenderNode = RenderNode.create(getClass().getName(), this);
4203
4204        if (!sCompatibilityDone && context != null) {
4205            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4206
4207            // Older apps may need this compatibility hack for measurement.
4208            sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1;
4209
4210            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4211            // of whether a layout was requested on that View.
4212            sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT;
4213
4214            Canvas.sCompatibilityRestore = targetSdkVersion < Build.VERSION_CODES.M;
4215
4216            // In M and newer, our widgets can pass a "hint" value in the size
4217            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4218            // know what the expected parent size is going to be, so e.g. list items can size
4219            // themselves at 1/3 the size of their container. It breaks older apps though,
4220            // specifically apps that use some popular open source libraries.
4221            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M;
4222
4223            // Old versions of the platform would give different results from
4224            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4225            // modes, so we always need to run an additional EXACTLY pass.
4226            sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M;
4227
4228            // Prior to N, layout params could change without requiring a
4229            // subsequent call to setLayoutParams() and they would usually
4230            // work. Partial layout breaks this assumption.
4231            sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M;
4232
4233            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4234            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4235            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M;
4236
4237            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4238            // in apps so we target check it to avoid breaking existing apps.
4239            sPreserveMarginParamsInLayoutParamConversion =
4240                    targetSdkVersion >= Build.VERSION_CODES.N;
4241
4242            sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N;
4243
4244            sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O;
4245
4246            sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O;
4247
4248            sCompatibilityDone = true;
4249        }
4250    }
4251
4252    /**
4253     * Constructor that is called when inflating a view from XML. This is called
4254     * when a view is being constructed from an XML file, supplying attributes
4255     * that were specified in the XML file. This version uses a default style of
4256     * 0, so the only attribute values applied are those in the Context's Theme
4257     * and the given AttributeSet.
4258     *
4259     * <p>
4260     * The method onFinishInflate() will be called after all children have been
4261     * added.
4262     *
4263     * @param context The Context the view is running in, through which it can
4264     *        access the current theme, resources, etc.
4265     * @param attrs The attributes of the XML tag that is inflating the view.
4266     * @see #View(Context, AttributeSet, int)
4267     */
4268    public View(Context context, @Nullable AttributeSet attrs) {
4269        this(context, attrs, 0);
4270    }
4271
4272    /**
4273     * Perform inflation from XML and apply a class-specific base style from a
4274     * theme attribute. This constructor of View allows subclasses to use their
4275     * own base style when they are inflating. For example, a Button class's
4276     * constructor would call this version of the super class constructor and
4277     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4278     * allows the theme's button style to modify all of the base view attributes
4279     * (in particular its background) as well as the Button class's attributes.
4280     *
4281     * @param context The Context the view is running in, through which it can
4282     *        access the current theme, resources, etc.
4283     * @param attrs The attributes of the XML tag that is inflating the view.
4284     * @param defStyleAttr An attribute in the current theme that contains a
4285     *        reference to a style resource that supplies default values for
4286     *        the view. Can be 0 to not look for defaults.
4287     * @see #View(Context, AttributeSet)
4288     */
4289    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4290        this(context, attrs, defStyleAttr, 0);
4291    }
4292
4293    /**
4294     * Perform inflation from XML and apply a class-specific base style from a
4295     * theme attribute or style resource. This constructor of View allows
4296     * subclasses to use their own base style when they are inflating.
4297     * <p>
4298     * When determining the final value of a particular attribute, there are
4299     * four inputs that come into play:
4300     * <ol>
4301     * <li>Any attribute values in the given AttributeSet.
4302     * <li>The style resource specified in the AttributeSet (named "style").
4303     * <li>The default style specified by <var>defStyleAttr</var>.
4304     * <li>The default style specified by <var>defStyleRes</var>.
4305     * <li>The base values in this theme.
4306     * </ol>
4307     * <p>
4308     * Each of these inputs is considered in-order, with the first listed taking
4309     * precedence over the following ones. In other words, if in the
4310     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4311     * , then the button's text will <em>always</em> be black, regardless of
4312     * what is specified in any of the styles.
4313     *
4314     * @param context The Context the view is running in, through which it can
4315     *        access the current theme, resources, etc.
4316     * @param attrs The attributes of the XML tag that is inflating the view.
4317     * @param defStyleAttr An attribute in the current theme that contains a
4318     *        reference to a style resource that supplies default values for
4319     *        the view. Can be 0 to not look for defaults.
4320     * @param defStyleRes A resource identifier of a style resource that
4321     *        supplies default values for the view, used only if
4322     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4323     *        to not look for defaults.
4324     * @see #View(Context, AttributeSet, int)
4325     */
4326    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4327        this(context);
4328
4329        final TypedArray a = context.obtainStyledAttributes(
4330                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4331
4332        if (mDebugViewAttributes) {
4333            saveAttributeData(attrs, a);
4334        }
4335
4336        Drawable background = null;
4337
4338        int leftPadding = -1;
4339        int topPadding = -1;
4340        int rightPadding = -1;
4341        int bottomPadding = -1;
4342        int startPadding = UNDEFINED_PADDING;
4343        int endPadding = UNDEFINED_PADDING;
4344
4345        int padding = -1;
4346        int paddingHorizontal = -1;
4347        int paddingVertical = -1;
4348
4349        int viewFlagValues = 0;
4350        int viewFlagMasks = 0;
4351
4352        boolean setScrollContainer = false;
4353
4354        int x = 0;
4355        int y = 0;
4356
4357        float tx = 0;
4358        float ty = 0;
4359        float tz = 0;
4360        float elevation = 0;
4361        float rotation = 0;
4362        float rotationX = 0;
4363        float rotationY = 0;
4364        float sx = 1f;
4365        float sy = 1f;
4366        boolean transformSet = false;
4367
4368        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4369        int overScrollMode = mOverScrollMode;
4370        boolean initializeScrollbars = false;
4371        boolean initializeScrollIndicators = false;
4372
4373        boolean startPaddingDefined = false;
4374        boolean endPaddingDefined = false;
4375        boolean leftPaddingDefined = false;
4376        boolean rightPaddingDefined = false;
4377
4378        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4379
4380        // Set default values.
4381        viewFlagValues |= FOCUSABLE_AUTO;
4382        viewFlagMasks |= FOCUSABLE_AUTO;
4383
4384        final int N = a.getIndexCount();
4385        for (int i = 0; i < N; i++) {
4386            int attr = a.getIndex(i);
4387            switch (attr) {
4388                case com.android.internal.R.styleable.View_background:
4389                    background = a.getDrawable(attr);
4390                    break;
4391                case com.android.internal.R.styleable.View_padding:
4392                    padding = a.getDimensionPixelSize(attr, -1);
4393                    mUserPaddingLeftInitial = padding;
4394                    mUserPaddingRightInitial = padding;
4395                    leftPaddingDefined = true;
4396                    rightPaddingDefined = true;
4397                    break;
4398                case com.android.internal.R.styleable.View_paddingHorizontal:
4399                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
4400                    mUserPaddingLeftInitial = paddingHorizontal;
4401                    mUserPaddingRightInitial = paddingHorizontal;
4402                    leftPaddingDefined = true;
4403                    rightPaddingDefined = true;
4404                    break;
4405                case com.android.internal.R.styleable.View_paddingVertical:
4406                    paddingVertical = a.getDimensionPixelSize(attr, -1);
4407                    break;
4408                 case com.android.internal.R.styleable.View_paddingLeft:
4409                    leftPadding = a.getDimensionPixelSize(attr, -1);
4410                    mUserPaddingLeftInitial = leftPadding;
4411                    leftPaddingDefined = true;
4412                    break;
4413                case com.android.internal.R.styleable.View_paddingTop:
4414                    topPadding = a.getDimensionPixelSize(attr, -1);
4415                    break;
4416                case com.android.internal.R.styleable.View_paddingRight:
4417                    rightPadding = a.getDimensionPixelSize(attr, -1);
4418                    mUserPaddingRightInitial = rightPadding;
4419                    rightPaddingDefined = true;
4420                    break;
4421                case com.android.internal.R.styleable.View_paddingBottom:
4422                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4423                    break;
4424                case com.android.internal.R.styleable.View_paddingStart:
4425                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4426                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4427                    break;
4428                case com.android.internal.R.styleable.View_paddingEnd:
4429                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4430                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4431                    break;
4432                case com.android.internal.R.styleable.View_scrollX:
4433                    x = a.getDimensionPixelOffset(attr, 0);
4434                    break;
4435                case com.android.internal.R.styleable.View_scrollY:
4436                    y = a.getDimensionPixelOffset(attr, 0);
4437                    break;
4438                case com.android.internal.R.styleable.View_alpha:
4439                    setAlpha(a.getFloat(attr, 1f));
4440                    break;
4441                case com.android.internal.R.styleable.View_transformPivotX:
4442                    setPivotX(a.getDimension(attr, 0));
4443                    break;
4444                case com.android.internal.R.styleable.View_transformPivotY:
4445                    setPivotY(a.getDimension(attr, 0));
4446                    break;
4447                case com.android.internal.R.styleable.View_translationX:
4448                    tx = a.getDimension(attr, 0);
4449                    transformSet = true;
4450                    break;
4451                case com.android.internal.R.styleable.View_translationY:
4452                    ty = a.getDimension(attr, 0);
4453                    transformSet = true;
4454                    break;
4455                case com.android.internal.R.styleable.View_translationZ:
4456                    tz = a.getDimension(attr, 0);
4457                    transformSet = true;
4458                    break;
4459                case com.android.internal.R.styleable.View_elevation:
4460                    elevation = a.getDimension(attr, 0);
4461                    transformSet = true;
4462                    break;
4463                case com.android.internal.R.styleable.View_rotation:
4464                    rotation = a.getFloat(attr, 0);
4465                    transformSet = true;
4466                    break;
4467                case com.android.internal.R.styleable.View_rotationX:
4468                    rotationX = a.getFloat(attr, 0);
4469                    transformSet = true;
4470                    break;
4471                case com.android.internal.R.styleable.View_rotationY:
4472                    rotationY = a.getFloat(attr, 0);
4473                    transformSet = true;
4474                    break;
4475                case com.android.internal.R.styleable.View_scaleX:
4476                    sx = a.getFloat(attr, 1f);
4477                    transformSet = true;
4478                    break;
4479                case com.android.internal.R.styleable.View_scaleY:
4480                    sy = a.getFloat(attr, 1f);
4481                    transformSet = true;
4482                    break;
4483                case com.android.internal.R.styleable.View_id:
4484                    mID = a.getResourceId(attr, NO_ID);
4485                    break;
4486                case com.android.internal.R.styleable.View_tag:
4487                    mTag = a.getText(attr);
4488                    break;
4489                case com.android.internal.R.styleable.View_fitsSystemWindows:
4490                    if (a.getBoolean(attr, false)) {
4491                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4492                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4493                    }
4494                    break;
4495                case com.android.internal.R.styleable.View_focusable:
4496                    viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
4497                    if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
4498                        viewFlagMasks |= FOCUSABLE_MASK;
4499                    }
4500                    break;
4501                case com.android.internal.R.styleable.View_focusableInTouchMode:
4502                    if (a.getBoolean(attr, false)) {
4503                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4504                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4505                    }
4506                    break;
4507                case com.android.internal.R.styleable.View_clickable:
4508                    if (a.getBoolean(attr, false)) {
4509                        viewFlagValues |= CLICKABLE;
4510                        viewFlagMasks |= CLICKABLE;
4511                    }
4512                    break;
4513                case com.android.internal.R.styleable.View_longClickable:
4514                    if (a.getBoolean(attr, false)) {
4515                        viewFlagValues |= LONG_CLICKABLE;
4516                        viewFlagMasks |= LONG_CLICKABLE;
4517                    }
4518                    break;
4519                case com.android.internal.R.styleable.View_contextClickable:
4520                    if (a.getBoolean(attr, false)) {
4521                        viewFlagValues |= CONTEXT_CLICKABLE;
4522                        viewFlagMasks |= CONTEXT_CLICKABLE;
4523                    }
4524                    break;
4525                case com.android.internal.R.styleable.View_saveEnabled:
4526                    if (!a.getBoolean(attr, true)) {
4527                        viewFlagValues |= SAVE_DISABLED;
4528                        viewFlagMasks |= SAVE_DISABLED_MASK;
4529                    }
4530                    break;
4531                case com.android.internal.R.styleable.View_duplicateParentState:
4532                    if (a.getBoolean(attr, false)) {
4533                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4534                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4535                    }
4536                    break;
4537                case com.android.internal.R.styleable.View_visibility:
4538                    final int visibility = a.getInt(attr, 0);
4539                    if (visibility != 0) {
4540                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4541                        viewFlagMasks |= VISIBILITY_MASK;
4542                    }
4543                    break;
4544                case com.android.internal.R.styleable.View_layoutDirection:
4545                    // Clear any layout direction flags (included resolved bits) already set
4546                    mPrivateFlags2 &=
4547                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4548                    // Set the layout direction flags depending on the value of the attribute
4549                    final int layoutDirection = a.getInt(attr, -1);
4550                    final int value = (layoutDirection != -1) ?
4551                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4552                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4553                    break;
4554                case com.android.internal.R.styleable.View_drawingCacheQuality:
4555                    final int cacheQuality = a.getInt(attr, 0);
4556                    if (cacheQuality != 0) {
4557                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4558                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4559                    }
4560                    break;
4561                case com.android.internal.R.styleable.View_contentDescription:
4562                    setContentDescription(a.getString(attr));
4563                    break;
4564                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4565                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4566                    break;
4567                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4568                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4569                    break;
4570                case com.android.internal.R.styleable.View_labelFor:
4571                    setLabelFor(a.getResourceId(attr, NO_ID));
4572                    break;
4573                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4574                    if (!a.getBoolean(attr, true)) {
4575                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4576                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4577                    }
4578                    break;
4579                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4580                    if (!a.getBoolean(attr, true)) {
4581                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4582                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4583                    }
4584                    break;
4585                case R.styleable.View_scrollbars:
4586                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4587                    if (scrollbars != SCROLLBARS_NONE) {
4588                        viewFlagValues |= scrollbars;
4589                        viewFlagMasks |= SCROLLBARS_MASK;
4590                        initializeScrollbars = true;
4591                    }
4592                    break;
4593                //noinspection deprecation
4594                case R.styleable.View_fadingEdge:
4595                    if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
4596                        // Ignore the attribute starting with ICS
4597                        break;
4598                    }
4599                    // With builds < ICS, fall through and apply fading edges
4600                case R.styleable.View_requiresFadingEdge:
4601                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4602                    if (fadingEdge != FADING_EDGE_NONE) {
4603                        viewFlagValues |= fadingEdge;
4604                        viewFlagMasks |= FADING_EDGE_MASK;
4605                        initializeFadingEdgeInternal(a);
4606                    }
4607                    break;
4608                case R.styleable.View_scrollbarStyle:
4609                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4610                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4611                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4612                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4613                    }
4614                    break;
4615                case R.styleable.View_isScrollContainer:
4616                    setScrollContainer = true;
4617                    if (a.getBoolean(attr, false)) {
4618                        setScrollContainer(true);
4619                    }
4620                    break;
4621                case com.android.internal.R.styleable.View_keepScreenOn:
4622                    if (a.getBoolean(attr, false)) {
4623                        viewFlagValues |= KEEP_SCREEN_ON;
4624                        viewFlagMasks |= KEEP_SCREEN_ON;
4625                    }
4626                    break;
4627                case R.styleable.View_filterTouchesWhenObscured:
4628                    if (a.getBoolean(attr, false)) {
4629                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4630                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4631                    }
4632                    break;
4633                case R.styleable.View_nextFocusLeft:
4634                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4635                    break;
4636                case R.styleable.View_nextFocusRight:
4637                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4638                    break;
4639                case R.styleable.View_nextFocusUp:
4640                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4641                    break;
4642                case R.styleable.View_nextFocusDown:
4643                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4644                    break;
4645                case R.styleable.View_nextFocusForward:
4646                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4647                    break;
4648                case R.styleable.View_nextClusterForward:
4649                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
4650                    break;
4651                case R.styleable.View_minWidth:
4652                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4653                    break;
4654                case R.styleable.View_minHeight:
4655                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4656                    break;
4657                case R.styleable.View_onClick:
4658                    if (context.isRestricted()) {
4659                        throw new IllegalStateException("The android:onClick attribute cannot "
4660                                + "be used within a restricted context");
4661                    }
4662
4663                    final String handlerName = a.getString(attr);
4664                    if (handlerName != null) {
4665                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4666                    }
4667                    break;
4668                case R.styleable.View_overScrollMode:
4669                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4670                    break;
4671                case R.styleable.View_verticalScrollbarPosition:
4672                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4673                    break;
4674                case R.styleable.View_layerType:
4675                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4676                    break;
4677                case R.styleable.View_textDirection:
4678                    // Clear any text direction flag already set
4679                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4680                    // Set the text direction flags depending on the value of the attribute
4681                    final int textDirection = a.getInt(attr, -1);
4682                    if (textDirection != -1) {
4683                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4684                    }
4685                    break;
4686                case R.styleable.View_textAlignment:
4687                    // Clear any text alignment flag already set
4688                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4689                    // Set the text alignment flag depending on the value of the attribute
4690                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4691                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4692                    break;
4693                case R.styleable.View_importantForAccessibility:
4694                    setImportantForAccessibility(a.getInt(attr,
4695                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4696                    break;
4697                case R.styleable.View_accessibilityLiveRegion:
4698                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4699                    break;
4700                case R.styleable.View_transitionName:
4701                    setTransitionName(a.getString(attr));
4702                    break;
4703                case R.styleable.View_nestedScrollingEnabled:
4704                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4705                    break;
4706                case R.styleable.View_stateListAnimator:
4707                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4708                            a.getResourceId(attr, 0)));
4709                    break;
4710                case R.styleable.View_backgroundTint:
4711                    // This will get applied later during setBackground().
4712                    if (mBackgroundTint == null) {
4713                        mBackgroundTint = new TintInfo();
4714                    }
4715                    mBackgroundTint.mTintList = a.getColorStateList(
4716                            R.styleable.View_backgroundTint);
4717                    mBackgroundTint.mHasTintList = true;
4718                    break;
4719                case R.styleable.View_backgroundTintMode:
4720                    // This will get applied later during setBackground().
4721                    if (mBackgroundTint == null) {
4722                        mBackgroundTint = new TintInfo();
4723                    }
4724                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4725                            R.styleable.View_backgroundTintMode, -1), null);
4726                    mBackgroundTint.mHasTintMode = true;
4727                    break;
4728                case R.styleable.View_outlineProvider:
4729                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4730                            PROVIDER_BACKGROUND));
4731                    break;
4732                case R.styleable.View_foreground:
4733                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4734                        setForeground(a.getDrawable(attr));
4735                    }
4736                    break;
4737                case R.styleable.View_foregroundGravity:
4738                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4739                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4740                    }
4741                    break;
4742                case R.styleable.View_foregroundTintMode:
4743                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4744                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4745                    }
4746                    break;
4747                case R.styleable.View_foregroundTint:
4748                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4749                        setForegroundTintList(a.getColorStateList(attr));
4750                    }
4751                    break;
4752                case R.styleable.View_foregroundInsidePadding:
4753                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4754                        if (mForegroundInfo == null) {
4755                            mForegroundInfo = new ForegroundInfo();
4756                        }
4757                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4758                                mForegroundInfo.mInsidePadding);
4759                    }
4760                    break;
4761                case R.styleable.View_scrollIndicators:
4762                    final int scrollIndicators =
4763                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4764                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4765                    if (scrollIndicators != 0) {
4766                        mPrivateFlags3 |= scrollIndicators;
4767                        initializeScrollIndicators = true;
4768                    }
4769                    break;
4770                case R.styleable.View_pointerIcon:
4771                    final int resourceId = a.getResourceId(attr, 0);
4772                    if (resourceId != 0) {
4773                        setPointerIcon(PointerIcon.load(
4774                                context.getResources(), resourceId));
4775                    } else {
4776                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4777                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4778                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4779                        }
4780                    }
4781                    break;
4782                case R.styleable.View_forceHasOverlappingRendering:
4783                    if (a.peekValue(attr) != null) {
4784                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4785                    }
4786                    break;
4787                case R.styleable.View_tooltipText:
4788                    setTooltipText(a.getText(attr));
4789                    break;
4790                case R.styleable.View_keyboardNavigationCluster:
4791                    if (a.peekValue(attr) != null) {
4792                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
4793                    }
4794                    break;
4795                case R.styleable.View_focusedByDefault:
4796                    if (a.peekValue(attr) != null) {
4797                        setFocusedByDefault(a.getBoolean(attr, true));
4798                    }
4799                    break;
4800                case com.android.internal.R.styleable.View_autoFillMode:
4801                    if (a.peekValue(attr) != null) {
4802                        setAutoFillMode(a.getInt(attr, AUTO_FILL_MODE_INHERIT));
4803                    }
4804                    break;
4805            }
4806        }
4807
4808        setOverScrollMode(overScrollMode);
4809
4810        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4811        // the resolved layout direction). Those cached values will be used later during padding
4812        // resolution.
4813        mUserPaddingStart = startPadding;
4814        mUserPaddingEnd = endPadding;
4815
4816        if (background != null) {
4817            setBackground(background);
4818        }
4819
4820        // setBackground above will record that padding is currently provided by the background.
4821        // If we have padding specified via xml, record that here instead and use it.
4822        mLeftPaddingDefined = leftPaddingDefined;
4823        mRightPaddingDefined = rightPaddingDefined;
4824
4825        if (padding >= 0) {
4826            leftPadding = padding;
4827            topPadding = padding;
4828            rightPadding = padding;
4829            bottomPadding = padding;
4830            mUserPaddingLeftInitial = padding;
4831            mUserPaddingRightInitial = padding;
4832        } else {
4833            if (paddingHorizontal >= 0) {
4834                leftPadding = paddingHorizontal;
4835                rightPadding = paddingHorizontal;
4836                mUserPaddingLeftInitial = paddingHorizontal;
4837                mUserPaddingRightInitial = paddingHorizontal;
4838            }
4839            if (paddingVertical >= 0) {
4840                topPadding = paddingVertical;
4841                bottomPadding = paddingVertical;
4842            }
4843        }
4844
4845        if (isRtlCompatibilityMode()) {
4846            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4847            // left / right padding are used if defined (meaning here nothing to do). If they are not
4848            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4849            // start / end and resolve them as left / right (layout direction is not taken into account).
4850            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4851            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4852            // defined.
4853            if (!mLeftPaddingDefined && startPaddingDefined) {
4854                leftPadding = startPadding;
4855            }
4856            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4857            if (!mRightPaddingDefined && endPaddingDefined) {
4858                rightPadding = endPadding;
4859            }
4860            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4861        } else {
4862            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4863            // values defined. Otherwise, left /right values are used.
4864            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4865            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4866            // defined.
4867            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4868
4869            if (mLeftPaddingDefined && !hasRelativePadding) {
4870                mUserPaddingLeftInitial = leftPadding;
4871            }
4872            if (mRightPaddingDefined && !hasRelativePadding) {
4873                mUserPaddingRightInitial = rightPadding;
4874            }
4875        }
4876
4877        internalSetPadding(
4878                mUserPaddingLeftInitial,
4879                topPadding >= 0 ? topPadding : mPaddingTop,
4880                mUserPaddingRightInitial,
4881                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4882
4883        if (viewFlagMasks != 0) {
4884            setFlags(viewFlagValues, viewFlagMasks);
4885        }
4886
4887        if (initializeScrollbars) {
4888            initializeScrollbarsInternal(a);
4889        }
4890
4891        if (initializeScrollIndicators) {
4892            initializeScrollIndicatorsInternal();
4893        }
4894
4895        a.recycle();
4896
4897        // Needs to be called after mViewFlags is set
4898        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4899            recomputePadding();
4900        }
4901
4902        if (x != 0 || y != 0) {
4903            scrollTo(x, y);
4904        }
4905
4906        if (transformSet) {
4907            setTranslationX(tx);
4908            setTranslationY(ty);
4909            setTranslationZ(tz);
4910            setElevation(elevation);
4911            setRotation(rotation);
4912            setRotationX(rotationX);
4913            setRotationY(rotationY);
4914            setScaleX(sx);
4915            setScaleY(sy);
4916        }
4917
4918        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4919            setScrollContainer(true);
4920        }
4921
4922        computeOpaqueFlags();
4923    }
4924
4925    /**
4926     * An implementation of OnClickListener that attempts to lazily load a
4927     * named click handling method from a parent or ancestor context.
4928     */
4929    private static class DeclaredOnClickListener implements OnClickListener {
4930        private final View mHostView;
4931        private final String mMethodName;
4932
4933        private Method mResolvedMethod;
4934        private Context mResolvedContext;
4935
4936        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4937            mHostView = hostView;
4938            mMethodName = methodName;
4939        }
4940
4941        @Override
4942        public void onClick(@NonNull View v) {
4943            if (mResolvedMethod == null) {
4944                resolveMethod(mHostView.getContext(), mMethodName);
4945            }
4946
4947            try {
4948                mResolvedMethod.invoke(mResolvedContext, v);
4949            } catch (IllegalAccessException e) {
4950                throw new IllegalStateException(
4951                        "Could not execute non-public method for android:onClick", e);
4952            } catch (InvocationTargetException e) {
4953                throw new IllegalStateException(
4954                        "Could not execute method for android:onClick", e);
4955            }
4956        }
4957
4958        @NonNull
4959        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4960            while (context != null) {
4961                try {
4962                    if (!context.isRestricted()) {
4963                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4964                        if (method != null) {
4965                            mResolvedMethod = method;
4966                            mResolvedContext = context;
4967                            return;
4968                        }
4969                    }
4970                } catch (NoSuchMethodException e) {
4971                    // Failed to find method, keep searching up the hierarchy.
4972                }
4973
4974                if (context instanceof ContextWrapper) {
4975                    context = ((ContextWrapper) context).getBaseContext();
4976                } else {
4977                    // Can't search up the hierarchy, null out and fail.
4978                    context = null;
4979                }
4980            }
4981
4982            final int id = mHostView.getId();
4983            final String idText = id == NO_ID ? "" : " with id '"
4984                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4985            throw new IllegalStateException("Could not find method " + mMethodName
4986                    + "(View) in a parent or ancestor Context for android:onClick "
4987                    + "attribute defined on view " + mHostView.getClass() + idText);
4988        }
4989    }
4990
4991    /**
4992     * Non-public constructor for use in testing
4993     */
4994    View() {
4995        mResources = null;
4996        mRenderNode = RenderNode.create(getClass().getName(), this);
4997    }
4998
4999    final boolean debugDraw() {
5000        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
5001    }
5002
5003    private static SparseArray<String> getAttributeMap() {
5004        if (mAttributeMap == null) {
5005            mAttributeMap = new SparseArray<>();
5006        }
5007        return mAttributeMap;
5008    }
5009
5010    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
5011        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
5012        final int indexCount = t.getIndexCount();
5013        final String[] attributes = new String[(attrsCount + indexCount) * 2];
5014
5015        int i = 0;
5016
5017        // Store raw XML attributes.
5018        for (int j = 0; j < attrsCount; ++j) {
5019            attributes[i] = attrs.getAttributeName(j);
5020            attributes[i + 1] = attrs.getAttributeValue(j);
5021            i += 2;
5022        }
5023
5024        // Store resolved styleable attributes.
5025        final Resources res = t.getResources();
5026        final SparseArray<String> attributeMap = getAttributeMap();
5027        for (int j = 0; j < indexCount; ++j) {
5028            final int index = t.getIndex(j);
5029            if (!t.hasValueOrEmpty(index)) {
5030                // Value is undefined. Skip it.
5031                continue;
5032            }
5033
5034            final int resourceId = t.getResourceId(index, 0);
5035            if (resourceId == 0) {
5036                // Value is not a reference. Skip it.
5037                continue;
5038            }
5039
5040            String resourceName = attributeMap.get(resourceId);
5041            if (resourceName == null) {
5042                try {
5043                    resourceName = res.getResourceName(resourceId);
5044                } catch (Resources.NotFoundException e) {
5045                    resourceName = "0x" + Integer.toHexString(resourceId);
5046                }
5047                attributeMap.put(resourceId, resourceName);
5048            }
5049
5050            attributes[i] = resourceName;
5051            attributes[i + 1] = t.getString(index);
5052            i += 2;
5053        }
5054
5055        // Trim to fit contents.
5056        final String[] trimmed = new String[i];
5057        System.arraycopy(attributes, 0, trimmed, 0, i);
5058        mAttributes = trimmed;
5059    }
5060
5061    public String toString() {
5062        StringBuilder out = new StringBuilder(128);
5063        out.append(getClass().getName());
5064        out.append('{');
5065        out.append(Integer.toHexString(System.identityHashCode(this)));
5066        out.append(' ');
5067        switch (mViewFlags&VISIBILITY_MASK) {
5068            case VISIBLE: out.append('V'); break;
5069            case INVISIBLE: out.append('I'); break;
5070            case GONE: out.append('G'); break;
5071            default: out.append('.'); break;
5072        }
5073        out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
5074        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5075        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5076        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5077        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5078        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5079        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5080        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5081        out.append(' ');
5082        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5083        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5084        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5085        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5086            out.append('p');
5087        } else {
5088            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5089        }
5090        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5091        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5092        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5093        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5094        out.append(' ');
5095        out.append(mLeft);
5096        out.append(',');
5097        out.append(mTop);
5098        out.append('-');
5099        out.append(mRight);
5100        out.append(',');
5101        out.append(mBottom);
5102        final int id = getId();
5103        if (id != NO_ID) {
5104            out.append(" #");
5105            out.append(Integer.toHexString(id));
5106            final Resources r = mResources;
5107            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5108                try {
5109                    String pkgname;
5110                    switch (id&0xff000000) {
5111                        case 0x7f000000:
5112                            pkgname="app";
5113                            break;
5114                        case 0x01000000:
5115                            pkgname="android";
5116                            break;
5117                        default:
5118                            pkgname = r.getResourcePackageName(id);
5119                            break;
5120                    }
5121                    String typename = r.getResourceTypeName(id);
5122                    String entryname = r.getResourceEntryName(id);
5123                    out.append(" ");
5124                    out.append(pkgname);
5125                    out.append(":");
5126                    out.append(typename);
5127                    out.append("/");
5128                    out.append(entryname);
5129                } catch (Resources.NotFoundException e) {
5130                }
5131            }
5132        }
5133        out.append("}");
5134        return out.toString();
5135    }
5136
5137    /**
5138     * <p>
5139     * Initializes the fading edges from a given set of styled attributes. This
5140     * method should be called by subclasses that need fading edges and when an
5141     * instance of these subclasses is created programmatically rather than
5142     * being inflated from XML. This method is automatically called when the XML
5143     * is inflated.
5144     * </p>
5145     *
5146     * @param a the styled attributes set to initialize the fading edges from
5147     *
5148     * @removed
5149     */
5150    protected void initializeFadingEdge(TypedArray a) {
5151        // This method probably shouldn't have been included in the SDK to begin with.
5152        // It relies on 'a' having been initialized using an attribute filter array that is
5153        // not publicly available to the SDK. The old method has been renamed
5154        // to initializeFadingEdgeInternal and hidden for framework use only;
5155        // this one initializes using defaults to make it safe to call for apps.
5156
5157        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5158
5159        initializeFadingEdgeInternal(arr);
5160
5161        arr.recycle();
5162    }
5163
5164    /**
5165     * <p>
5166     * Initializes the fading edges from a given set of styled attributes. This
5167     * method should be called by subclasses that need fading edges and when an
5168     * instance of these subclasses is created programmatically rather than
5169     * being inflated from XML. This method is automatically called when the XML
5170     * is inflated.
5171     * </p>
5172     *
5173     * @param a the styled attributes set to initialize the fading edges from
5174     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5175     */
5176    protected void initializeFadingEdgeInternal(TypedArray a) {
5177        initScrollCache();
5178
5179        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5180                R.styleable.View_fadingEdgeLength,
5181                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5182    }
5183
5184    /**
5185     * Returns the size of the vertical faded edges used to indicate that more
5186     * content in this view is visible.
5187     *
5188     * @return The size in pixels of the vertical faded edge or 0 if vertical
5189     *         faded edges are not enabled for this view.
5190     * @attr ref android.R.styleable#View_fadingEdgeLength
5191     */
5192    public int getVerticalFadingEdgeLength() {
5193        if (isVerticalFadingEdgeEnabled()) {
5194            ScrollabilityCache cache = mScrollCache;
5195            if (cache != null) {
5196                return cache.fadingEdgeLength;
5197            }
5198        }
5199        return 0;
5200    }
5201
5202    /**
5203     * Set the size of the faded edge used to indicate that more content in this
5204     * view is available.  Will not change whether the fading edge is enabled; use
5205     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5206     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5207     * for the vertical or horizontal fading edges.
5208     *
5209     * @param length The size in pixels of the faded edge used to indicate that more
5210     *        content in this view is visible.
5211     */
5212    public void setFadingEdgeLength(int length) {
5213        initScrollCache();
5214        mScrollCache.fadingEdgeLength = length;
5215    }
5216
5217    /**
5218     * Returns the size of the horizontal faded edges used to indicate that more
5219     * content in this view is visible.
5220     *
5221     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5222     *         faded edges are not enabled for this view.
5223     * @attr ref android.R.styleable#View_fadingEdgeLength
5224     */
5225    public int getHorizontalFadingEdgeLength() {
5226        if (isHorizontalFadingEdgeEnabled()) {
5227            ScrollabilityCache cache = mScrollCache;
5228            if (cache != null) {
5229                return cache.fadingEdgeLength;
5230            }
5231        }
5232        return 0;
5233    }
5234
5235    /**
5236     * Returns the width of the vertical scrollbar.
5237     *
5238     * @return The width in pixels of the vertical scrollbar or 0 if there
5239     *         is no vertical scrollbar.
5240     */
5241    public int getVerticalScrollbarWidth() {
5242        ScrollabilityCache cache = mScrollCache;
5243        if (cache != null) {
5244            ScrollBarDrawable scrollBar = cache.scrollBar;
5245            if (scrollBar != null) {
5246                int size = scrollBar.getSize(true);
5247                if (size <= 0) {
5248                    size = cache.scrollBarSize;
5249                }
5250                return size;
5251            }
5252            return 0;
5253        }
5254        return 0;
5255    }
5256
5257    /**
5258     * Returns the height of the horizontal scrollbar.
5259     *
5260     * @return The height in pixels of the horizontal scrollbar or 0 if
5261     *         there is no horizontal scrollbar.
5262     */
5263    protected int getHorizontalScrollbarHeight() {
5264        ScrollabilityCache cache = mScrollCache;
5265        if (cache != null) {
5266            ScrollBarDrawable scrollBar = cache.scrollBar;
5267            if (scrollBar != null) {
5268                int size = scrollBar.getSize(false);
5269                if (size <= 0) {
5270                    size = cache.scrollBarSize;
5271                }
5272                return size;
5273            }
5274            return 0;
5275        }
5276        return 0;
5277    }
5278
5279    /**
5280     * <p>
5281     * Initializes the scrollbars from a given set of styled attributes. This
5282     * method should be called by subclasses that need scrollbars and when an
5283     * instance of these subclasses is created programmatically rather than
5284     * being inflated from XML. This method is automatically called when the XML
5285     * is inflated.
5286     * </p>
5287     *
5288     * @param a the styled attributes set to initialize the scrollbars from
5289     *
5290     * @removed
5291     */
5292    protected void initializeScrollbars(TypedArray a) {
5293        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5294        // using the View filter array which is not available to the SDK. As such, internal
5295        // framework usage now uses initializeScrollbarsInternal and we grab a default
5296        // TypedArray with the right filter instead here.
5297        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5298
5299        initializeScrollbarsInternal(arr);
5300
5301        // We ignored the method parameter. Recycle the one we actually did use.
5302        arr.recycle();
5303    }
5304
5305    /**
5306     * <p>
5307     * Initializes the scrollbars from a given set of styled attributes. This
5308     * method should be called by subclasses that need scrollbars and when an
5309     * instance of these subclasses is created programmatically rather than
5310     * being inflated from XML. This method is automatically called when the XML
5311     * is inflated.
5312     * </p>
5313     *
5314     * @param a the styled attributes set to initialize the scrollbars from
5315     * @hide
5316     */
5317    protected void initializeScrollbarsInternal(TypedArray a) {
5318        initScrollCache();
5319
5320        final ScrollabilityCache scrollabilityCache = mScrollCache;
5321
5322        if (scrollabilityCache.scrollBar == null) {
5323            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5324            scrollabilityCache.scrollBar.setState(getDrawableState());
5325            scrollabilityCache.scrollBar.setCallback(this);
5326        }
5327
5328        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5329
5330        if (!fadeScrollbars) {
5331            scrollabilityCache.state = ScrollabilityCache.ON;
5332        }
5333        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5334
5335
5336        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5337                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5338                        .getScrollBarFadeDuration());
5339        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5340                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5341                ViewConfiguration.getScrollDefaultDelay());
5342
5343
5344        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5345                com.android.internal.R.styleable.View_scrollbarSize,
5346                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5347
5348        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5349        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5350
5351        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5352        if (thumb != null) {
5353            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5354        }
5355
5356        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5357                false);
5358        if (alwaysDraw) {
5359            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5360        }
5361
5362        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5363        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5364
5365        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5366        if (thumb != null) {
5367            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5368        }
5369
5370        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5371                false);
5372        if (alwaysDraw) {
5373            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5374        }
5375
5376        // Apply layout direction to the new Drawables if needed
5377        final int layoutDirection = getLayoutDirection();
5378        if (track != null) {
5379            track.setLayoutDirection(layoutDirection);
5380        }
5381        if (thumb != null) {
5382            thumb.setLayoutDirection(layoutDirection);
5383        }
5384
5385        // Re-apply user/background padding so that scrollbar(s) get added
5386        resolvePadding();
5387    }
5388
5389    private void initializeScrollIndicatorsInternal() {
5390        // Some day maybe we'll break this into top/left/start/etc. and let the
5391        // client control it. Until then, you can have any scroll indicator you
5392        // want as long as it's a 1dp foreground-colored rectangle.
5393        if (mScrollIndicatorDrawable == null) {
5394            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5395        }
5396    }
5397
5398    /**
5399     * <p>
5400     * Initalizes the scrollability cache if necessary.
5401     * </p>
5402     */
5403    private void initScrollCache() {
5404        if (mScrollCache == null) {
5405            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5406        }
5407    }
5408
5409    private ScrollabilityCache getScrollCache() {
5410        initScrollCache();
5411        return mScrollCache;
5412    }
5413
5414    /**
5415     * Set the position of the vertical scroll bar. Should be one of
5416     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5417     * {@link #SCROLLBAR_POSITION_RIGHT}.
5418     *
5419     * @param position Where the vertical scroll bar should be positioned.
5420     */
5421    public void setVerticalScrollbarPosition(int position) {
5422        if (mVerticalScrollbarPosition != position) {
5423            mVerticalScrollbarPosition = position;
5424            computeOpaqueFlags();
5425            resolvePadding();
5426        }
5427    }
5428
5429    /**
5430     * @return The position where the vertical scroll bar will show, if applicable.
5431     * @see #setVerticalScrollbarPosition(int)
5432     */
5433    public int getVerticalScrollbarPosition() {
5434        return mVerticalScrollbarPosition;
5435    }
5436
5437    boolean isOnScrollbar(float x, float y) {
5438        if (mScrollCache == null) {
5439            return false;
5440        }
5441        x += getScrollX();
5442        y += getScrollY();
5443        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5444            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5445            getVerticalScrollBarBounds(null, touchBounds);
5446            if (touchBounds.contains((int) x, (int) y)) {
5447                return true;
5448            }
5449        }
5450        if (isHorizontalScrollBarEnabled()) {
5451            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5452            getHorizontalScrollBarBounds(null, touchBounds);
5453            if (touchBounds.contains((int) x, (int) y)) {
5454                return true;
5455            }
5456        }
5457        return false;
5458    }
5459
5460    boolean isOnScrollbarThumb(float x, float y) {
5461        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5462    }
5463
5464    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5465        if (mScrollCache == null) {
5466            return false;
5467        }
5468        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5469            x += getScrollX();
5470            y += getScrollY();
5471            final Rect bounds = mScrollCache.mScrollBarBounds;
5472            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5473            getVerticalScrollBarBounds(bounds, touchBounds);
5474            final int range = computeVerticalScrollRange();
5475            final int offset = computeVerticalScrollOffset();
5476            final int extent = computeVerticalScrollExtent();
5477            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5478                    extent, range);
5479            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5480                    extent, range, offset);
5481            final int thumbTop = bounds.top + thumbOffset;
5482            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
5483            if (x >= touchBounds.left && x <= touchBounds.right
5484                    && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) {
5485                return true;
5486            }
5487        }
5488        return false;
5489    }
5490
5491    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5492        if (mScrollCache == null) {
5493            return false;
5494        }
5495        if (isHorizontalScrollBarEnabled()) {
5496            x += getScrollX();
5497            y += getScrollY();
5498            final Rect bounds = mScrollCache.mScrollBarBounds;
5499            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5500            getHorizontalScrollBarBounds(bounds, touchBounds);
5501            final int range = computeHorizontalScrollRange();
5502            final int offset = computeHorizontalScrollOffset();
5503            final int extent = computeHorizontalScrollExtent();
5504            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5505                    extent, range);
5506            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5507                    extent, range, offset);
5508            final int thumbLeft = bounds.left + thumbOffset;
5509            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
5510            if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust
5511                    && y >= touchBounds.top && y <= touchBounds.bottom) {
5512                return true;
5513            }
5514        }
5515        return false;
5516    }
5517
5518    boolean isDraggingScrollBar() {
5519        return mScrollCache != null
5520                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5521    }
5522
5523    /**
5524     * Sets the state of all scroll indicators.
5525     * <p>
5526     * See {@link #setScrollIndicators(int, int)} for usage information.
5527     *
5528     * @param indicators a bitmask of indicators that should be enabled, or
5529     *                   {@code 0} to disable all indicators
5530     * @see #setScrollIndicators(int, int)
5531     * @see #getScrollIndicators()
5532     * @attr ref android.R.styleable#View_scrollIndicators
5533     */
5534    public void setScrollIndicators(@ScrollIndicators int indicators) {
5535        setScrollIndicators(indicators,
5536                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5537    }
5538
5539    /**
5540     * Sets the state of the scroll indicators specified by the mask. To change
5541     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5542     * <p>
5543     * When a scroll indicator is enabled, it will be displayed if the view
5544     * can scroll in the direction of the indicator.
5545     * <p>
5546     * Multiple indicator types may be enabled or disabled by passing the
5547     * logical OR of the desired types. If multiple types are specified, they
5548     * will all be set to the same enabled state.
5549     * <p>
5550     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5551     *
5552     * @param indicators the indicator direction, or the logical OR of multiple
5553     *             indicator directions. One or more of:
5554     *             <ul>
5555     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5556     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5557     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5558     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5559     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5560     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5561     *             </ul>
5562     * @see #setScrollIndicators(int)
5563     * @see #getScrollIndicators()
5564     * @attr ref android.R.styleable#View_scrollIndicators
5565     */
5566    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5567        // Shift and sanitize mask.
5568        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5569        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5570
5571        // Shift and mask indicators.
5572        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5573        indicators &= mask;
5574
5575        // Merge with non-masked flags.
5576        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5577
5578        if (mPrivateFlags3 != updatedFlags) {
5579            mPrivateFlags3 = updatedFlags;
5580
5581            if (indicators != 0) {
5582                initializeScrollIndicatorsInternal();
5583            }
5584            invalidate();
5585        }
5586    }
5587
5588    /**
5589     * Returns a bitmask representing the enabled scroll indicators.
5590     * <p>
5591     * For example, if the top and left scroll indicators are enabled and all
5592     * other indicators are disabled, the return value will be
5593     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5594     * <p>
5595     * To check whether the bottom scroll indicator is enabled, use the value
5596     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5597     *
5598     * @return a bitmask representing the enabled scroll indicators
5599     */
5600    @ScrollIndicators
5601    public int getScrollIndicators() {
5602        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5603                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5604    }
5605
5606    ListenerInfo getListenerInfo() {
5607        if (mListenerInfo != null) {
5608            return mListenerInfo;
5609        }
5610        mListenerInfo = new ListenerInfo();
5611        return mListenerInfo;
5612    }
5613
5614    /**
5615     * Register a callback to be invoked when the scroll X or Y positions of
5616     * this view change.
5617     * <p>
5618     * <b>Note:</b> Some views handle scrolling independently from View and may
5619     * have their own separate listeners for scroll-type events. For example,
5620     * {@link android.widget.ListView ListView} allows clients to register an
5621     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5622     * to listen for changes in list scroll position.
5623     *
5624     * @param l The listener to notify when the scroll X or Y position changes.
5625     * @see android.view.View#getScrollX()
5626     * @see android.view.View#getScrollY()
5627     */
5628    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5629        getListenerInfo().mOnScrollChangeListener = l;
5630    }
5631
5632    /**
5633     * Register a callback to be invoked when focus of this view changed.
5634     *
5635     * @param l The callback that will run.
5636     */
5637    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5638        getListenerInfo().mOnFocusChangeListener = l;
5639    }
5640
5641    /**
5642     * Add a listener that will be called when the bounds of the view change due to
5643     * layout processing.
5644     *
5645     * @param listener The listener that will be called when layout bounds change.
5646     */
5647    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5648        ListenerInfo li = getListenerInfo();
5649        if (li.mOnLayoutChangeListeners == null) {
5650            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5651        }
5652        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5653            li.mOnLayoutChangeListeners.add(listener);
5654        }
5655    }
5656
5657    /**
5658     * Remove a listener for layout changes.
5659     *
5660     * @param listener The listener for layout bounds change.
5661     */
5662    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5663        ListenerInfo li = mListenerInfo;
5664        if (li == null || li.mOnLayoutChangeListeners == null) {
5665            return;
5666        }
5667        li.mOnLayoutChangeListeners.remove(listener);
5668    }
5669
5670    /**
5671     * Add a listener for attach state changes.
5672     *
5673     * This listener will be called whenever this view is attached or detached
5674     * from a window. Remove the listener using
5675     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5676     *
5677     * @param listener Listener to attach
5678     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5679     */
5680    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5681        ListenerInfo li = getListenerInfo();
5682        if (li.mOnAttachStateChangeListeners == null) {
5683            li.mOnAttachStateChangeListeners
5684                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5685        }
5686        li.mOnAttachStateChangeListeners.add(listener);
5687    }
5688
5689    /**
5690     * Remove a listener for attach state changes. The listener will receive no further
5691     * notification of window attach/detach events.
5692     *
5693     * @param listener Listener to remove
5694     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5695     */
5696    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5697        ListenerInfo li = mListenerInfo;
5698        if (li == null || li.mOnAttachStateChangeListeners == null) {
5699            return;
5700        }
5701        li.mOnAttachStateChangeListeners.remove(listener);
5702    }
5703
5704    /**
5705     * Returns the focus-change callback registered for this view.
5706     *
5707     * @return The callback, or null if one is not registered.
5708     */
5709    public OnFocusChangeListener getOnFocusChangeListener() {
5710        ListenerInfo li = mListenerInfo;
5711        return li != null ? li.mOnFocusChangeListener : null;
5712    }
5713
5714    /**
5715     * Register a callback to be invoked when this view is clicked. If this view is not
5716     * clickable, it becomes clickable.
5717     *
5718     * @param l The callback that will run
5719     *
5720     * @see #setClickable(boolean)
5721     */
5722    public void setOnClickListener(@Nullable OnClickListener l) {
5723        if (!isClickable()) {
5724            setClickable(true);
5725        }
5726        getListenerInfo().mOnClickListener = l;
5727    }
5728
5729    /**
5730     * Return whether this view has an attached OnClickListener.  Returns
5731     * true if there is a listener, false if there is none.
5732     */
5733    public boolean hasOnClickListeners() {
5734        ListenerInfo li = mListenerInfo;
5735        return (li != null && li.mOnClickListener != null);
5736    }
5737
5738    /**
5739     * Register a callback to be invoked when this view is clicked and held. If this view is not
5740     * long clickable, it becomes long clickable.
5741     *
5742     * @param l The callback that will run
5743     *
5744     * @see #setLongClickable(boolean)
5745     */
5746    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5747        if (!isLongClickable()) {
5748            setLongClickable(true);
5749        }
5750        getListenerInfo().mOnLongClickListener = l;
5751    }
5752
5753    /**
5754     * Register a callback to be invoked when this view is context clicked. If the view is not
5755     * context clickable, it becomes context clickable.
5756     *
5757     * @param l The callback that will run
5758     * @see #setContextClickable(boolean)
5759     */
5760    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5761        if (!isContextClickable()) {
5762            setContextClickable(true);
5763        }
5764        getListenerInfo().mOnContextClickListener = l;
5765    }
5766
5767    /**
5768     * Register a callback to be invoked when the context menu for this view is
5769     * being built. If this view is not long clickable, it becomes long clickable.
5770     *
5771     * @param l The callback that will run
5772     *
5773     */
5774    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5775        if (!isLongClickable()) {
5776            setLongClickable(true);
5777        }
5778        getListenerInfo().mOnCreateContextMenuListener = l;
5779    }
5780
5781    /**
5782     * Set an observer to collect stats for each frame rendered for this view.
5783     *
5784     * @hide
5785     */
5786    public void addFrameMetricsListener(Window window,
5787            Window.OnFrameMetricsAvailableListener listener,
5788            Handler handler) {
5789        if (mAttachInfo != null) {
5790            if (mAttachInfo.mThreadedRenderer != null) {
5791                if (mFrameMetricsObservers == null) {
5792                    mFrameMetricsObservers = new ArrayList<>();
5793                }
5794
5795                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5796                        handler.getLooper(), listener);
5797                mFrameMetricsObservers.add(fmo);
5798                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
5799            } else {
5800                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5801            }
5802        } else {
5803            if (mFrameMetricsObservers == null) {
5804                mFrameMetricsObservers = new ArrayList<>();
5805            }
5806
5807            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5808                    handler.getLooper(), listener);
5809            mFrameMetricsObservers.add(fmo);
5810        }
5811    }
5812
5813    /**
5814     * Remove observer configured to collect frame stats for this view.
5815     *
5816     * @hide
5817     */
5818    public void removeFrameMetricsListener(
5819            Window.OnFrameMetricsAvailableListener listener) {
5820        ThreadedRenderer renderer = getThreadedRenderer();
5821        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5822        if (fmo == null) {
5823            throw new IllegalArgumentException(
5824                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5825        }
5826
5827        if (mFrameMetricsObservers != null) {
5828            mFrameMetricsObservers.remove(fmo);
5829            if (renderer != null) {
5830                renderer.removeFrameMetricsObserver(fmo);
5831            }
5832        }
5833    }
5834
5835    private void registerPendingFrameMetricsObservers() {
5836        if (mFrameMetricsObservers != null) {
5837            ThreadedRenderer renderer = getThreadedRenderer();
5838            if (renderer != null) {
5839                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5840                    renderer.addFrameMetricsObserver(fmo);
5841                }
5842            } else {
5843                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5844            }
5845        }
5846    }
5847
5848    private FrameMetricsObserver findFrameMetricsObserver(
5849            Window.OnFrameMetricsAvailableListener listener) {
5850        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5851            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5852            if (observer.mListener == listener) {
5853                return observer;
5854            }
5855        }
5856
5857        return null;
5858    }
5859
5860    /**
5861     * Call this view's OnClickListener, if it is defined.  Performs all normal
5862     * actions associated with clicking: reporting accessibility event, playing
5863     * a sound, etc.
5864     *
5865     * @return True there was an assigned OnClickListener that was called, false
5866     *         otherwise is returned.
5867     */
5868    public boolean performClick() {
5869        final boolean result;
5870        final ListenerInfo li = mListenerInfo;
5871        if (li != null && li.mOnClickListener != null) {
5872            playSoundEffect(SoundEffectConstants.CLICK);
5873            li.mOnClickListener.onClick(this);
5874            result = true;
5875        } else {
5876            result = false;
5877        }
5878
5879        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5880        return result;
5881    }
5882
5883    /**
5884     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5885     * this only calls the listener, and does not do any associated clicking
5886     * actions like reporting an accessibility event.
5887     *
5888     * @return True there was an assigned OnClickListener that was called, false
5889     *         otherwise is returned.
5890     */
5891    public boolean callOnClick() {
5892        ListenerInfo li = mListenerInfo;
5893        if (li != null && li.mOnClickListener != null) {
5894            li.mOnClickListener.onClick(this);
5895            return true;
5896        }
5897        return false;
5898    }
5899
5900    /**
5901     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5902     * context menu if the OnLongClickListener did not consume the event.
5903     *
5904     * @return {@code true} if one of the above receivers consumed the event,
5905     *         {@code false} otherwise
5906     */
5907    public boolean performLongClick() {
5908        return performLongClickInternal(mLongClickX, mLongClickY);
5909    }
5910
5911    /**
5912     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5913     * context menu if the OnLongClickListener did not consume the event,
5914     * anchoring it to an (x,y) coordinate.
5915     *
5916     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5917     *          to disable anchoring
5918     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5919     *          to disable anchoring
5920     * @return {@code true} if one of the above receivers consumed the event,
5921     *         {@code false} otherwise
5922     */
5923    public boolean performLongClick(float x, float y) {
5924        mLongClickX = x;
5925        mLongClickY = y;
5926        final boolean handled = performLongClick();
5927        mLongClickX = Float.NaN;
5928        mLongClickY = Float.NaN;
5929        return handled;
5930    }
5931
5932    /**
5933     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5934     * context menu if the OnLongClickListener did not consume the event,
5935     * optionally anchoring it to an (x,y) coordinate.
5936     *
5937     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5938     *          to disable anchoring
5939     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5940     *          to disable anchoring
5941     * @return {@code true} if one of the above receivers consumed the event,
5942     *         {@code false} otherwise
5943     */
5944    private boolean performLongClickInternal(float x, float y) {
5945        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5946
5947        boolean handled = false;
5948        final ListenerInfo li = mListenerInfo;
5949        if (li != null && li.mOnLongClickListener != null) {
5950            handled = li.mOnLongClickListener.onLongClick(View.this);
5951        }
5952        if (!handled) {
5953            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5954            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5955        }
5956        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
5957            if (!handled) {
5958                handled = showLongClickTooltip((int) x, (int) y);
5959            }
5960        }
5961        if (handled) {
5962            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5963        }
5964        return handled;
5965    }
5966
5967    /**
5968     * Call this view's OnContextClickListener, if it is defined.
5969     *
5970     * @param x the x coordinate of the context click
5971     * @param y the y coordinate of the context click
5972     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5973     *         otherwise.
5974     */
5975    public boolean performContextClick(float x, float y) {
5976        return performContextClick();
5977    }
5978
5979    /**
5980     * Call this view's OnContextClickListener, if it is defined.
5981     *
5982     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5983     *         otherwise.
5984     */
5985    public boolean performContextClick() {
5986        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5987
5988        boolean handled = false;
5989        ListenerInfo li = mListenerInfo;
5990        if (li != null && li.mOnContextClickListener != null) {
5991            handled = li.mOnContextClickListener.onContextClick(View.this);
5992        }
5993        if (handled) {
5994            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5995        }
5996        return handled;
5997    }
5998
5999    /**
6000     * Performs button-related actions during a touch down event.
6001     *
6002     * @param event The event.
6003     * @return True if the down was consumed.
6004     *
6005     * @hide
6006     */
6007    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
6008        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
6009            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
6010            showContextMenu(event.getX(), event.getY());
6011            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
6012            return true;
6013        }
6014        return false;
6015    }
6016
6017    /**
6018     * Shows the context menu for this view.
6019     *
6020     * @return {@code true} if the context menu was shown, {@code false}
6021     *         otherwise
6022     * @see #showContextMenu(float, float)
6023     */
6024    public boolean showContextMenu() {
6025        return getParent().showContextMenuForChild(this);
6026    }
6027
6028    /**
6029     * Shows the context menu for this view anchored to the specified
6030     * view-relative coordinate.
6031     *
6032     * @param x the X coordinate in pixels relative to the view to which the
6033     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6034     * @param y the Y coordinate in pixels relative to the view to which the
6035     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6036     * @return {@code true} if the context menu was shown, {@code false}
6037     *         otherwise
6038     */
6039    public boolean showContextMenu(float x, float y) {
6040        return getParent().showContextMenuForChild(this, x, y);
6041    }
6042
6043    /**
6044     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
6045     *
6046     * @param callback Callback that will control the lifecycle of the action mode
6047     * @return The new action mode if it is started, null otherwise
6048     *
6049     * @see ActionMode
6050     * @see #startActionMode(android.view.ActionMode.Callback, int)
6051     */
6052    public ActionMode startActionMode(ActionMode.Callback callback) {
6053        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6054    }
6055
6056    /**
6057     * Start an action mode with the given type.
6058     *
6059     * @param callback Callback that will control the lifecycle of the action mode
6060     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6061     * @return The new action mode if it is started, null otherwise
6062     *
6063     * @see ActionMode
6064     */
6065    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6066        ViewParent parent = getParent();
6067        if (parent == null) return null;
6068        try {
6069            return parent.startActionModeForChild(this, callback, type);
6070        } catch (AbstractMethodError ame) {
6071            // Older implementations of custom views might not implement this.
6072            return parent.startActionModeForChild(this, callback);
6073        }
6074    }
6075
6076    /**
6077     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6078     * Context, creating a unique View identifier to retrieve the result.
6079     *
6080     * @param intent The Intent to be started.
6081     * @param requestCode The request code to use.
6082     * @hide
6083     */
6084    public void startActivityForResult(Intent intent, int requestCode) {
6085        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6086        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6087    }
6088
6089    /**
6090     * If this View corresponds to the calling who, dispatches the activity result.
6091     * @param who The identifier for the targeted View to receive the result.
6092     * @param requestCode The integer request code originally supplied to
6093     *                    startActivityForResult(), allowing you to identify who this
6094     *                    result came from.
6095     * @param resultCode The integer result code returned by the child activity
6096     *                   through its setResult().
6097     * @param data An Intent, which can return result data to the caller
6098     *               (various data can be attached to Intent "extras").
6099     * @return {@code true} if the activity result was dispatched.
6100     * @hide
6101     */
6102    public boolean dispatchActivityResult(
6103            String who, int requestCode, int resultCode, Intent data) {
6104        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6105            onActivityResult(requestCode, resultCode, data);
6106            mStartActivityRequestWho = null;
6107            return true;
6108        }
6109        return false;
6110    }
6111
6112    /**
6113     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6114     *
6115     * @param requestCode The integer request code originally supplied to
6116     *                    startActivityForResult(), allowing you to identify who this
6117     *                    result came from.
6118     * @param resultCode The integer result code returned by the child activity
6119     *                   through its setResult().
6120     * @param data An Intent, which can return result data to the caller
6121     *               (various data can be attached to Intent "extras").
6122     * @hide
6123     */
6124    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6125        // Do nothing.
6126    }
6127
6128    /**
6129     * Register a callback to be invoked when a hardware key is pressed in this view.
6130     * Key presses in software input methods will generally not trigger the methods of
6131     * this listener.
6132     * @param l the key listener to attach to this view
6133     */
6134    public void setOnKeyListener(OnKeyListener l) {
6135        getListenerInfo().mOnKeyListener = l;
6136    }
6137
6138    /**
6139     * Register a callback to be invoked when a touch event is sent to this view.
6140     * @param l the touch listener to attach to this view
6141     */
6142    public void setOnTouchListener(OnTouchListener l) {
6143        getListenerInfo().mOnTouchListener = l;
6144    }
6145
6146    /**
6147     * Register a callback to be invoked when a generic motion event is sent to this view.
6148     * @param l the generic motion listener to attach to this view
6149     */
6150    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6151        getListenerInfo().mOnGenericMotionListener = l;
6152    }
6153
6154    /**
6155     * Register a callback to be invoked when a hover event is sent to this view.
6156     * @param l the hover listener to attach to this view
6157     */
6158    public void setOnHoverListener(OnHoverListener l) {
6159        getListenerInfo().mOnHoverListener = l;
6160    }
6161
6162    /**
6163     * Register a drag event listener callback object for this View. The parameter is
6164     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6165     * View, the system calls the
6166     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6167     * @param l An implementation of {@link android.view.View.OnDragListener}.
6168     */
6169    public void setOnDragListener(OnDragListener l) {
6170        getListenerInfo().mOnDragListener = l;
6171    }
6172
6173    /**
6174     * Give this view focus. This will cause
6175     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6176     *
6177     * Note: this does not check whether this {@link View} should get focus, it just
6178     * gives it focus no matter what.  It should only be called internally by framework
6179     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6180     *
6181     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6182     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6183     *        focus moved when requestFocus() is called. It may not always
6184     *        apply, in which case use the default View.FOCUS_DOWN.
6185     * @param previouslyFocusedRect The rectangle of the view that had focus
6186     *        prior in this View's coordinate system.
6187     */
6188    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6189        if (DBG) {
6190            System.out.println(this + " requestFocus()");
6191        }
6192
6193        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6194            mPrivateFlags |= PFLAG_FOCUSED;
6195
6196            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6197
6198            if (mParent != null) {
6199                mParent.requestChildFocus(this, this);
6200                setFocusedInCluster();
6201            }
6202
6203            if (mAttachInfo != null) {
6204                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6205            }
6206
6207            onFocusChanged(true, direction, previouslyFocusedRect);
6208            refreshDrawableState();
6209        }
6210    }
6211
6212    /**
6213     * Sets this view's preference for reveal behavior when it gains focus.
6214     *
6215     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6216     * this view would prefer to be brought fully into view when it gains focus.
6217     * For example, a text field that a user is meant to type into. Other views such
6218     * as scrolling containers may prefer to opt-out of this behavior.</p>
6219     *
6220     * <p>The default value for views is true, though subclasses may change this
6221     * based on their preferred behavior.</p>
6222     *
6223     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6224     *
6225     * @see #getRevealOnFocusHint()
6226     */
6227    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6228        if (revealOnFocus) {
6229            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6230        } else {
6231            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6232        }
6233    }
6234
6235    /**
6236     * Returns this view's preference for reveal behavior when it gains focus.
6237     *
6238     * <p>When this method returns true for a child view requesting focus, ancestor
6239     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6240     * should make a best effort to make the newly focused child fully visible to the user.
6241     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6242     * other properties affecting visibility to the user as part of the focus change.</p>
6243     *
6244     * @return true if this view would prefer to become fully visible when it gains focus,
6245     *         false if it would prefer not to disrupt scroll positioning
6246     *
6247     * @see #setRevealOnFocusHint(boolean)
6248     */
6249    public final boolean getRevealOnFocusHint() {
6250        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6251    }
6252
6253    /**
6254     * Populates <code>outRect</code> with the hotspot bounds. By default,
6255     * the hotspot bounds are identical to the screen bounds.
6256     *
6257     * @param outRect rect to populate with hotspot bounds
6258     * @hide Only for internal use by views and widgets.
6259     */
6260    public void getHotspotBounds(Rect outRect) {
6261        final Drawable background = getBackground();
6262        if (background != null) {
6263            background.getHotspotBounds(outRect);
6264        } else {
6265            getBoundsOnScreen(outRect);
6266        }
6267    }
6268
6269    /**
6270     * Request that a rectangle of this view be visible on the screen,
6271     * scrolling if necessary just enough.
6272     *
6273     * <p>A View should call this if it maintains some notion of which part
6274     * of its content is interesting.  For example, a text editing view
6275     * should call this when its cursor moves.
6276     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6277     * It should not be affected by which part of the View is currently visible or its scroll
6278     * position.
6279     *
6280     * @param rectangle The rectangle in the View's content coordinate space
6281     * @return Whether any parent scrolled.
6282     */
6283    public boolean requestRectangleOnScreen(Rect rectangle) {
6284        return requestRectangleOnScreen(rectangle, false);
6285    }
6286
6287    /**
6288     * Request that a rectangle of this view be visible on the screen,
6289     * scrolling if necessary just enough.
6290     *
6291     * <p>A View should call this if it maintains some notion of which part
6292     * of its content is interesting.  For example, a text editing view
6293     * should call this when its cursor moves.
6294     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6295     * It should not be affected by which part of the View is currently visible or its scroll
6296     * position.
6297     * <p>When <code>immediate</code> is set to true, scrolling will not be
6298     * animated.
6299     *
6300     * @param rectangle The rectangle in the View's content coordinate space
6301     * @param immediate True to forbid animated scrolling, false otherwise
6302     * @return Whether any parent scrolled.
6303     */
6304    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6305        if (mParent == null) {
6306            return false;
6307        }
6308
6309        View child = this;
6310
6311        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6312        position.set(rectangle);
6313
6314        ViewParent parent = mParent;
6315        boolean scrolled = false;
6316        while (parent != null) {
6317            rectangle.set((int) position.left, (int) position.top,
6318                    (int) position.right, (int) position.bottom);
6319
6320            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6321
6322            if (!(parent instanceof View)) {
6323                break;
6324            }
6325
6326            // move it from child's content coordinate space to parent's content coordinate space
6327            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6328
6329            child = (View) parent;
6330            parent = child.getParent();
6331        }
6332
6333        return scrolled;
6334    }
6335
6336    /**
6337     * Called when this view wants to give up focus. If focus is cleared
6338     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6339     * <p>
6340     * <strong>Note:</strong> When a View clears focus the framework is trying
6341     * to give focus to the first focusable View from the top. Hence, if this
6342     * View is the first from the top that can take focus, then all callbacks
6343     * related to clearing focus will be invoked after which the framework will
6344     * give focus to this view.
6345     * </p>
6346     */
6347    public void clearFocus() {
6348        if (DBG) {
6349            System.out.println(this + " clearFocus()");
6350        }
6351
6352        clearFocusInternal(null, true, true);
6353    }
6354
6355    /**
6356     * Clears focus from the view, optionally propagating the change up through
6357     * the parent hierarchy and requesting that the root view place new focus.
6358     *
6359     * @param propagate whether to propagate the change up through the parent
6360     *            hierarchy
6361     * @param refocus when propagate is true, specifies whether to request the
6362     *            root view place new focus
6363     */
6364    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6365        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6366            mPrivateFlags &= ~PFLAG_FOCUSED;
6367
6368            if (propagate && mParent != null) {
6369                mParent.clearChildFocus(this);
6370            }
6371
6372            onFocusChanged(false, 0, null);
6373            refreshDrawableState();
6374
6375            if (propagate && (!refocus || !rootViewRequestFocus())) {
6376                notifyGlobalFocusCleared(this);
6377            }
6378        }
6379    }
6380
6381    void notifyGlobalFocusCleared(View oldFocus) {
6382        if (oldFocus != null && mAttachInfo != null) {
6383            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6384        }
6385    }
6386
6387    boolean rootViewRequestFocus() {
6388        final View root = getRootView();
6389        return root != null && root.requestFocus();
6390    }
6391
6392    /**
6393     * Called internally by the view system when a new view is getting focus.
6394     * This is what clears the old focus.
6395     * <p>
6396     * <b>NOTE:</b> The parent view's focused child must be updated manually
6397     * after calling this method. Otherwise, the view hierarchy may be left in
6398     * an inconstent state.
6399     */
6400    void unFocus(View focused) {
6401        if (DBG) {
6402            System.out.println(this + " unFocus()");
6403        }
6404
6405        clearFocusInternal(focused, false, false);
6406    }
6407
6408    /**
6409     * Returns true if this view has focus itself, or is the ancestor of the
6410     * view that has focus.
6411     *
6412     * @return True if this view has or contains focus, false otherwise.
6413     */
6414    @ViewDebug.ExportedProperty(category = "focus")
6415    public boolean hasFocus() {
6416        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6417    }
6418
6419    /**
6420     * Returns true if this view is focusable or if it contains a reachable View
6421     * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()"
6422     * is a view whose parents do not block descendants focus.
6423     * Only {@link #VISIBLE} views are considered focusable.
6424     *
6425     * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable
6426     * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}.
6427     * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of
6428     * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return
6429     * {@code false} for views not explicitly marked as focusable.
6430     * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O}
6431     * behavior.</p>
6432     *
6433     * @return {@code true} if the view is focusable or if the view contains a focusable
6434     *         view, {@code false} otherwise
6435     *
6436     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6437     * @see ViewGroup#getTouchscreenBlocksFocus()
6438     * @see #hasExplicitFocusable()
6439     */
6440    public boolean hasFocusable() {
6441        return hasFocusable(!sHasFocusableExcludeAutoFocusable, false);
6442    }
6443
6444    /**
6445     * Returns true if this view is focusable or if it contains a reachable View
6446     * for which {@link #hasExplicitFocusable()} returns {@code true}.
6447     * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus.
6448     * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return
6449     * {@link #FOCUSABLE} are considered focusable.
6450     *
6451     * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of
6452     * {@link #hasFocusable()} in that only views explicitly set focusable will cause
6453     * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves
6454     * to focusable will not.</p>
6455     *
6456     * @return {@code true} if the view is focusable or if the view contains a focusable
6457     *         view, {@code false} otherwise
6458     *
6459     * @see #hasFocusable()
6460     */
6461    public boolean hasExplicitFocusable() {
6462        return hasFocusable(false, true);
6463    }
6464
6465    boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) {
6466        if (!isFocusableInTouchMode()) {
6467            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6468                final ViewGroup g = (ViewGroup) p;
6469                if (g.shouldBlockFocusForTouchscreen()) {
6470                    return false;
6471                }
6472            }
6473        }
6474        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6475            return false;
6476        }
6477        return (allowAutoFocus
6478                ? getFocusable() != NOT_FOCUSABLE
6479                : getFocusable() == FOCUSABLE) && isFocusable();
6480    }
6481
6482    /**
6483     * Called by the view system when the focus state of this view changes.
6484     * When the focus change event is caused by directional navigation, direction
6485     * and previouslyFocusedRect provide insight into where the focus is coming from.
6486     * When overriding, be sure to call up through to the super class so that
6487     * the standard focus handling will occur.
6488     *
6489     * @param gainFocus True if the View has focus; false otherwise.
6490     * @param direction The direction focus has moved when requestFocus()
6491     *                  is called to give this view focus. Values are
6492     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6493     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6494     *                  It may not always apply, in which case use the default.
6495     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6496     *        system, of the previously focused view.  If applicable, this will be
6497     *        passed in as finer grained information about where the focus is coming
6498     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6499     */
6500    @CallSuper
6501    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6502            @Nullable Rect previouslyFocusedRect) {
6503        if (gainFocus) {
6504            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6505        } else {
6506            notifyViewAccessibilityStateChangedIfNeeded(
6507                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6508        }
6509
6510        InputMethodManager imm = InputMethodManager.peekInstance();
6511        if (!gainFocus) {
6512            if (isPressed()) {
6513                setPressed(false);
6514            }
6515            if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6516                imm.focusOut(this);
6517            }
6518            onFocusLost();
6519        } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6520            imm.focusIn(this);
6521        }
6522
6523        if (isAutoFillable()) {
6524            AutoFillManager afm = getAutoFillManager();
6525            if (afm != null) {
6526                afm.focusChanged(this, gainFocus);
6527            }
6528        }
6529
6530        invalidate(true);
6531        ListenerInfo li = mListenerInfo;
6532        if (li != null && li.mOnFocusChangeListener != null) {
6533            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6534        }
6535
6536        if (mAttachInfo != null) {
6537            mAttachInfo.mKeyDispatchState.reset(this);
6538        }
6539    }
6540
6541    /**
6542     * Sends an accessibility event of the given type. If accessibility is
6543     * not enabled this method has no effect. The default implementation calls
6544     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6545     * to populate information about the event source (this View), then calls
6546     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6547     * populate the text content of the event source including its descendants,
6548     * and last calls
6549     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6550     * on its parent to request sending of the event to interested parties.
6551     * <p>
6552     * If an {@link AccessibilityDelegate} has been specified via calling
6553     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6554     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6555     * responsible for handling this call.
6556     * </p>
6557     *
6558     * @param eventType The type of the event to send, as defined by several types from
6559     * {@link android.view.accessibility.AccessibilityEvent}, such as
6560     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6561     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6562     *
6563     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6564     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6565     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6566     * @see AccessibilityDelegate
6567     */
6568    public void sendAccessibilityEvent(int eventType) {
6569        if (mAccessibilityDelegate != null) {
6570            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6571        } else {
6572            sendAccessibilityEventInternal(eventType);
6573        }
6574    }
6575
6576    /**
6577     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6578     * {@link AccessibilityEvent} to make an announcement which is related to some
6579     * sort of a context change for which none of the events representing UI transitions
6580     * is a good fit. For example, announcing a new page in a book. If accessibility
6581     * is not enabled this method does nothing.
6582     *
6583     * @param text The announcement text.
6584     */
6585    public void announceForAccessibility(CharSequence text) {
6586        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6587            AccessibilityEvent event = AccessibilityEvent.obtain(
6588                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6589            onInitializeAccessibilityEvent(event);
6590            event.getText().add(text);
6591            event.setContentDescription(null);
6592            mParent.requestSendAccessibilityEvent(this, event);
6593        }
6594    }
6595
6596    /**
6597     * @see #sendAccessibilityEvent(int)
6598     *
6599     * Note: Called from the default {@link AccessibilityDelegate}.
6600     *
6601     * @hide
6602     */
6603    public void sendAccessibilityEventInternal(int eventType) {
6604        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6605            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6606        }
6607    }
6608
6609    /**
6610     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6611     * takes as an argument an empty {@link AccessibilityEvent} and does not
6612     * perform a check whether accessibility is enabled.
6613     * <p>
6614     * If an {@link AccessibilityDelegate} has been specified via calling
6615     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6616     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6617     * is responsible for handling this call.
6618     * </p>
6619     *
6620     * @param event The event to send.
6621     *
6622     * @see #sendAccessibilityEvent(int)
6623     */
6624    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6625        if (mAccessibilityDelegate != null) {
6626            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6627        } else {
6628            sendAccessibilityEventUncheckedInternal(event);
6629        }
6630    }
6631
6632    /**
6633     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6634     *
6635     * Note: Called from the default {@link AccessibilityDelegate}.
6636     *
6637     * @hide
6638     */
6639    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6640        if (!isShown()) {
6641            return;
6642        }
6643        onInitializeAccessibilityEvent(event);
6644        // Only a subset of accessibility events populates text content.
6645        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6646            dispatchPopulateAccessibilityEvent(event);
6647        }
6648        // In the beginning we called #isShown(), so we know that getParent() is not null.
6649        getParent().requestSendAccessibilityEvent(this, event);
6650    }
6651
6652    /**
6653     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6654     * to its children for adding their text content to the event. Note that the
6655     * event text is populated in a separate dispatch path since we add to the
6656     * event not only the text of the source but also the text of all its descendants.
6657     * A typical implementation will call
6658     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6659     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6660     * on each child. Override this method if custom population of the event text
6661     * content is required.
6662     * <p>
6663     * If an {@link AccessibilityDelegate} has been specified via calling
6664     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6665     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6666     * is responsible for handling this call.
6667     * </p>
6668     * <p>
6669     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6670     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6671     * </p>
6672     *
6673     * @param event The event.
6674     *
6675     * @return True if the event population was completed.
6676     */
6677    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6678        if (mAccessibilityDelegate != null) {
6679            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6680        } else {
6681            return dispatchPopulateAccessibilityEventInternal(event);
6682        }
6683    }
6684
6685    /**
6686     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6687     *
6688     * Note: Called from the default {@link AccessibilityDelegate}.
6689     *
6690     * @hide
6691     */
6692    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6693        onPopulateAccessibilityEvent(event);
6694        return false;
6695    }
6696
6697    /**
6698     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6699     * giving a chance to this View to populate the accessibility event with its
6700     * text content. While this method is free to modify event
6701     * attributes other than text content, doing so should normally be performed in
6702     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6703     * <p>
6704     * Example: Adding formatted date string to an accessibility event in addition
6705     *          to the text added by the super implementation:
6706     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6707     *     super.onPopulateAccessibilityEvent(event);
6708     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6709     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6710     *         mCurrentDate.getTimeInMillis(), flags);
6711     *     event.getText().add(selectedDateUtterance);
6712     * }</pre>
6713     * <p>
6714     * If an {@link AccessibilityDelegate} has been specified via calling
6715     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6716     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6717     * is responsible for handling this call.
6718     * </p>
6719     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6720     * information to the event, in case the default implementation has basic information to add.
6721     * </p>
6722     *
6723     * @param event The accessibility event which to populate.
6724     *
6725     * @see #sendAccessibilityEvent(int)
6726     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6727     */
6728    @CallSuper
6729    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6730        if (mAccessibilityDelegate != null) {
6731            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6732        } else {
6733            onPopulateAccessibilityEventInternal(event);
6734        }
6735    }
6736
6737    /**
6738     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6739     *
6740     * Note: Called from the default {@link AccessibilityDelegate}.
6741     *
6742     * @hide
6743     */
6744    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6745    }
6746
6747    /**
6748     * Initializes an {@link AccessibilityEvent} with information about
6749     * this View which is the event source. In other words, the source of
6750     * an accessibility event is the view whose state change triggered firing
6751     * the event.
6752     * <p>
6753     * Example: Setting the password property of an event in addition
6754     *          to properties set by the super implementation:
6755     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6756     *     super.onInitializeAccessibilityEvent(event);
6757     *     event.setPassword(true);
6758     * }</pre>
6759     * <p>
6760     * If an {@link AccessibilityDelegate} has been specified via calling
6761     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6762     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6763     * is responsible for handling this call.
6764     * </p>
6765     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6766     * information to the event, in case the default implementation has basic information to add.
6767     * </p>
6768     * @param event The event to initialize.
6769     *
6770     * @see #sendAccessibilityEvent(int)
6771     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6772     */
6773    @CallSuper
6774    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6775        if (mAccessibilityDelegate != null) {
6776            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6777        } else {
6778            onInitializeAccessibilityEventInternal(event);
6779        }
6780    }
6781
6782    /**
6783     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6784     *
6785     * Note: Called from the default {@link AccessibilityDelegate}.
6786     *
6787     * @hide
6788     */
6789    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6790        event.setSource(this);
6791        event.setClassName(getAccessibilityClassName());
6792        event.setPackageName(getContext().getPackageName());
6793        event.setEnabled(isEnabled());
6794        event.setContentDescription(mContentDescription);
6795
6796        switch (event.getEventType()) {
6797            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6798                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6799                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6800                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6801                event.setItemCount(focusablesTempList.size());
6802                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6803                if (mAttachInfo != null) {
6804                    focusablesTempList.clear();
6805                }
6806            } break;
6807            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6808                CharSequence text = getIterableTextForAccessibility();
6809                if (text != null && text.length() > 0) {
6810                    event.setFromIndex(getAccessibilitySelectionStart());
6811                    event.setToIndex(getAccessibilitySelectionEnd());
6812                    event.setItemCount(text.length());
6813                }
6814            } break;
6815        }
6816    }
6817
6818    /**
6819     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6820     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6821     * This method is responsible for obtaining an accessibility node info from a
6822     * pool of reusable instances and calling
6823     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6824     * initialize the former.
6825     * <p>
6826     * Note: The client is responsible for recycling the obtained instance by calling
6827     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6828     * </p>
6829     *
6830     * @return A populated {@link AccessibilityNodeInfo}.
6831     *
6832     * @see AccessibilityNodeInfo
6833     */
6834    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6835        if (mAccessibilityDelegate != null) {
6836            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6837        } else {
6838            return createAccessibilityNodeInfoInternal();
6839        }
6840    }
6841
6842    /**
6843     * @see #createAccessibilityNodeInfo()
6844     *
6845     * @hide
6846     */
6847    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6848        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6849        if (provider != null) {
6850            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6851        } else {
6852            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6853            onInitializeAccessibilityNodeInfo(info);
6854            return info;
6855        }
6856    }
6857
6858    /**
6859     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6860     * The base implementation sets:
6861     * <ul>
6862     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6863     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6864     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6865     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6866     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6867     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6868     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6869     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6870     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6871     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6872     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6873     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6874     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6875     * </ul>
6876     * <p>
6877     * Subclasses should override this method, call the super implementation,
6878     * and set additional attributes.
6879     * </p>
6880     * <p>
6881     * If an {@link AccessibilityDelegate} has been specified via calling
6882     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6883     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6884     * is responsible for handling this call.
6885     * </p>
6886     *
6887     * @param info The instance to initialize.
6888     */
6889    @CallSuper
6890    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6891        if (mAccessibilityDelegate != null) {
6892            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6893        } else {
6894            onInitializeAccessibilityNodeInfoInternal(info);
6895        }
6896    }
6897
6898    /**
6899     * Gets the location of this view in screen coordinates.
6900     *
6901     * @param outRect The output location
6902     * @hide
6903     */
6904    public void getBoundsOnScreen(Rect outRect) {
6905        getBoundsOnScreen(outRect, false);
6906    }
6907
6908    /**
6909     * Gets the location of this view in screen coordinates.
6910     *
6911     * @param outRect The output location
6912     * @param clipToParent Whether to clip child bounds to the parent ones.
6913     * @hide
6914     */
6915    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6916        if (mAttachInfo == null) {
6917            return;
6918        }
6919
6920        RectF position = mAttachInfo.mTmpTransformRect;
6921        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6922
6923        if (!hasIdentityMatrix()) {
6924            getMatrix().mapRect(position);
6925        }
6926
6927        position.offset(mLeft, mTop);
6928
6929        ViewParent parent = mParent;
6930        while (parent instanceof View) {
6931            View parentView = (View) parent;
6932
6933            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6934
6935            if (clipToParent) {
6936                position.left = Math.max(position.left, 0);
6937                position.top = Math.max(position.top, 0);
6938                position.right = Math.min(position.right, parentView.getWidth());
6939                position.bottom = Math.min(position.bottom, parentView.getHeight());
6940            }
6941
6942            if (!parentView.hasIdentityMatrix()) {
6943                parentView.getMatrix().mapRect(position);
6944            }
6945
6946            position.offset(parentView.mLeft, parentView.mTop);
6947
6948            parent = parentView.mParent;
6949        }
6950
6951        if (parent instanceof ViewRootImpl) {
6952            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6953            position.offset(0, -viewRootImpl.mCurScrollY);
6954        }
6955
6956        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6957
6958        outRect.set(Math.round(position.left), Math.round(position.top),
6959                Math.round(position.right), Math.round(position.bottom));
6960    }
6961
6962    /**
6963     * Return the class name of this object to be used for accessibility purposes.
6964     * Subclasses should only override this if they are implementing something that
6965     * should be seen as a completely new class of view when used by accessibility,
6966     * unrelated to the class it is deriving from.  This is used to fill in
6967     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6968     */
6969    public CharSequence getAccessibilityClassName() {
6970        return View.class.getName();
6971    }
6972
6973    /**
6974     * Called when assist structure is being retrieved from a view as part of
6975     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6976     * @param structure Fill in with structured view data.  The default implementation
6977     * fills in all data that can be inferred from the view itself.
6978     */
6979    public void onProvideStructure(ViewStructure structure) {
6980        onProvideStructureForAssistOrAutoFill(structure, false);
6981    }
6982
6983    /**
6984     * Called when assist structure is being retrieved from a view as part of an auto-fill request.
6985     *
6986     * <p>When implementing this method, subclasses must also:
6987     *
6988     * <ol>
6989     * <li>Implement {@link #autoFill(AutoFillValue)}, {@link #getAutoFillType()}
6990     * and {@link #getAutoFillValue()}.
6991     * <li>Call {@link android.view.autofill.AutoFillManager#virtualValueChanged(View, int,
6992     * AutoFillValue)} when its value changed.
6993     * </ol>
6994     *
6995     * @param structure Fill in with structured view data. The default implementation
6996     * fills in all data that can be inferred from the view itself.
6997     * @param flags optional flags (currently {@code 0}).
6998     */
6999    public void onProvideAutoFillStructure(ViewStructure structure, int flags) {
7000        onProvideStructureForAssistOrAutoFill(structure, true);
7001    }
7002
7003    private void onProvideStructureForAssistOrAutoFill(ViewStructure structure,
7004            boolean forAutoFill) {
7005        final int id = mID;
7006        if (id != NO_ID && !isViewIdGenerated(id)) {
7007            String pkg, type, entry;
7008            try {
7009                final Resources res = getResources();
7010                entry = res.getResourceEntryName(id);
7011                type = res.getResourceTypeName(id);
7012                pkg = res.getResourcePackageName(id);
7013            } catch (Resources.NotFoundException e) {
7014                entry = type = pkg = null;
7015            }
7016            structure.setId(id, pkg, type, entry);
7017        } else {
7018            structure.setId(id, null, null, null);
7019        }
7020
7021        if (forAutoFill) {
7022            final AutoFillType autoFillType = getAutoFillType();
7023            // Don't need to fill auto-fill info if view does not support it.
7024            // For example, only TextViews that are editable support auto-fill
7025            if (autoFillType != null) {
7026                // The auto-fill id needs to be unique, but its value doesn't matter, so it's better
7027                // to reuse the accessibility id to save space.
7028                structure.setAutoFillId(getAccessibilityViewId());
7029                structure.setAutoFillType(autoFillType);
7030                structure.setAutoFillValue(getAutoFillValue());
7031            }
7032        }
7033
7034        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
7035        if (!hasIdentityMatrix()) {
7036            structure.setTransformation(getMatrix());
7037        }
7038        structure.setElevation(getZ());
7039        structure.setVisibility(getVisibility());
7040        structure.setEnabled(isEnabled());
7041        if (isClickable()) {
7042            structure.setClickable(true);
7043        }
7044        if (isFocusable()) {
7045            structure.setFocusable(true);
7046        }
7047        if (isFocused()) {
7048            structure.setFocused(true);
7049        }
7050        if (isAccessibilityFocused()) {
7051            structure.setAccessibilityFocused(true);
7052        }
7053        if (isSelected()) {
7054            structure.setSelected(true);
7055        }
7056        if (isActivated()) {
7057            structure.setActivated(true);
7058        }
7059        if (isLongClickable()) {
7060            structure.setLongClickable(true);
7061        }
7062        if (this instanceof Checkable) {
7063            structure.setCheckable(true);
7064            if (((Checkable)this).isChecked()) {
7065                structure.setChecked(true);
7066            }
7067        }
7068        if (isContextClickable()) {
7069            structure.setContextClickable(true);
7070        }
7071        structure.setClassName(getAccessibilityClassName().toString());
7072        structure.setContentDescription(getContentDescription());
7073    }
7074
7075    /**
7076     * Called when assist structure is being retrieved from a view as part of
7077     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
7078     * generate additional virtual structure under this view.  The defaullt implementation
7079     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
7080     * view's virtual accessibility nodes, if any.  You can override this for a more
7081     * optimal implementation providing this data.
7082     */
7083    public void onProvideVirtualStructure(ViewStructure structure) {
7084        onProvideVirtualStructureForAssistOrAutoFill(structure, false);
7085    }
7086
7087    /**
7088     * Called when assist structure is being retrieved from a view as part of an auto-fill request
7089     * to generate additional virtual structure under this view.
7090     *
7091     * <p>The default implementation uses {@link #getAccessibilityNodeProvider()} to try to
7092     * generate this from the view's virtual accessibility nodes, if any. You can override this
7093     * for a more optimal implementation providing this data.
7094     *
7095     * <p>When implementing this method, subclasses must follow the rules below:
7096     *
7097     * <ol>
7098     * <li>Also implement {@link #autoFillVirtual(int, AutoFillValue)} to auto-fill the virtual
7099     * children.
7100     * <li>Call {@link android.view.autofill.AutoFillManager#virtualFocusChanged(View, int, Rect,
7101     * boolean)} when the focus inside the view changed.
7102     * <li>Call {@link android.view.autofill.AutoFillManager#virtualValueChanged(View, int,
7103     * AutoFillValue)} when the value of a child changed.
7104     * <li>Call {@link android.view.autofill.AutoFillManager#reset()} when the auto-fill context
7105     * of the view structure changed.
7106     * </ol>
7107     *
7108     * @param structure Fill in with structured view data.
7109     * @param flags optional flags (currently {@code 0}).
7110     */
7111    public void onProvideAutoFillVirtualStructure(ViewStructure structure, int flags) {
7112        onProvideVirtualStructureForAssistOrAutoFill(structure, true);
7113    }
7114
7115    private void onProvideVirtualStructureForAssistOrAutoFill(ViewStructure structure,
7116            boolean forAutoFill) {
7117        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7118        // this method should take a boolean with the type of request.
7119        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7120        if (provider != null) {
7121            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7122            structure.setChildCount(1);
7123            ViewStructure root = structure.newChild(0);
7124            populateVirtualStructure(root, provider, info, forAutoFill);
7125            info.recycle();
7126        }
7127    }
7128
7129    /**
7130     * Automatically fills the content of this view with the {@code value}.
7131     *
7132     * <p>By default does nothing, but views should override it (and {@link #getAutoFillType()},
7133     * {@link #getAutoFillValue()}, and {@link #onProvideAutoFillStructure(ViewStructure, int)}
7134     * to support the AutoFill Framework.
7135     *
7136     * <p>Typically, it is implemented by:
7137     *
7138     * <ol>
7139     * <li>Calling the proper getter method on {@link AutoFillValue} to fetch the actual value.
7140     * <li>Passing the actual value to the equivalent setter in the view.
7141     * <ol>
7142     *
7143     * <p>For example, a text-field view would call:
7144     *
7145     * <pre class="prettyprint">
7146     * CharSequence text = value.getTextValue();
7147     * if (text != null) {
7148     *     setText(text);
7149     * }
7150     * </pre>
7151     *
7152     * @param value value to be auto-filled.
7153     */
7154    public void autoFill(@SuppressWarnings("unused") AutoFillValue value) {
7155    }
7156
7157    /**
7158     * Automatically fills the content of a virtual view with the {@code value}
7159     *
7160     * <p>See {@link #autoFill(AutoFillValue)} and
7161     * {@link #onProvideAutoFillVirtualStructure(ViewStructure, int)} for more info.
7162     *
7163     * @param value value to be auto-filled.
7164     * @param virtualId id identifying the virtual child inside the custom view.
7165     */
7166    public void autoFillVirtual(@SuppressWarnings("unused") int virtualId,
7167            @SuppressWarnings("unused") AutoFillValue value) {
7168    }
7169
7170    /**
7171     * Describes the auto-fill type that should be used on calls to
7172     * {@link #autoFill(AutoFillValue)} and {@link #autoFillVirtual(int, AutoFillValue)}.
7173
7174     * <p>By default returns {@code null}, but views should override it (and
7175     * {@link #autoFill(AutoFillValue)} to support the AutoFill Framework.
7176     */
7177    @Nullable
7178    public AutoFillType getAutoFillType() {
7179        return null;
7180    }
7181
7182    /**
7183     * Gets the {@link View}'s current auto-fill value.
7184     *
7185     * <p>By default returns {@code null}, but views should override it,
7186     * {@link #autoFill(AutoFillValue)}, and {@link #getAutoFillType()} to support the AutoFill
7187     * Framework.
7188     */
7189    @Nullable
7190    public AutoFillValue getAutoFillValue() {
7191        return null;
7192    }
7193
7194    @Nullable
7195    private AutoFillManager getAutoFillManager() {
7196        return mContext.getSystemService(AutoFillManager.class);
7197    }
7198
7199    private boolean isAutoFillable() {
7200        return getAutoFillType() != null && !isAutoFillBlocked();
7201    }
7202
7203    private void populateVirtualStructure(ViewStructure structure,
7204            AccessibilityNodeProvider provider, AccessibilityNodeInfo info, boolean forAutoFill) {
7205        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
7206                null, null, null);
7207        Rect rect = structure.getTempRect();
7208        info.getBoundsInParent(rect);
7209        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
7210        structure.setVisibility(VISIBLE);
7211        structure.setEnabled(info.isEnabled());
7212        if (info.isClickable()) {
7213            structure.setClickable(true);
7214        }
7215        if (info.isFocusable()) {
7216            structure.setFocusable(true);
7217        }
7218        if (info.isFocused()) {
7219            structure.setFocused(true);
7220        }
7221        if (info.isAccessibilityFocused()) {
7222            structure.setAccessibilityFocused(true);
7223        }
7224        if (info.isSelected()) {
7225            structure.setSelected(true);
7226        }
7227        if (info.isLongClickable()) {
7228            structure.setLongClickable(true);
7229        }
7230        if (info.isCheckable()) {
7231            structure.setCheckable(true);
7232            if (info.isChecked()) {
7233                structure.setChecked(true);
7234            }
7235        }
7236        if (info.isContextClickable()) {
7237            structure.setContextClickable(true);
7238        }
7239        CharSequence cname = info.getClassName();
7240        structure.setClassName(cname != null ? cname.toString() : null);
7241        structure.setContentDescription(info.getContentDescription());
7242        if (!forAutoFill && (info.getText() != null || info.getError() != null)) {
7243            // TODO(b/33197203) (b/33269702): when sanitized, try to use the Accessibility API to
7244            // just set sanitized values (like text coming from resource files), rather than not
7245            // setting it at all.
7246            structure.setText(info.getText(), info.getTextSelectionStart(),
7247                    info.getTextSelectionEnd());
7248        }
7249        final int NCHILDREN = info.getChildCount();
7250        if (NCHILDREN > 0) {
7251            structure.setChildCount(NCHILDREN);
7252            for (int i=0; i<NCHILDREN; i++) {
7253                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
7254                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
7255                ViewStructure child = structure.newChild(i);
7256                populateVirtualStructure(child, provider, cinfo, forAutoFill);
7257                cinfo.recycle();
7258            }
7259        }
7260    }
7261
7262    /**
7263     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
7264     * implementation calls {@link #onProvideStructure} and
7265     * {@link #onProvideVirtualStructure}.
7266     */
7267    public void dispatchProvideStructure(ViewStructure structure) {
7268        dispatchProvideStructureForAssistOrAutoFill(structure, false);
7269    }
7270
7271    /**
7272     * Dispatch creation of {@link ViewStructure} down the hierarchy.
7273     *
7274     * <p>The structure must be filled according to the request type, which is set in the
7275     * {@code flags} parameter - see the documentation on each flag for more details.
7276     *
7277     * <p>The default implementation calls {@link #onProvideAutoFillStructure(ViewStructure, int)}
7278     * and {@link #onProvideAutoFillVirtualStructure(ViewStructure, int)}.
7279     *
7280     * @param structure Fill in with structured view data.
7281     * @param flags optional flags (currently {@code 0}).
7282     */
7283    public void dispatchProvideAutoFillStructure(ViewStructure structure, int flags) {
7284        dispatchProvideStructureForAssistOrAutoFill(structure, true);
7285    }
7286
7287    private void dispatchProvideStructureForAssistOrAutoFill(ViewStructure structure,
7288            boolean forAutoFill) {
7289        boolean blocked = forAutoFill ? isAutoFillBlocked() : isAssistBlocked();
7290        if (!blocked) {
7291            if (forAutoFill) {
7292                // The auto-fill id needs to be unique, but its value doesn't matter,
7293                // so it's better to reuse the accessibility id to save space.
7294                structure.setAutoFillId(getAccessibilityViewId());
7295                // NOTE: flags are not currently supported, hence 0
7296                onProvideAutoFillStructure(structure, 0);
7297                onProvideAutoFillVirtualStructure(structure, 0);
7298            } else {
7299                onProvideStructure(structure);
7300                onProvideVirtualStructure(structure);
7301            }
7302        } else {
7303            structure.setClassName(getAccessibilityClassName().toString());
7304            structure.setAssistBlocked(true);
7305        }
7306    }
7307
7308    /**
7309     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
7310     *
7311     * Note: Called from the default {@link AccessibilityDelegate}.
7312     *
7313     * @hide
7314     */
7315    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
7316        if (mAttachInfo == null) {
7317            return;
7318        }
7319
7320        Rect bounds = mAttachInfo.mTmpInvalRect;
7321
7322        getDrawingRect(bounds);
7323        info.setBoundsInParent(bounds);
7324
7325        getBoundsOnScreen(bounds, true);
7326        info.setBoundsInScreen(bounds);
7327
7328        ViewParent parent = getParentForAccessibility();
7329        if (parent instanceof View) {
7330            info.setParent((View) parent);
7331        }
7332
7333        if (mID != View.NO_ID) {
7334            View rootView = getRootView();
7335            if (rootView == null) {
7336                rootView = this;
7337            }
7338
7339            View label = rootView.findLabelForView(this, mID);
7340            if (label != null) {
7341                info.setLabeledBy(label);
7342            }
7343
7344            if ((mAttachInfo.mAccessibilityFetchFlags
7345                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
7346                    && Resources.resourceHasPackage(mID)) {
7347                try {
7348                    String viewId = getResources().getResourceName(mID);
7349                    info.setViewIdResourceName(viewId);
7350                } catch (Resources.NotFoundException nfe) {
7351                    /* ignore */
7352                }
7353            }
7354        }
7355
7356        if (mLabelForId != View.NO_ID) {
7357            View rootView = getRootView();
7358            if (rootView == null) {
7359                rootView = this;
7360            }
7361            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
7362            if (labeled != null) {
7363                info.setLabelFor(labeled);
7364            }
7365        }
7366
7367        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
7368            View rootView = getRootView();
7369            if (rootView == null) {
7370                rootView = this;
7371            }
7372            View next = rootView.findViewInsideOutShouldExist(this,
7373                    mAccessibilityTraversalBeforeId);
7374            if (next != null && next.includeForAccessibility()) {
7375                info.setTraversalBefore(next);
7376            }
7377        }
7378
7379        if (mAccessibilityTraversalAfterId != View.NO_ID) {
7380            View rootView = getRootView();
7381            if (rootView == null) {
7382                rootView = this;
7383            }
7384            View next = rootView.findViewInsideOutShouldExist(this,
7385                    mAccessibilityTraversalAfterId);
7386            if (next != null && next.includeForAccessibility()) {
7387                info.setTraversalAfter(next);
7388            }
7389        }
7390
7391        info.setVisibleToUser(isVisibleToUser());
7392
7393        info.setImportantForAccessibility(isImportantForAccessibility());
7394        info.setPackageName(mContext.getPackageName());
7395        info.setClassName(getAccessibilityClassName());
7396        info.setContentDescription(getContentDescription());
7397
7398        info.setEnabled(isEnabled());
7399        info.setClickable(isClickable());
7400        info.setFocusable(isFocusable());
7401        info.setFocused(isFocused());
7402        info.setAccessibilityFocused(isAccessibilityFocused());
7403        info.setSelected(isSelected());
7404        info.setLongClickable(isLongClickable());
7405        info.setContextClickable(isContextClickable());
7406        info.setLiveRegion(getAccessibilityLiveRegion());
7407
7408        // TODO: These make sense only if we are in an AdapterView but all
7409        // views can be selected. Maybe from accessibility perspective
7410        // we should report as selectable view in an AdapterView.
7411        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
7412        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
7413
7414        if (isFocusable()) {
7415            if (isFocused()) {
7416                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
7417            } else {
7418                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
7419            }
7420        }
7421
7422        if (!isAccessibilityFocused()) {
7423            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
7424        } else {
7425            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
7426        }
7427
7428        if (isClickable() && isEnabled()) {
7429            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
7430        }
7431
7432        if (isLongClickable() && isEnabled()) {
7433            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
7434        }
7435
7436        if (isContextClickable() && isEnabled()) {
7437            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
7438        }
7439
7440        CharSequence text = getIterableTextForAccessibility();
7441        if (text != null && text.length() > 0) {
7442            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
7443
7444            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
7445            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
7446            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
7447            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
7448                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
7449                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
7450        }
7451
7452        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
7453        populateAccessibilityNodeInfoDrawingOrderInParent(info);
7454    }
7455
7456    /**
7457     * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
7458     * additional data.
7459     * <p>
7460     * This method only needs overloading if the node is marked as having extra data available.
7461     * </p>
7462     *
7463     * @param info The info to which to add the extra data. Never {@code null}.
7464     * @param extraDataKey A key specifying the type of extra data to add to the info. The
7465     *                     extra data should be added to the {@link Bundle} returned by
7466     *                     the info's {@link AccessibilityNodeInfo#getExtras} method. Never
7467     *                     {@code null}.
7468     * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be
7469     *                  {@code null} if the service provided no arguments.
7470     *
7471     * @see AccessibilityNodeInfo#setExtraAvailableData
7472     */
7473    public void addExtraDataToAccessibilityNodeInfo(
7474            @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
7475            @Nullable Bundle arguments) {
7476    }
7477
7478    /**
7479     * Determine the order in which this view will be drawn relative to its siblings for a11y
7480     *
7481     * @param info The info whose drawing order should be populated
7482     */
7483    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7484        /*
7485         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7486         * drawing order may not be well-defined, and some Views with custom drawing order may
7487         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7488         */
7489        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7490            info.setDrawingOrder(0);
7491            return;
7492        }
7493        int drawingOrderInParent = 1;
7494        // Iterate up the hierarchy if parents are not important for a11y
7495        View viewAtDrawingLevel = this;
7496        final ViewParent parent = getParentForAccessibility();
7497        while (viewAtDrawingLevel != parent) {
7498            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7499            if (!(currentParent instanceof ViewGroup)) {
7500                // Should only happen for the Decor
7501                drawingOrderInParent = 0;
7502                break;
7503            } else {
7504                final ViewGroup parentGroup = (ViewGroup) currentParent;
7505                final int childCount = parentGroup.getChildCount();
7506                if (childCount > 1) {
7507                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7508                    if (preorderedList != null) {
7509                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7510                        for (int i = 0; i < childDrawIndex; i++) {
7511                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7512                        }
7513                    } else {
7514                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7515                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7516                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7517                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7518                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7519                        if (childDrawIndex != 0) {
7520                            for (int i = 0; i < numChildrenToIterate; i++) {
7521                                final int otherDrawIndex = (customOrder ?
7522                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7523                                if (otherDrawIndex < childDrawIndex) {
7524                                    drawingOrderInParent +=
7525                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7526                                }
7527                            }
7528                        }
7529                    }
7530                }
7531            }
7532            viewAtDrawingLevel = (View) currentParent;
7533        }
7534        info.setDrawingOrder(drawingOrderInParent);
7535    }
7536
7537    private static int numViewsForAccessibility(View view) {
7538        if (view != null) {
7539            if (view.includeForAccessibility()) {
7540                return 1;
7541            } else if (view instanceof ViewGroup) {
7542                return ((ViewGroup) view).getNumChildrenForAccessibility();
7543            }
7544        }
7545        return 0;
7546    }
7547
7548    private View findLabelForView(View view, int labeledId) {
7549        if (mMatchLabelForPredicate == null) {
7550            mMatchLabelForPredicate = new MatchLabelForPredicate();
7551        }
7552        mMatchLabelForPredicate.mLabeledId = labeledId;
7553        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7554    }
7555
7556    /**
7557     * Computes whether this view is visible to the user. Such a view is
7558     * attached, visible, all its predecessors are visible, it is not clipped
7559     * entirely by its predecessors, and has an alpha greater than zero.
7560     *
7561     * @return Whether the view is visible on the screen.
7562     *
7563     * @hide
7564     */
7565    protected boolean isVisibleToUser() {
7566        return isVisibleToUser(null);
7567    }
7568
7569    /**
7570     * Computes whether the given portion of this view is visible to the user.
7571     * Such a view is attached, visible, all its predecessors are visible,
7572     * has an alpha greater than zero, and the specified portion is not
7573     * clipped entirely by its predecessors.
7574     *
7575     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7576     *                    <code>null</code>, and the entire view will be tested in this case.
7577     *                    When <code>true</code> is returned by the function, the actual visible
7578     *                    region will be stored in this parameter; that is, if boundInView is fully
7579     *                    contained within the view, no modification will be made, otherwise regions
7580     *                    outside of the visible area of the view will be clipped.
7581     *
7582     * @return Whether the specified portion of the view is visible on the screen.
7583     *
7584     * @hide
7585     */
7586    protected boolean isVisibleToUser(Rect boundInView) {
7587        if (mAttachInfo != null) {
7588            // Attached to invisible window means this view is not visible.
7589            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7590                return false;
7591            }
7592            // An invisible predecessor or one with alpha zero means
7593            // that this view is not visible to the user.
7594            Object current = this;
7595            while (current instanceof View) {
7596                View view = (View) current;
7597                // We have attach info so this view is attached and there is no
7598                // need to check whether we reach to ViewRootImpl on the way up.
7599                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7600                        view.getVisibility() != VISIBLE) {
7601                    return false;
7602                }
7603                current = view.mParent;
7604            }
7605            // Check if the view is entirely covered by its predecessors.
7606            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7607            Point offset = mAttachInfo.mPoint;
7608            if (!getGlobalVisibleRect(visibleRect, offset)) {
7609                return false;
7610            }
7611            // Check if the visible portion intersects the rectangle of interest.
7612            if (boundInView != null) {
7613                visibleRect.offset(-offset.x, -offset.y);
7614                return boundInView.intersect(visibleRect);
7615            }
7616            return true;
7617        }
7618        return false;
7619    }
7620
7621    /**
7622     * Returns the delegate for implementing accessibility support via
7623     * composition. For more details see {@link AccessibilityDelegate}.
7624     *
7625     * @return The delegate, or null if none set.
7626     *
7627     * @hide
7628     */
7629    public AccessibilityDelegate getAccessibilityDelegate() {
7630        return mAccessibilityDelegate;
7631    }
7632
7633    /**
7634     * Sets a delegate for implementing accessibility support via composition
7635     * (as opposed to inheritance). For more details, see
7636     * {@link AccessibilityDelegate}.
7637     * <p>
7638     * <strong>Note:</strong> On platform versions prior to
7639     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7640     * views in the {@code android.widget.*} package are called <i>before</i>
7641     * host methods. This prevents certain properties such as class name from
7642     * being modified by overriding
7643     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7644     * as any changes will be overwritten by the host class.
7645     * <p>
7646     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7647     * methods are called <i>after</i> host methods, which all properties to be
7648     * modified without being overwritten by the host class.
7649     *
7650     * @param delegate the object to which accessibility method calls should be
7651     *                 delegated
7652     * @see AccessibilityDelegate
7653     */
7654    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7655        mAccessibilityDelegate = delegate;
7656    }
7657
7658    /**
7659     * Gets the provider for managing a virtual view hierarchy rooted at this View
7660     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7661     * that explore the window content.
7662     * <p>
7663     * If this method returns an instance, this instance is responsible for managing
7664     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7665     * View including the one representing the View itself. Similarly the returned
7666     * instance is responsible for performing accessibility actions on any virtual
7667     * view or the root view itself.
7668     * </p>
7669     * <p>
7670     * If an {@link AccessibilityDelegate} has been specified via calling
7671     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7672     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7673     * is responsible for handling this call.
7674     * </p>
7675     *
7676     * @return The provider.
7677     *
7678     * @see AccessibilityNodeProvider
7679     */
7680    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7681        if (mAccessibilityDelegate != null) {
7682            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7683        } else {
7684            return null;
7685        }
7686    }
7687
7688    /**
7689     * Gets the unique identifier of this view on the screen for accessibility purposes.
7690     *
7691     * @return The view accessibility id.
7692     *
7693     * @hide
7694     */
7695    public int getAccessibilityViewId() {
7696        if (mAccessibilityViewId == NO_ID) {
7697            mAccessibilityViewId = sNextAccessibilityViewId++;
7698        }
7699        return mAccessibilityViewId;
7700    }
7701
7702    /**
7703     * Gets the unique identifier of the window in which this View reseides.
7704     *
7705     * @return The window accessibility id.
7706     *
7707     * @hide
7708     */
7709    public int getAccessibilityWindowId() {
7710        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7711                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7712    }
7713
7714    /**
7715     * Returns the {@link View}'s content description.
7716     * <p>
7717     * <strong>Note:</strong> Do not override this method, as it will have no
7718     * effect on the content description presented to accessibility services.
7719     * You must call {@link #setContentDescription(CharSequence)} to modify the
7720     * content description.
7721     *
7722     * @return the content description
7723     * @see #setContentDescription(CharSequence)
7724     * @attr ref android.R.styleable#View_contentDescription
7725     */
7726    @ViewDebug.ExportedProperty(category = "accessibility")
7727    public CharSequence getContentDescription() {
7728        return mContentDescription;
7729    }
7730
7731    /**
7732     * Sets the {@link View}'s content description.
7733     * <p>
7734     * A content description briefly describes the view and is primarily used
7735     * for accessibility support to determine how a view should be presented to
7736     * the user. In the case of a view with no textual representation, such as
7737     * {@link android.widget.ImageButton}, a useful content description
7738     * explains what the view does. For example, an image button with a phone
7739     * icon that is used to place a call may use "Call" as its content
7740     * description. An image of a floppy disk that is used to save a file may
7741     * use "Save".
7742     *
7743     * @param contentDescription The content description.
7744     * @see #getContentDescription()
7745     * @attr ref android.R.styleable#View_contentDescription
7746     */
7747    @RemotableViewMethod
7748    public void setContentDescription(CharSequence contentDescription) {
7749        if (mContentDescription == null) {
7750            if (contentDescription == null) {
7751                return;
7752            }
7753        } else if (mContentDescription.equals(contentDescription)) {
7754            return;
7755        }
7756        mContentDescription = contentDescription;
7757        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7758        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7759            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7760            notifySubtreeAccessibilityStateChangedIfNeeded();
7761        } else {
7762            notifyViewAccessibilityStateChangedIfNeeded(
7763                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7764        }
7765    }
7766
7767    /**
7768     * Sets the id of a view before which this one is visited in accessibility traversal.
7769     * A screen-reader must visit the content of this view before the content of the one
7770     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7771     * will traverse the entire content of B before traversing the entire content of A,
7772     * regardles of what traversal strategy it is using.
7773     * <p>
7774     * Views that do not have specified before/after relationships are traversed in order
7775     * determined by the screen-reader.
7776     * </p>
7777     * <p>
7778     * Setting that this view is before a view that is not important for accessibility
7779     * or if this view is not important for accessibility will have no effect as the
7780     * screen-reader is not aware of unimportant views.
7781     * </p>
7782     *
7783     * @param beforeId The id of a view this one precedes in accessibility traversal.
7784     *
7785     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7786     *
7787     * @see #setImportantForAccessibility(int)
7788     */
7789    @RemotableViewMethod
7790    public void setAccessibilityTraversalBefore(int beforeId) {
7791        if (mAccessibilityTraversalBeforeId == beforeId) {
7792            return;
7793        }
7794        mAccessibilityTraversalBeforeId = beforeId;
7795        notifyViewAccessibilityStateChangedIfNeeded(
7796                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7797    }
7798
7799    /**
7800     * Gets the id of a view before which this one is visited in accessibility traversal.
7801     *
7802     * @return The id of a view this one precedes in accessibility traversal if
7803     *         specified, otherwise {@link #NO_ID}.
7804     *
7805     * @see #setAccessibilityTraversalBefore(int)
7806     */
7807    public int getAccessibilityTraversalBefore() {
7808        return mAccessibilityTraversalBeforeId;
7809    }
7810
7811    /**
7812     * Sets the id of a view after which this one is visited in accessibility traversal.
7813     * A screen-reader must visit the content of the other view before the content of this
7814     * one. For example, if view B is set to be after view A, then a screen-reader
7815     * will traverse the entire content of A before traversing the entire content of B,
7816     * regardles of what traversal strategy it is using.
7817     * <p>
7818     * Views that do not have specified before/after relationships are traversed in order
7819     * determined by the screen-reader.
7820     * </p>
7821     * <p>
7822     * Setting that this view is after a view that is not important for accessibility
7823     * or if this view is not important for accessibility will have no effect as the
7824     * screen-reader is not aware of unimportant views.
7825     * </p>
7826     *
7827     * @param afterId The id of a view this one succedees in accessibility traversal.
7828     *
7829     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7830     *
7831     * @see #setImportantForAccessibility(int)
7832     */
7833    @RemotableViewMethod
7834    public void setAccessibilityTraversalAfter(int afterId) {
7835        if (mAccessibilityTraversalAfterId == afterId) {
7836            return;
7837        }
7838        mAccessibilityTraversalAfterId = afterId;
7839        notifyViewAccessibilityStateChangedIfNeeded(
7840                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7841    }
7842
7843    /**
7844     * Gets the id of a view after which this one is visited in accessibility traversal.
7845     *
7846     * @return The id of a view this one succeedes in accessibility traversal if
7847     *         specified, otherwise {@link #NO_ID}.
7848     *
7849     * @see #setAccessibilityTraversalAfter(int)
7850     */
7851    public int getAccessibilityTraversalAfter() {
7852        return mAccessibilityTraversalAfterId;
7853    }
7854
7855    /**
7856     * Gets the id of a view for which this view serves as a label for
7857     * accessibility purposes.
7858     *
7859     * @return The labeled view id.
7860     */
7861    @ViewDebug.ExportedProperty(category = "accessibility")
7862    public int getLabelFor() {
7863        return mLabelForId;
7864    }
7865
7866    /**
7867     * Sets the id of a view for which this view serves as a label for
7868     * accessibility purposes.
7869     *
7870     * @param id The labeled view id.
7871     */
7872    @RemotableViewMethod
7873    public void setLabelFor(@IdRes int id) {
7874        if (mLabelForId == id) {
7875            return;
7876        }
7877        mLabelForId = id;
7878        if (mLabelForId != View.NO_ID
7879                && mID == View.NO_ID) {
7880            mID = generateViewId();
7881        }
7882        notifyViewAccessibilityStateChangedIfNeeded(
7883                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7884    }
7885
7886    /**
7887     * Invoked whenever this view loses focus, either by losing window focus or by losing
7888     * focus within its window. This method can be used to clear any state tied to the
7889     * focus. For instance, if a button is held pressed with the trackball and the window
7890     * loses focus, this method can be used to cancel the press.
7891     *
7892     * Subclasses of View overriding this method should always call super.onFocusLost().
7893     *
7894     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7895     * @see #onWindowFocusChanged(boolean)
7896     *
7897     * @hide pending API council approval
7898     */
7899    @CallSuper
7900    protected void onFocusLost() {
7901        resetPressedState();
7902    }
7903
7904    private void resetPressedState() {
7905        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7906            return;
7907        }
7908
7909        if (isPressed()) {
7910            setPressed(false);
7911
7912            if (!mHasPerformedLongPress) {
7913                removeLongPressCallback();
7914            }
7915        }
7916    }
7917
7918    /**
7919     * Returns true if this view has focus
7920     *
7921     * @return True if this view has focus, false otherwise.
7922     */
7923    @ViewDebug.ExportedProperty(category = "focus")
7924    public boolean isFocused() {
7925        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7926    }
7927
7928    /**
7929     * Find the view in the hierarchy rooted at this view that currently has
7930     * focus.
7931     *
7932     * @return The view that currently has focus, or null if no focused view can
7933     *         be found.
7934     */
7935    public View findFocus() {
7936        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7937    }
7938
7939    /**
7940     * Indicates whether this view is one of the set of scrollable containers in
7941     * its window.
7942     *
7943     * @return whether this view is one of the set of scrollable containers in
7944     * its window
7945     *
7946     * @attr ref android.R.styleable#View_isScrollContainer
7947     */
7948    public boolean isScrollContainer() {
7949        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7950    }
7951
7952    /**
7953     * Change whether this view is one of the set of scrollable containers in
7954     * its window.  This will be used to determine whether the window can
7955     * resize or must pan when a soft input area is open -- scrollable
7956     * containers allow the window to use resize mode since the container
7957     * will appropriately shrink.
7958     *
7959     * @attr ref android.R.styleable#View_isScrollContainer
7960     */
7961    public void setScrollContainer(boolean isScrollContainer) {
7962        if (isScrollContainer) {
7963            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7964                mAttachInfo.mScrollContainers.add(this);
7965                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7966            }
7967            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7968        } else {
7969            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7970                mAttachInfo.mScrollContainers.remove(this);
7971            }
7972            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7973        }
7974    }
7975
7976    /**
7977     * Returns the quality of the drawing cache.
7978     *
7979     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7980     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7981     *
7982     * @see #setDrawingCacheQuality(int)
7983     * @see #setDrawingCacheEnabled(boolean)
7984     * @see #isDrawingCacheEnabled()
7985     *
7986     * @attr ref android.R.styleable#View_drawingCacheQuality
7987     */
7988    @DrawingCacheQuality
7989    public int getDrawingCacheQuality() {
7990        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7991    }
7992
7993    /**
7994     * Set the drawing cache quality of this view. This value is used only when the
7995     * drawing cache is enabled
7996     *
7997     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7998     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7999     *
8000     * @see #getDrawingCacheQuality()
8001     * @see #setDrawingCacheEnabled(boolean)
8002     * @see #isDrawingCacheEnabled()
8003     *
8004     * @attr ref android.R.styleable#View_drawingCacheQuality
8005     */
8006    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
8007        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
8008    }
8009
8010    /**
8011     * Returns whether the screen should remain on, corresponding to the current
8012     * value of {@link #KEEP_SCREEN_ON}.
8013     *
8014     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
8015     *
8016     * @see #setKeepScreenOn(boolean)
8017     *
8018     * @attr ref android.R.styleable#View_keepScreenOn
8019     */
8020    public boolean getKeepScreenOn() {
8021        return (mViewFlags & KEEP_SCREEN_ON) != 0;
8022    }
8023
8024    /**
8025     * Controls whether the screen should remain on, modifying the
8026     * value of {@link #KEEP_SCREEN_ON}.
8027     *
8028     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
8029     *
8030     * @see #getKeepScreenOn()
8031     *
8032     * @attr ref android.R.styleable#View_keepScreenOn
8033     */
8034    public void setKeepScreenOn(boolean keepScreenOn) {
8035        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
8036    }
8037
8038    /**
8039     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
8040     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8041     *
8042     * @attr ref android.R.styleable#View_nextFocusLeft
8043     */
8044    public int getNextFocusLeftId() {
8045        return mNextFocusLeftId;
8046    }
8047
8048    /**
8049     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
8050     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
8051     * decide automatically.
8052     *
8053     * @attr ref android.R.styleable#View_nextFocusLeft
8054     */
8055    public void setNextFocusLeftId(int nextFocusLeftId) {
8056        mNextFocusLeftId = nextFocusLeftId;
8057    }
8058
8059    /**
8060     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
8061     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8062     *
8063     * @attr ref android.R.styleable#View_nextFocusRight
8064     */
8065    public int getNextFocusRightId() {
8066        return mNextFocusRightId;
8067    }
8068
8069    /**
8070     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
8071     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
8072     * decide automatically.
8073     *
8074     * @attr ref android.R.styleable#View_nextFocusRight
8075     */
8076    public void setNextFocusRightId(int nextFocusRightId) {
8077        mNextFocusRightId = nextFocusRightId;
8078    }
8079
8080    /**
8081     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
8082     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8083     *
8084     * @attr ref android.R.styleable#View_nextFocusUp
8085     */
8086    public int getNextFocusUpId() {
8087        return mNextFocusUpId;
8088    }
8089
8090    /**
8091     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
8092     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
8093     * decide automatically.
8094     *
8095     * @attr ref android.R.styleable#View_nextFocusUp
8096     */
8097    public void setNextFocusUpId(int nextFocusUpId) {
8098        mNextFocusUpId = nextFocusUpId;
8099    }
8100
8101    /**
8102     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
8103     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8104     *
8105     * @attr ref android.R.styleable#View_nextFocusDown
8106     */
8107    public int getNextFocusDownId() {
8108        return mNextFocusDownId;
8109    }
8110
8111    /**
8112     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
8113     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
8114     * decide automatically.
8115     *
8116     * @attr ref android.R.styleable#View_nextFocusDown
8117     */
8118    public void setNextFocusDownId(int nextFocusDownId) {
8119        mNextFocusDownId = nextFocusDownId;
8120    }
8121
8122    /**
8123     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8124     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8125     *
8126     * @attr ref android.R.styleable#View_nextFocusForward
8127     */
8128    public int getNextFocusForwardId() {
8129        return mNextFocusForwardId;
8130    }
8131
8132    /**
8133     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8134     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
8135     * decide automatically.
8136     *
8137     * @attr ref android.R.styleable#View_nextFocusForward
8138     */
8139    public void setNextFocusForwardId(int nextFocusForwardId) {
8140        mNextFocusForwardId = nextFocusForwardId;
8141    }
8142
8143    /**
8144     * Gets the id of the root of the next keyboard navigation cluster.
8145     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
8146     * decide automatically.
8147     *
8148     * @attr ref android.R.styleable#View_nextClusterForward
8149     */
8150    public int getNextClusterForwardId() {
8151        return mNextClusterForwardId;
8152    }
8153
8154    /**
8155     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
8156     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
8157     * decide automatically.
8158     *
8159     * @attr ref android.R.styleable#View_nextClusterForward
8160     */
8161    public void setNextClusterForwardId(int nextClusterForwardId) {
8162        mNextClusterForwardId = nextClusterForwardId;
8163    }
8164
8165    /**
8166     * Returns the visibility of this view and all of its ancestors
8167     *
8168     * @return True if this view and all of its ancestors are {@link #VISIBLE}
8169     */
8170    public boolean isShown() {
8171        View current = this;
8172        //noinspection ConstantConditions
8173        do {
8174            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8175                return false;
8176            }
8177            ViewParent parent = current.mParent;
8178            if (parent == null) {
8179                return false; // We are not attached to the view root
8180            }
8181            if (!(parent instanceof View)) {
8182                return true;
8183            }
8184            current = (View) parent;
8185        } while (current != null);
8186
8187        return false;
8188    }
8189
8190    /**
8191     * Called by the view hierarchy when the content insets for a window have
8192     * changed, to allow it to adjust its content to fit within those windows.
8193     * The content insets tell you the space that the status bar, input method,
8194     * and other system windows infringe on the application's window.
8195     *
8196     * <p>You do not normally need to deal with this function, since the default
8197     * window decoration given to applications takes care of applying it to the
8198     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
8199     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
8200     * and your content can be placed under those system elements.  You can then
8201     * use this method within your view hierarchy if you have parts of your UI
8202     * which you would like to ensure are not being covered.
8203     *
8204     * <p>The default implementation of this method simply applies the content
8205     * insets to the view's padding, consuming that content (modifying the
8206     * insets to be 0), and returning true.  This behavior is off by default, but can
8207     * be enabled through {@link #setFitsSystemWindows(boolean)}.
8208     *
8209     * <p>This function's traversal down the hierarchy is depth-first.  The same content
8210     * insets object is propagated down the hierarchy, so any changes made to it will
8211     * be seen by all following views (including potentially ones above in
8212     * the hierarchy since this is a depth-first traversal).  The first view
8213     * that returns true will abort the entire traversal.
8214     *
8215     * <p>The default implementation works well for a situation where it is
8216     * used with a container that covers the entire window, allowing it to
8217     * apply the appropriate insets to its content on all edges.  If you need
8218     * a more complicated layout (such as two different views fitting system
8219     * windows, one on the top of the window, and one on the bottom),
8220     * you can override the method and handle the insets however you would like.
8221     * Note that the insets provided by the framework are always relative to the
8222     * far edges of the window, not accounting for the location of the called view
8223     * within that window.  (In fact when this method is called you do not yet know
8224     * where the layout will place the view, as it is done before layout happens.)
8225     *
8226     * <p>Note: unlike many View methods, there is no dispatch phase to this
8227     * call.  If you are overriding it in a ViewGroup and want to allow the
8228     * call to continue to your children, you must be sure to call the super
8229     * implementation.
8230     *
8231     * <p>Here is a sample layout that makes use of fitting system windows
8232     * to have controls for a video view placed inside of the window decorations
8233     * that it hides and shows.  This can be used with code like the second
8234     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
8235     *
8236     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
8237     *
8238     * @param insets Current content insets of the window.  Prior to
8239     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
8240     * the insets or else you and Android will be unhappy.
8241     *
8242     * @return {@code true} if this view applied the insets and it should not
8243     * continue propagating further down the hierarchy, {@code false} otherwise.
8244     * @see #getFitsSystemWindows()
8245     * @see #setFitsSystemWindows(boolean)
8246     * @see #setSystemUiVisibility(int)
8247     *
8248     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
8249     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
8250     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
8251     * to implement handling their own insets.
8252     */
8253    @Deprecated
8254    protected boolean fitSystemWindows(Rect insets) {
8255        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
8256            if (insets == null) {
8257                // Null insets by definition have already been consumed.
8258                // This call cannot apply insets since there are none to apply,
8259                // so return false.
8260                return false;
8261            }
8262            // If we're not in the process of dispatching the newer apply insets call,
8263            // that means we're not in the compatibility path. Dispatch into the newer
8264            // apply insets path and take things from there.
8265            try {
8266                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
8267                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
8268            } finally {
8269                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
8270            }
8271        } else {
8272            // We're being called from the newer apply insets path.
8273            // Perform the standard fallback behavior.
8274            return fitSystemWindowsInt(insets);
8275        }
8276    }
8277
8278    private boolean fitSystemWindowsInt(Rect insets) {
8279        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
8280            mUserPaddingStart = UNDEFINED_PADDING;
8281            mUserPaddingEnd = UNDEFINED_PADDING;
8282            Rect localInsets = sThreadLocal.get();
8283            if (localInsets == null) {
8284                localInsets = new Rect();
8285                sThreadLocal.set(localInsets);
8286            }
8287            boolean res = computeFitSystemWindows(insets, localInsets);
8288            mUserPaddingLeftInitial = localInsets.left;
8289            mUserPaddingRightInitial = localInsets.right;
8290            internalSetPadding(localInsets.left, localInsets.top,
8291                    localInsets.right, localInsets.bottom);
8292            return res;
8293        }
8294        return false;
8295    }
8296
8297    /**
8298     * Called when the view should apply {@link WindowInsets} according to its internal policy.
8299     *
8300     * <p>This method should be overridden by views that wish to apply a policy different from or
8301     * in addition to the default behavior. Clients that wish to force a view subtree
8302     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
8303     *
8304     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
8305     * it will be called during dispatch instead of this method. The listener may optionally
8306     * call this method from its own implementation if it wishes to apply the view's default
8307     * insets policy in addition to its own.</p>
8308     *
8309     * <p>Implementations of this method should either return the insets parameter unchanged
8310     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
8311     * that this view applied itself. This allows new inset types added in future platform
8312     * versions to pass through existing implementations unchanged without being erroneously
8313     * consumed.</p>
8314     *
8315     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
8316     * property is set then the view will consume the system window insets and apply them
8317     * as padding for the view.</p>
8318     *
8319     * @param insets Insets to apply
8320     * @return The supplied insets with any applied insets consumed
8321     */
8322    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
8323        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
8324            // We weren't called from within a direct call to fitSystemWindows,
8325            // call into it as a fallback in case we're in a class that overrides it
8326            // and has logic to perform.
8327            if (fitSystemWindows(insets.getSystemWindowInsets())) {
8328                return insets.consumeSystemWindowInsets();
8329            }
8330        } else {
8331            // We were called from within a direct call to fitSystemWindows.
8332            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
8333                return insets.consumeSystemWindowInsets();
8334            }
8335        }
8336        return insets;
8337    }
8338
8339    /**
8340     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
8341     * window insets to this view. The listener's
8342     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
8343     * method will be called instead of the view's
8344     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
8345     *
8346     * @param listener Listener to set
8347     *
8348     * @see #onApplyWindowInsets(WindowInsets)
8349     */
8350    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
8351        getListenerInfo().mOnApplyWindowInsetsListener = listener;
8352    }
8353
8354    /**
8355     * Request to apply the given window insets to this view or another view in its subtree.
8356     *
8357     * <p>This method should be called by clients wishing to apply insets corresponding to areas
8358     * obscured by window decorations or overlays. This can include the status and navigation bars,
8359     * action bars, input methods and more. New inset categories may be added in the future.
8360     * The method returns the insets provided minus any that were applied by this view or its
8361     * children.</p>
8362     *
8363     * <p>Clients wishing to provide custom behavior should override the
8364     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
8365     * {@link OnApplyWindowInsetsListener} via the
8366     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
8367     * method.</p>
8368     *
8369     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
8370     * </p>
8371     *
8372     * @param insets Insets to apply
8373     * @return The provided insets minus the insets that were consumed
8374     */
8375    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
8376        try {
8377            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
8378            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
8379                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
8380            } else {
8381                return onApplyWindowInsets(insets);
8382            }
8383        } finally {
8384            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
8385        }
8386    }
8387
8388    /**
8389     * Compute the view's coordinate within the surface.
8390     *
8391     * <p>Computes the coordinates of this view in its surface. The argument
8392     * must be an array of two integers. After the method returns, the array
8393     * contains the x and y location in that order.</p>
8394     * @hide
8395     * @param location an array of two integers in which to hold the coordinates
8396     */
8397    public void getLocationInSurface(@Size(2) int[] location) {
8398        getLocationInWindow(location);
8399        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
8400            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
8401            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
8402        }
8403    }
8404
8405    /**
8406     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
8407     * only available if the view is attached.
8408     *
8409     * @return WindowInsets from the top of the view hierarchy or null if View is detached
8410     */
8411    public WindowInsets getRootWindowInsets() {
8412        if (mAttachInfo != null) {
8413            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
8414        }
8415        return null;
8416    }
8417
8418    /**
8419     * @hide Compute the insets that should be consumed by this view and the ones
8420     * that should propagate to those under it.
8421     */
8422    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
8423        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8424                || mAttachInfo == null
8425                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
8426                        && !mAttachInfo.mOverscanRequested)) {
8427            outLocalInsets.set(inoutInsets);
8428            inoutInsets.set(0, 0, 0, 0);
8429            return true;
8430        } else {
8431            // The application wants to take care of fitting system window for
8432            // the content...  however we still need to take care of any overscan here.
8433            final Rect overscan = mAttachInfo.mOverscanInsets;
8434            outLocalInsets.set(overscan);
8435            inoutInsets.left -= overscan.left;
8436            inoutInsets.top -= overscan.top;
8437            inoutInsets.right -= overscan.right;
8438            inoutInsets.bottom -= overscan.bottom;
8439            return false;
8440        }
8441    }
8442
8443    /**
8444     * Compute insets that should be consumed by this view and the ones that should propagate
8445     * to those under it.
8446     *
8447     * @param in Insets currently being processed by this View, likely received as a parameter
8448     *           to {@link #onApplyWindowInsets(WindowInsets)}.
8449     * @param outLocalInsets A Rect that will receive the insets that should be consumed
8450     *                       by this view
8451     * @return Insets that should be passed along to views under this one
8452     */
8453    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
8454        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8455                || mAttachInfo == null
8456                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
8457            outLocalInsets.set(in.getSystemWindowInsets());
8458            return in.consumeSystemWindowInsets();
8459        } else {
8460            outLocalInsets.set(0, 0, 0, 0);
8461            return in;
8462        }
8463    }
8464
8465    /**
8466     * Sets whether or not this view should account for system screen decorations
8467     * such as the status bar and inset its content; that is, controlling whether
8468     * the default implementation of {@link #fitSystemWindows(Rect)} will be
8469     * executed.  See that method for more details.
8470     *
8471     * <p>Note that if you are providing your own implementation of
8472     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
8473     * flag to true -- your implementation will be overriding the default
8474     * implementation that checks this flag.
8475     *
8476     * @param fitSystemWindows If true, then the default implementation of
8477     * {@link #fitSystemWindows(Rect)} will be executed.
8478     *
8479     * @attr ref android.R.styleable#View_fitsSystemWindows
8480     * @see #getFitsSystemWindows()
8481     * @see #fitSystemWindows(Rect)
8482     * @see #setSystemUiVisibility(int)
8483     */
8484    public void setFitsSystemWindows(boolean fitSystemWindows) {
8485        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
8486    }
8487
8488    /**
8489     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
8490     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
8491     * will be executed.
8492     *
8493     * @return {@code true} if the default implementation of
8494     * {@link #fitSystemWindows(Rect)} will be executed.
8495     *
8496     * @attr ref android.R.styleable#View_fitsSystemWindows
8497     * @see #setFitsSystemWindows(boolean)
8498     * @see #fitSystemWindows(Rect)
8499     * @see #setSystemUiVisibility(int)
8500     */
8501    @ViewDebug.ExportedProperty
8502    public boolean getFitsSystemWindows() {
8503        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8504    }
8505
8506    /** @hide */
8507    public boolean fitsSystemWindows() {
8508        return getFitsSystemWindows();
8509    }
8510
8511    /**
8512     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8513     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8514     */
8515    @Deprecated
8516    public void requestFitSystemWindows() {
8517        if (mParent != null) {
8518            mParent.requestFitSystemWindows();
8519        }
8520    }
8521
8522    /**
8523     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8524     */
8525    public void requestApplyInsets() {
8526        requestFitSystemWindows();
8527    }
8528
8529    /**
8530     * For use by PhoneWindow to make its own system window fitting optional.
8531     * @hide
8532     */
8533    public void makeOptionalFitsSystemWindows() {
8534        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8535    }
8536
8537    /**
8538     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8539     * treat them as such.
8540     * @hide
8541     */
8542    public void getOutsets(Rect outOutsetRect) {
8543        if (mAttachInfo != null) {
8544            outOutsetRect.set(mAttachInfo.mOutsets);
8545        } else {
8546            outOutsetRect.setEmpty();
8547        }
8548    }
8549
8550    /**
8551     * Returns the visibility status for this view.
8552     *
8553     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8554     * @attr ref android.R.styleable#View_visibility
8555     */
8556    @ViewDebug.ExportedProperty(mapping = {
8557        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
8558        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
8559        @ViewDebug.IntToString(from = GONE,      to = "GONE")
8560    })
8561    @Visibility
8562    public int getVisibility() {
8563        return mViewFlags & VISIBILITY_MASK;
8564    }
8565
8566    /**
8567     * Set the visibility state of this view.
8568     *
8569     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8570     * @attr ref android.R.styleable#View_visibility
8571     */
8572    @RemotableViewMethod
8573    public void setVisibility(@Visibility int visibility) {
8574        setFlags(visibility, VISIBILITY_MASK);
8575    }
8576
8577    /**
8578     * Returns the enabled status for this view. The interpretation of the
8579     * enabled state varies by subclass.
8580     *
8581     * @return True if this view is enabled, false otherwise.
8582     */
8583    @ViewDebug.ExportedProperty
8584    public boolean isEnabled() {
8585        return (mViewFlags & ENABLED_MASK) == ENABLED;
8586    }
8587
8588    /**
8589     * Set the enabled state of this view. The interpretation of the enabled
8590     * state varies by subclass.
8591     *
8592     * @param enabled True if this view is enabled, false otherwise.
8593     */
8594    @RemotableViewMethod
8595    public void setEnabled(boolean enabled) {
8596        if (enabled == isEnabled()) return;
8597
8598        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8599
8600        /*
8601         * The View most likely has to change its appearance, so refresh
8602         * the drawable state.
8603         */
8604        refreshDrawableState();
8605
8606        // Invalidate too, since the default behavior for views is to be
8607        // be drawn at 50% alpha rather than to change the drawable.
8608        invalidate(true);
8609
8610        if (!enabled) {
8611            cancelPendingInputEvents();
8612        }
8613    }
8614
8615    /**
8616     * Set whether this view can receive the focus.
8617     * <p>
8618     * Setting this to false will also ensure that this view is not focusable
8619     * in touch mode.
8620     *
8621     * @param focusable If true, this view can receive the focus.
8622     *
8623     * @see #setFocusableInTouchMode(boolean)
8624     * @see #setFocusable(int)
8625     * @attr ref android.R.styleable#View_focusable
8626     */
8627    public void setFocusable(boolean focusable) {
8628        setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
8629    }
8630
8631    /**
8632     * Sets whether this view can receive focus.
8633     * <p>
8634     * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
8635     * automatically based on the view's interactivity. This is the default.
8636     * <p>
8637     * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
8638     * in touch mode.
8639     *
8640     * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
8641     *                  or {@link #FOCUSABLE_AUTO}.
8642     * @see #setFocusableInTouchMode(boolean)
8643     * @attr ref android.R.styleable#View_focusable
8644     */
8645    public void setFocusable(@Focusable int focusable) {
8646        if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
8647            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8648        }
8649        setFlags(focusable, FOCUSABLE_MASK);
8650    }
8651
8652    /**
8653     * Set whether this view can receive focus while in touch mode.
8654     *
8655     * Setting this to true will also ensure that this view is focusable.
8656     *
8657     * @param focusableInTouchMode If true, this view can receive the focus while
8658     *   in touch mode.
8659     *
8660     * @see #setFocusable(boolean)
8661     * @attr ref android.R.styleable#View_focusableInTouchMode
8662     */
8663    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8664        // Focusable in touch mode should always be set before the focusable flag
8665        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8666        // which, in touch mode, will not successfully request focus on this view
8667        // because the focusable in touch mode flag is not set
8668        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8669        if (focusableInTouchMode) {
8670            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8671        }
8672    }
8673
8674    /**
8675     * Set auto-fill mode for the view.
8676     *
8677     * @param autoFillMode One of {@link #AUTO_FILL_MODE_INHERIT}, {@link #AUTO_FILL_MODE_AUTO},
8678     *                     or {@link #AUTO_FILL_MODE_MANUAL}.
8679     * @attr ref android.R.styleable#View_autoFillMode
8680     */
8681    public void setAutoFillMode(@AutoFillMode int autoFillMode) {
8682        Preconditions.checkArgumentInRange(autoFillMode, AUTO_FILL_MODE_INHERIT,
8683                AUTO_FILL_MODE_MANUAL, "autoFillMode");
8684
8685        mPrivateFlags3 &= ~PFLAG3_AUTO_FILL_MODE_MASK;
8686        mPrivateFlags3 |= autoFillMode << PFLAG3_AUTO_FILL_MODE_SHIFT;
8687    }
8688
8689    /**
8690     * Set whether this view should have sound effects enabled for events such as
8691     * clicking and touching.
8692     *
8693     * <p>You may wish to disable sound effects for a view if you already play sounds,
8694     * for instance, a dial key that plays dtmf tones.
8695     *
8696     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8697     * @see #isSoundEffectsEnabled()
8698     * @see #playSoundEffect(int)
8699     * @attr ref android.R.styleable#View_soundEffectsEnabled
8700     */
8701    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8702        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8703    }
8704
8705    /**
8706     * @return whether this view should have sound effects enabled for events such as
8707     *     clicking and touching.
8708     *
8709     * @see #setSoundEffectsEnabled(boolean)
8710     * @see #playSoundEffect(int)
8711     * @attr ref android.R.styleable#View_soundEffectsEnabled
8712     */
8713    @ViewDebug.ExportedProperty
8714    public boolean isSoundEffectsEnabled() {
8715        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8716    }
8717
8718    /**
8719     * Set whether this view should have haptic feedback for events such as
8720     * long presses.
8721     *
8722     * <p>You may wish to disable haptic feedback if your view already controls
8723     * its own haptic feedback.
8724     *
8725     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8726     * @see #isHapticFeedbackEnabled()
8727     * @see #performHapticFeedback(int)
8728     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8729     */
8730    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8731        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8732    }
8733
8734    /**
8735     * @return whether this view should have haptic feedback enabled for events
8736     * long presses.
8737     *
8738     * @see #setHapticFeedbackEnabled(boolean)
8739     * @see #performHapticFeedback(int)
8740     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8741     */
8742    @ViewDebug.ExportedProperty
8743    public boolean isHapticFeedbackEnabled() {
8744        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8745    }
8746
8747    /**
8748     * Returns the layout direction for this view.
8749     *
8750     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8751     *   {@link #LAYOUT_DIRECTION_RTL},
8752     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8753     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8754     *
8755     * @attr ref android.R.styleable#View_layoutDirection
8756     *
8757     * @hide
8758     */
8759    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8760        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8761        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8762        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8763        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8764    })
8765    @LayoutDir
8766    public int getRawLayoutDirection() {
8767        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8768    }
8769
8770    /**
8771     * Set the layout direction for this view. This will propagate a reset of layout direction
8772     * resolution to the view's children and resolve layout direction for this view.
8773     *
8774     * @param layoutDirection the layout direction to set. Should be one of:
8775     *
8776     * {@link #LAYOUT_DIRECTION_LTR},
8777     * {@link #LAYOUT_DIRECTION_RTL},
8778     * {@link #LAYOUT_DIRECTION_INHERIT},
8779     * {@link #LAYOUT_DIRECTION_LOCALE}.
8780     *
8781     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8782     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8783     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8784     *
8785     * @attr ref android.R.styleable#View_layoutDirection
8786     */
8787    @RemotableViewMethod
8788    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8789        if (getRawLayoutDirection() != layoutDirection) {
8790            // Reset the current layout direction and the resolved one
8791            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8792            resetRtlProperties();
8793            // Set the new layout direction (filtered)
8794            mPrivateFlags2 |=
8795                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8796            // We need to resolve all RTL properties as they all depend on layout direction
8797            resolveRtlPropertiesIfNeeded();
8798            requestLayout();
8799            invalidate(true);
8800        }
8801    }
8802
8803    /**
8804     * Returns the resolved layout direction for this view.
8805     *
8806     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8807     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8808     *
8809     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8810     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8811     *
8812     * @attr ref android.R.styleable#View_layoutDirection
8813     */
8814    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8815        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8816        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8817    })
8818    @ResolvedLayoutDir
8819    public int getLayoutDirection() {
8820        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8821        if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
8822            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8823            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8824        }
8825        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8826                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8827    }
8828
8829    /**
8830     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8831     * layout attribute and/or the inherited value from the parent
8832     *
8833     * @return true if the layout is right-to-left.
8834     *
8835     * @hide
8836     */
8837    @ViewDebug.ExportedProperty(category = "layout")
8838    public boolean isLayoutRtl() {
8839        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8840    }
8841
8842    /**
8843     * Indicates whether the view is currently tracking transient state that the
8844     * app should not need to concern itself with saving and restoring, but that
8845     * the framework should take special note to preserve when possible.
8846     *
8847     * <p>A view with transient state cannot be trivially rebound from an external
8848     * data source, such as an adapter binding item views in a list. This may be
8849     * because the view is performing an animation, tracking user selection
8850     * of content, or similar.</p>
8851     *
8852     * @return true if the view has transient state
8853     */
8854    @ViewDebug.ExportedProperty(category = "layout")
8855    public boolean hasTransientState() {
8856        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8857    }
8858
8859    /**
8860     * Set whether this view is currently tracking transient state that the
8861     * framework should attempt to preserve when possible. This flag is reference counted,
8862     * so every call to setHasTransientState(true) should be paired with a later call
8863     * to setHasTransientState(false).
8864     *
8865     * <p>A view with transient state cannot be trivially rebound from an external
8866     * data source, such as an adapter binding item views in a list. This may be
8867     * because the view is performing an animation, tracking user selection
8868     * of content, or similar.</p>
8869     *
8870     * @param hasTransientState true if this view has transient state
8871     */
8872    public void setHasTransientState(boolean hasTransientState) {
8873        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8874                mTransientStateCount - 1;
8875        if (mTransientStateCount < 0) {
8876            mTransientStateCount = 0;
8877            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8878                    "unmatched pair of setHasTransientState calls");
8879        } else if ((hasTransientState && mTransientStateCount == 1) ||
8880                (!hasTransientState && mTransientStateCount == 0)) {
8881            // update flag if we've just incremented up from 0 or decremented down to 0
8882            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8883                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8884            if (mParent != null) {
8885                try {
8886                    mParent.childHasTransientStateChanged(this, hasTransientState);
8887                } catch (AbstractMethodError e) {
8888                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8889                            " does not fully implement ViewParent", e);
8890                }
8891            }
8892        }
8893    }
8894
8895    /**
8896     * Returns true if this view is currently attached to a window.
8897     */
8898    public boolean isAttachedToWindow() {
8899        return mAttachInfo != null;
8900    }
8901
8902    /**
8903     * Returns true if this view has been through at least one layout since it
8904     * was last attached to or detached from a window.
8905     */
8906    public boolean isLaidOut() {
8907        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8908    }
8909
8910    /**
8911     * If this view doesn't do any drawing on its own, set this flag to
8912     * allow further optimizations. By default, this flag is not set on
8913     * View, but could be set on some View subclasses such as ViewGroup.
8914     *
8915     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8916     * you should clear this flag.
8917     *
8918     * @param willNotDraw whether or not this View draw on its own
8919     */
8920    public void setWillNotDraw(boolean willNotDraw) {
8921        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8922    }
8923
8924    /**
8925     * Returns whether or not this View draws on its own.
8926     *
8927     * @return true if this view has nothing to draw, false otherwise
8928     */
8929    @ViewDebug.ExportedProperty(category = "drawing")
8930    public boolean willNotDraw() {
8931        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8932    }
8933
8934    /**
8935     * When a View's drawing cache is enabled, drawing is redirected to an
8936     * offscreen bitmap. Some views, like an ImageView, must be able to
8937     * bypass this mechanism if they already draw a single bitmap, to avoid
8938     * unnecessary usage of the memory.
8939     *
8940     * @param willNotCacheDrawing true if this view does not cache its
8941     *        drawing, false otherwise
8942     */
8943    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8944        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8945    }
8946
8947    /**
8948     * Returns whether or not this View can cache its drawing or not.
8949     *
8950     * @return true if this view does not cache its drawing, false otherwise
8951     */
8952    @ViewDebug.ExportedProperty(category = "drawing")
8953    public boolean willNotCacheDrawing() {
8954        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8955    }
8956
8957    /**
8958     * Indicates whether this view reacts to click events or not.
8959     *
8960     * @return true if the view is clickable, false otherwise
8961     *
8962     * @see #setClickable(boolean)
8963     * @attr ref android.R.styleable#View_clickable
8964     */
8965    @ViewDebug.ExportedProperty
8966    public boolean isClickable() {
8967        return (mViewFlags & CLICKABLE) == CLICKABLE;
8968    }
8969
8970    /**
8971     * Enables or disables click events for this view. When a view
8972     * is clickable it will change its state to "pressed" on every click.
8973     * Subclasses should set the view clickable to visually react to
8974     * user's clicks.
8975     *
8976     * @param clickable true to make the view clickable, false otherwise
8977     *
8978     * @see #isClickable()
8979     * @attr ref android.R.styleable#View_clickable
8980     */
8981    public void setClickable(boolean clickable) {
8982        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8983    }
8984
8985    /**
8986     * Indicates whether this view reacts to long click events or not.
8987     *
8988     * @return true if the view is long clickable, false otherwise
8989     *
8990     * @see #setLongClickable(boolean)
8991     * @attr ref android.R.styleable#View_longClickable
8992     */
8993    public boolean isLongClickable() {
8994        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8995    }
8996
8997    /**
8998     * Enables or disables long click events for this view. When a view is long
8999     * clickable it reacts to the user holding down the button for a longer
9000     * duration than a tap. This event can either launch the listener or a
9001     * context menu.
9002     *
9003     * @param longClickable true to make the view long clickable, false otherwise
9004     * @see #isLongClickable()
9005     * @attr ref android.R.styleable#View_longClickable
9006     */
9007    public void setLongClickable(boolean longClickable) {
9008        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
9009    }
9010
9011    /**
9012     * Indicates whether this view reacts to context clicks or not.
9013     *
9014     * @return true if the view is context clickable, false otherwise
9015     * @see #setContextClickable(boolean)
9016     * @attr ref android.R.styleable#View_contextClickable
9017     */
9018    public boolean isContextClickable() {
9019        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
9020    }
9021
9022    /**
9023     * Enables or disables context clicking for this view. This event can launch the listener.
9024     *
9025     * @param contextClickable true to make the view react to a context click, false otherwise
9026     * @see #isContextClickable()
9027     * @attr ref android.R.styleable#View_contextClickable
9028     */
9029    public void setContextClickable(boolean contextClickable) {
9030        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
9031    }
9032
9033    /**
9034     * Sets the pressed state for this view and provides a touch coordinate for
9035     * animation hinting.
9036     *
9037     * @param pressed Pass true to set the View's internal state to "pressed",
9038     *            or false to reverts the View's internal state from a
9039     *            previously set "pressed" state.
9040     * @param x The x coordinate of the touch that caused the press
9041     * @param y The y coordinate of the touch that caused the press
9042     */
9043    private void setPressed(boolean pressed, float x, float y) {
9044        if (pressed) {
9045            drawableHotspotChanged(x, y);
9046        }
9047
9048        setPressed(pressed);
9049    }
9050
9051    /**
9052     * Sets the pressed state for this view.
9053     *
9054     * @see #isClickable()
9055     * @see #setClickable(boolean)
9056     *
9057     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
9058     *        the View's internal state from a previously set "pressed" state.
9059     */
9060    public void setPressed(boolean pressed) {
9061        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
9062
9063        if (pressed) {
9064            mPrivateFlags |= PFLAG_PRESSED;
9065        } else {
9066            mPrivateFlags &= ~PFLAG_PRESSED;
9067        }
9068
9069        if (needsRefresh) {
9070            refreshDrawableState();
9071        }
9072        dispatchSetPressed(pressed);
9073    }
9074
9075    /**
9076     * Dispatch setPressed to all of this View's children.
9077     *
9078     * @see #setPressed(boolean)
9079     *
9080     * @param pressed The new pressed state
9081     */
9082    protected void dispatchSetPressed(boolean pressed) {
9083    }
9084
9085    /**
9086     * Indicates whether the view is currently in pressed state. Unless
9087     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
9088     * the pressed state.
9089     *
9090     * @see #setPressed(boolean)
9091     * @see #isClickable()
9092     * @see #setClickable(boolean)
9093     *
9094     * @return true if the view is currently pressed, false otherwise
9095     */
9096    @ViewDebug.ExportedProperty
9097    public boolean isPressed() {
9098        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
9099    }
9100
9101    /**
9102     * @hide
9103     * Indicates whether this view will participate in data collection through
9104     * {@link ViewStructure}.  If true, it will not provide any data
9105     * for itself or its children.  If false, the normal data collection will be allowed.
9106     *
9107     * @return Returns false if assist data collection is not blocked, else true.
9108     *
9109     * @see #setAssistBlocked(boolean)
9110     * @attr ref android.R.styleable#View_assistBlocked
9111     */
9112    public boolean isAssistBlocked() {
9113        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
9114    }
9115
9116    /**
9117     * @hide
9118     * Indicates whether this view will participate in data collection through
9119     * {@link ViewStructure} for auto-fill purposes.
9120     *
9121     * <p>If {@code true}, it will not provide any data for itself or its children.
9122     * <p>If {@code false}, the normal data collection will be allowed.
9123     *
9124     * @return Returns {@code false} if assist data collection for auto-fill is not blocked,
9125     * else {@code true}.
9126     *
9127     * TODO(b/33197203): update / remove javadoc tags below
9128     * @see #setAssistBlocked(boolean)
9129     * @attr ref android.R.styleable#View_assistBlocked
9130     */
9131    public boolean isAutoFillBlocked() {
9132        return false; // TODO(b/33197203): properly implement it
9133    }
9134
9135    /**
9136     * @hide
9137     * Controls whether assist data collection from this view and its children is enabled
9138     * (that is, whether {@link #onProvideStructure} and
9139     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
9140     * allowing normal assist collection.  Setting this to false will disable assist collection.
9141     *
9142     * @param enabled Set to true to <em>disable</em> assist data collection, or false
9143     * (the default) to allow it.
9144     *
9145     * @see #isAssistBlocked()
9146     * @see #onProvideStructure
9147     * @see #onProvideVirtualStructure
9148     * @attr ref android.R.styleable#View_assistBlocked
9149     */
9150    public void setAssistBlocked(boolean enabled) {
9151        if (enabled) {
9152            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
9153        } else {
9154            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
9155        }
9156    }
9157
9158    /**
9159     * Indicates whether this view will save its state (that is,
9160     * whether its {@link #onSaveInstanceState} method will be called).
9161     *
9162     * @return Returns true if the view state saving is enabled, else false.
9163     *
9164     * @see #setSaveEnabled(boolean)
9165     * @attr ref android.R.styleable#View_saveEnabled
9166     */
9167    public boolean isSaveEnabled() {
9168        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
9169    }
9170
9171    /**
9172     * Controls whether the saving of this view's state is
9173     * enabled (that is, whether its {@link #onSaveInstanceState} method
9174     * will be called).  Note that even if freezing is enabled, the
9175     * view still must have an id assigned to it (via {@link #setId(int)})
9176     * for its state to be saved.  This flag can only disable the
9177     * saving of this view; any child views may still have their state saved.
9178     *
9179     * @param enabled Set to false to <em>disable</em> state saving, or true
9180     * (the default) to allow it.
9181     *
9182     * @see #isSaveEnabled()
9183     * @see #setId(int)
9184     * @see #onSaveInstanceState()
9185     * @attr ref android.R.styleable#View_saveEnabled
9186     */
9187    public void setSaveEnabled(boolean enabled) {
9188        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
9189    }
9190
9191    /**
9192     * Gets whether the framework should discard touches when the view's
9193     * window is obscured by another visible window.
9194     * Refer to the {@link View} security documentation for more details.
9195     *
9196     * @return True if touch filtering is enabled.
9197     *
9198     * @see #setFilterTouchesWhenObscured(boolean)
9199     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9200     */
9201    @ViewDebug.ExportedProperty
9202    public boolean getFilterTouchesWhenObscured() {
9203        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
9204    }
9205
9206    /**
9207     * Sets whether the framework should discard touches when the view's
9208     * window is obscured by another visible window.
9209     * Refer to the {@link View} security documentation for more details.
9210     *
9211     * @param enabled True if touch filtering should be enabled.
9212     *
9213     * @see #getFilterTouchesWhenObscured
9214     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9215     */
9216    public void setFilterTouchesWhenObscured(boolean enabled) {
9217        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
9218                FILTER_TOUCHES_WHEN_OBSCURED);
9219    }
9220
9221    /**
9222     * Indicates whether the entire hierarchy under this view will save its
9223     * state when a state saving traversal occurs from its parent.  The default
9224     * is true; if false, these views will not be saved unless
9225     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9226     *
9227     * @return Returns true if the view state saving from parent is enabled, else false.
9228     *
9229     * @see #setSaveFromParentEnabled(boolean)
9230     */
9231    public boolean isSaveFromParentEnabled() {
9232        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
9233    }
9234
9235    /**
9236     * Controls whether the entire hierarchy under this view will save its
9237     * state when a state saving traversal occurs from its parent.  The default
9238     * is true; if false, these views will not be saved unless
9239     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9240     *
9241     * @param enabled Set to false to <em>disable</em> state saving, or true
9242     * (the default) to allow it.
9243     *
9244     * @see #isSaveFromParentEnabled()
9245     * @see #setId(int)
9246     * @see #onSaveInstanceState()
9247     */
9248    public void setSaveFromParentEnabled(boolean enabled) {
9249        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
9250    }
9251
9252
9253    /**
9254     * Returns whether this View is currently able to take focus.
9255     *
9256     * @return True if this view can take focus, or false otherwise.
9257     */
9258    @ViewDebug.ExportedProperty(category = "focus")
9259    public final boolean isFocusable() {
9260        return FOCUSABLE == (mViewFlags & FOCUSABLE);
9261    }
9262
9263    /**
9264     * Returns the focusable setting for this view.
9265     *
9266     * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
9267     * @attr ref android.R.styleable#View_focusable
9268     */
9269    @ViewDebug.ExportedProperty(mapping = {
9270            @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
9271            @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
9272            @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
9273            })
9274    @Focusable
9275    public int getFocusable() {
9276        return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
9277    }
9278
9279    /**
9280     * When a view is focusable, it may not want to take focus when in touch mode.
9281     * For example, a button would like focus when the user is navigating via a D-pad
9282     * so that the user can click on it, but once the user starts touching the screen,
9283     * the button shouldn't take focus
9284     * @return Whether the view is focusable in touch mode.
9285     * @attr ref android.R.styleable#View_focusableInTouchMode
9286     */
9287    @ViewDebug.ExportedProperty
9288    public final boolean isFocusableInTouchMode() {
9289        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
9290    }
9291
9292    /**
9293     * Returns the auto-fill mode for this view.
9294     *
9295     * @return One of {@link #AUTO_FILL_MODE_INHERIT}, {@link #AUTO_FILL_MODE_AUTO}, or
9296     * {@link #AUTO_FILL_MODE_MANUAL}.
9297     * @attr ref android.R.styleable#View_autoFillMode
9298     */
9299    @ViewDebug.ExportedProperty(mapping = {
9300            @ViewDebug.IntToString(from = AUTO_FILL_MODE_INHERIT, to = "AUTO_FILL_MODE_INHERIT"),
9301            @ViewDebug.IntToString(from = AUTO_FILL_MODE_AUTO, to = "AUTO_FILL_MODE_AUTO"),
9302            @ViewDebug.IntToString(from = AUTO_FILL_MODE_MANUAL, to = "AUTO_FILL_MODE_MANUAL")
9303            })
9304    @AutoFillMode
9305    public int getAutoFillMode() {
9306        return (mPrivateFlags3 & PFLAG3_AUTO_FILL_MODE_MASK) >> PFLAG3_AUTO_FILL_MODE_SHIFT;
9307    }
9308
9309    /**
9310     * Find the nearest view in the specified direction that can take focus.
9311     * This does not actually give focus to that view.
9312     *
9313     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9314     *
9315     * @return The nearest focusable in the specified direction, or null if none
9316     *         can be found.
9317     */
9318    public View focusSearch(@FocusRealDirection int direction) {
9319        if (mParent != null) {
9320            return mParent.focusSearch(this, direction);
9321        } else {
9322            return null;
9323        }
9324    }
9325
9326    /**
9327     * Returns whether this View is a root of a keyboard navigation cluster.
9328     *
9329     * @return True if this view is a root of a cluster, or false otherwise.
9330     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9331     */
9332    @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster")
9333    public final boolean isKeyboardNavigationCluster() {
9334        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
9335    }
9336
9337    /**
9338     * Set whether this view is a root of a keyboard navigation cluster.
9339     *
9340     * @param isCluster If true, this view is a root of a cluster.
9341     *
9342     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9343     */
9344    public void setKeyboardNavigationCluster(boolean isCluster) {
9345        if (isCluster) {
9346            mPrivateFlags3 |= PFLAG3_CLUSTER;
9347        } else {
9348            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
9349        }
9350    }
9351
9352    /**
9353     * Sets this View as the one which receives focus the next time cluster navigation jumps
9354     * to the cluster containing this View. This does NOT change focus even if the cluster
9355     * containing this view is current.
9356     *
9357     * @hide
9358     */
9359    public void setFocusedInCluster() {
9360        if (mParent instanceof ViewGroup) {
9361            ((ViewGroup) mParent).setFocusInCluster(this);
9362        }
9363    }
9364
9365    /**
9366     * Returns whether this View should receive focus when the focus is restored for the view
9367     * hierarchy containing this view.
9368     * <p>
9369     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9370     * window or serves as a target of cluster navigation.
9371     *
9372     * @see #restoreDefaultFocus(int)
9373     *
9374     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
9375     * @attr ref android.R.styleable#View_focusedByDefault
9376     */
9377    @ViewDebug.ExportedProperty(category = "focusedByDefault")
9378    public final boolean isFocusedByDefault() {
9379        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
9380    }
9381
9382    /**
9383     * Sets whether this View should receive focus when the focus is restored for the view
9384     * hierarchy containing this view.
9385     * <p>
9386     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9387     * window or serves as a target of cluster navigation.
9388     *
9389     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
9390     *                           {@code false} otherwise.
9391     *
9392     * @see #restoreDefaultFocus(int)
9393     *
9394     * @attr ref android.R.styleable#View_focusedByDefault
9395     */
9396    public void setFocusedByDefault(boolean isFocusedByDefault) {
9397        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
9398            return;
9399        }
9400
9401        if (isFocusedByDefault) {
9402            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
9403        } else {
9404            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
9405        }
9406
9407        if (mParent instanceof ViewGroup) {
9408            if (isFocusedByDefault) {
9409                ((ViewGroup) mParent).setDefaultFocus(this);
9410            } else {
9411                ((ViewGroup) mParent).clearDefaultFocus(this);
9412            }
9413        }
9414    }
9415
9416    /**
9417     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
9418     *
9419     * @return {@code true} if this view has default focus, {@code false} otherwise
9420     */
9421    boolean hasDefaultFocus() {
9422        return isFocusedByDefault();
9423    }
9424
9425    /**
9426     * Find the nearest keyboard navigation cluster in the specified direction.
9427     * This does not actually give focus to that cluster.
9428     *
9429     * @param currentCluster The starting point of the search. Null means the current cluster is not
9430     *                       found yet
9431     * @param direction Direction to look
9432     *
9433     * @return The nearest keyboard navigation cluster in the specified direction, or null if none
9434     *         can be found
9435     */
9436    public View keyboardNavigationClusterSearch(View currentCluster, int direction) {
9437        if (isKeyboardNavigationCluster()) {
9438            currentCluster = this;
9439        }
9440        if (isRootNamespace()) {
9441            // Root namespace means we should consider ourselves the top of the
9442            // tree for group searching; otherwise we could be group searching
9443            // into other tabs.  see LocalActivityManager and TabHost for more info.
9444            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
9445                    this, currentCluster, direction);
9446        } else if (mParent != null) {
9447            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
9448        }
9449        return null;
9450    }
9451
9452    /**
9453     * This method is the last chance for the focused view and its ancestors to
9454     * respond to an arrow key. This is called when the focused view did not
9455     * consume the key internally, nor could the view system find a new view in
9456     * the requested direction to give focus to.
9457     *
9458     * @param focused The currently focused view.
9459     * @param direction The direction focus wants to move. One of FOCUS_UP,
9460     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
9461     * @return True if the this view consumed this unhandled move.
9462     */
9463    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
9464        return false;
9465    }
9466
9467    /**
9468     * If a user manually specified the next view id for a particular direction,
9469     * use the root to look up the view.
9470     * @param root The root view of the hierarchy containing this view.
9471     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
9472     * or FOCUS_BACKWARD.
9473     * @return The user specified next view, or null if there is none.
9474     */
9475    View findUserSetNextFocus(View root, @FocusDirection int direction) {
9476        switch (direction) {
9477            case FOCUS_LEFT:
9478                if (mNextFocusLeftId == View.NO_ID) return null;
9479                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
9480            case FOCUS_RIGHT:
9481                if (mNextFocusRightId == View.NO_ID) return null;
9482                return findViewInsideOutShouldExist(root, mNextFocusRightId);
9483            case FOCUS_UP:
9484                if (mNextFocusUpId == View.NO_ID) return null;
9485                return findViewInsideOutShouldExist(root, mNextFocusUpId);
9486            case FOCUS_DOWN:
9487                if (mNextFocusDownId == View.NO_ID) return null;
9488                return findViewInsideOutShouldExist(root, mNextFocusDownId);
9489            case FOCUS_FORWARD:
9490                if (mNextFocusForwardId == View.NO_ID) return null;
9491                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
9492            case FOCUS_BACKWARD: {
9493                if (mID == View.NO_ID) return null;
9494                final int id = mID;
9495                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
9496                    @Override
9497                    public boolean test(View t) {
9498                        return t.mNextFocusForwardId == id;
9499                    }
9500                });
9501            }
9502        }
9503        return null;
9504    }
9505
9506    private View findViewInsideOutShouldExist(View root, int id) {
9507        if (mMatchIdPredicate == null) {
9508            mMatchIdPredicate = new MatchIdPredicate();
9509        }
9510        mMatchIdPredicate.mId = id;
9511        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
9512        if (result == null) {
9513            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
9514        }
9515        return result;
9516    }
9517
9518    /**
9519     * Find and return all focusable views that are descendants of this view,
9520     * possibly including this view if it is focusable itself.
9521     *
9522     * @param direction The direction of the focus
9523     * @return A list of focusable views
9524     */
9525    public ArrayList<View> getFocusables(@FocusDirection int direction) {
9526        ArrayList<View> result = new ArrayList<View>(24);
9527        addFocusables(result, direction);
9528        return result;
9529    }
9530
9531    /**
9532     * Add any focusable views that are descendants of this view (possibly
9533     * including this view if it is focusable itself) to views.  If we are in touch mode,
9534     * only add views that are also focusable in touch mode.
9535     *
9536     * @param views Focusable views found so far
9537     * @param direction The direction of the focus
9538     */
9539    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
9540        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
9541    }
9542
9543    /**
9544     * Adds any focusable views that are descendants of this view (possibly
9545     * including this view if it is focusable itself) to views. This method
9546     * adds all focusable views regardless if we are in touch mode or
9547     * only views focusable in touch mode if we are in touch mode or
9548     * only views that can take accessibility focus if accessibility is enabled
9549     * depending on the focusable mode parameter.
9550     *
9551     * @param views Focusable views found so far or null if all we are interested is
9552     *        the number of focusables.
9553     * @param direction The direction of the focus.
9554     * @param focusableMode The type of focusables to be added.
9555     *
9556     * @see #FOCUSABLES_ALL
9557     * @see #FOCUSABLES_TOUCH_MODE
9558     */
9559    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
9560            @FocusableMode int focusableMode) {
9561        if (views == null) {
9562            return;
9563        }
9564        if (!isFocusable()) {
9565            return;
9566        }
9567        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
9568                && !isFocusableInTouchMode()) {
9569            return;
9570        }
9571        views.add(this);
9572    }
9573
9574    /**
9575     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
9576     * including this view if it is a cluster root itself) to views.
9577     *
9578     * @param views Keyboard navigation cluster roots found so far
9579     * @param direction Direction to look
9580     */
9581    public void addKeyboardNavigationClusters(
9582            @NonNull Collection<View> views,
9583            int direction) {
9584        if (!isKeyboardNavigationCluster()) {
9585            return;
9586        }
9587        if (!hasFocusable()) {
9588            return;
9589        }
9590        views.add(this);
9591    }
9592
9593    /**
9594     * Finds the Views that contain given text. The containment is case insensitive.
9595     * The search is performed by either the text that the View renders or the content
9596     * description that describes the view for accessibility purposes and the view does
9597     * not render or both. Clients can specify how the search is to be performed via
9598     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
9599     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
9600     *
9601     * @param outViews The output list of matching Views.
9602     * @param searched The text to match against.
9603     *
9604     * @see #FIND_VIEWS_WITH_TEXT
9605     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
9606     * @see #setContentDescription(CharSequence)
9607     */
9608    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
9609            @FindViewFlags int flags) {
9610        if (getAccessibilityNodeProvider() != null) {
9611            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
9612                outViews.add(this);
9613            }
9614        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
9615                && (searched != null && searched.length() > 0)
9616                && (mContentDescription != null && mContentDescription.length() > 0)) {
9617            String searchedLowerCase = searched.toString().toLowerCase();
9618            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
9619            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
9620                outViews.add(this);
9621            }
9622        }
9623    }
9624
9625    /**
9626     * Find and return all touchable views that are descendants of this view,
9627     * possibly including this view if it is touchable itself.
9628     *
9629     * @return A list of touchable views
9630     */
9631    public ArrayList<View> getTouchables() {
9632        ArrayList<View> result = new ArrayList<View>();
9633        addTouchables(result);
9634        return result;
9635    }
9636
9637    /**
9638     * Add any touchable views that are descendants of this view (possibly
9639     * including this view if it is touchable itself) to views.
9640     *
9641     * @param views Touchable views found so far
9642     */
9643    public void addTouchables(ArrayList<View> views) {
9644        final int viewFlags = mViewFlags;
9645
9646        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
9647                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
9648                && (viewFlags & ENABLED_MASK) == ENABLED) {
9649            views.add(this);
9650        }
9651    }
9652
9653    /**
9654     * Returns whether this View is accessibility focused.
9655     *
9656     * @return True if this View is accessibility focused.
9657     */
9658    public boolean isAccessibilityFocused() {
9659        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
9660    }
9661
9662    /**
9663     * Call this to try to give accessibility focus to this view.
9664     *
9665     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
9666     * returns false or the view is no visible or the view already has accessibility
9667     * focus.
9668     *
9669     * See also {@link #focusSearch(int)}, which is what you call to say that you
9670     * have focus, and you want your parent to look for the next one.
9671     *
9672     * @return Whether this view actually took accessibility focus.
9673     *
9674     * @hide
9675     */
9676    public boolean requestAccessibilityFocus() {
9677        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
9678        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
9679            return false;
9680        }
9681        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9682            return false;
9683        }
9684        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
9685            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
9686            ViewRootImpl viewRootImpl = getViewRootImpl();
9687            if (viewRootImpl != null) {
9688                viewRootImpl.setAccessibilityFocus(this, null);
9689            }
9690            invalidate();
9691            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
9692            return true;
9693        }
9694        return false;
9695    }
9696
9697    /**
9698     * Call this to try to clear accessibility focus of this view.
9699     *
9700     * See also {@link #focusSearch(int)}, which is what you call to say that you
9701     * have focus, and you want your parent to look for the next one.
9702     *
9703     * @hide
9704     */
9705    public void clearAccessibilityFocus() {
9706        clearAccessibilityFocusNoCallbacks(0);
9707
9708        // Clear the global reference of accessibility focus if this view or
9709        // any of its descendants had accessibility focus. This will NOT send
9710        // an event or update internal state if focus is cleared from a
9711        // descendant view, which may leave views in inconsistent states.
9712        final ViewRootImpl viewRootImpl = getViewRootImpl();
9713        if (viewRootImpl != null) {
9714            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
9715            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9716                viewRootImpl.setAccessibilityFocus(null, null);
9717            }
9718        }
9719    }
9720
9721    private void sendAccessibilityHoverEvent(int eventType) {
9722        // Since we are not delivering to a client accessibility events from not
9723        // important views (unless the clinet request that) we need to fire the
9724        // event from the deepest view exposed to the client. As a consequence if
9725        // the user crosses a not exposed view the client will see enter and exit
9726        // of the exposed predecessor followed by and enter and exit of that same
9727        // predecessor when entering and exiting the not exposed descendant. This
9728        // is fine since the client has a clear idea which view is hovered at the
9729        // price of a couple more events being sent. This is a simple and
9730        // working solution.
9731        View source = this;
9732        while (true) {
9733            if (source.includeForAccessibility()) {
9734                source.sendAccessibilityEvent(eventType);
9735                return;
9736            }
9737            ViewParent parent = source.getParent();
9738            if (parent instanceof View) {
9739                source = (View) parent;
9740            } else {
9741                return;
9742            }
9743        }
9744    }
9745
9746    /**
9747     * Clears accessibility focus without calling any callback methods
9748     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9749     * is used separately from that one for clearing accessibility focus when
9750     * giving this focus to another view.
9751     *
9752     * @param action The action, if any, that led to focus being cleared. Set to
9753     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9754     * the window.
9755     */
9756    void clearAccessibilityFocusNoCallbacks(int action) {
9757        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9758            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9759            invalidate();
9760            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9761                AccessibilityEvent event = AccessibilityEvent.obtain(
9762                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9763                event.setAction(action);
9764                if (mAccessibilityDelegate != null) {
9765                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9766                } else {
9767                    sendAccessibilityEventUnchecked(event);
9768                }
9769            }
9770        }
9771    }
9772
9773    /**
9774     * Call this to try to give focus to a specific view or to one of its
9775     * descendants.
9776     *
9777     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9778     * false), or if it is focusable and it is not focusable in touch mode
9779     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9780     *
9781     * See also {@link #focusSearch(int)}, which is what you call to say that you
9782     * have focus, and you want your parent to look for the next one.
9783     *
9784     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9785     * {@link #FOCUS_DOWN} and <code>null</code>.
9786     *
9787     * @return Whether this view or one of its descendants actually took focus.
9788     */
9789    public final boolean requestFocus() {
9790        return requestFocus(View.FOCUS_DOWN);
9791    }
9792
9793    /**
9794     * This will request focus for whichever View was last focused within this
9795     * cluster before a focus-jump out of it.
9796     *
9797     * @hide
9798     */
9799    @TestApi
9800    public boolean restoreFocusInCluster(@FocusRealDirection int direction) {
9801        // Prioritize focusableByDefault over algorithmic focus selection.
9802        if (restoreDefaultFocus()) {
9803            return true;
9804        }
9805        return requestFocus(direction);
9806    }
9807
9808    /**
9809     * This will request focus for whichever View not in a cluster was last focused before a
9810     * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus
9811     * the "first" focusable view it finds.
9812     *
9813     * @hide
9814     */
9815    @TestApi
9816    public boolean restoreFocusNotInCluster() {
9817        return requestFocus(View.FOCUS_DOWN);
9818    }
9819
9820    /**
9821     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
9822     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
9823     *
9824     * @return Whether this view or one of its descendants actually took focus
9825     */
9826    public boolean restoreDefaultFocus() {
9827        return requestFocus(View.FOCUS_DOWN);
9828    }
9829
9830    /**
9831     * Call this to try to give focus to a specific view or to one of its
9832     * descendants and give it a hint about what direction focus is heading.
9833     *
9834     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9835     * false), or if it is focusable and it is not focusable in touch mode
9836     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9837     *
9838     * See also {@link #focusSearch(int)}, which is what you call to say that you
9839     * have focus, and you want your parent to look for the next one.
9840     *
9841     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9842     * <code>null</code> set for the previously focused rectangle.
9843     *
9844     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9845     * @return Whether this view or one of its descendants actually took focus.
9846     */
9847    public final boolean requestFocus(int direction) {
9848        return requestFocus(direction, null);
9849    }
9850
9851    /**
9852     * Call this to try to give focus to a specific view or to one of its descendants
9853     * and give it hints about the direction and a specific rectangle that the focus
9854     * is coming from.  The rectangle can help give larger views a finer grained hint
9855     * about where focus is coming from, and therefore, where to show selection, or
9856     * forward focus change internally.
9857     *
9858     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9859     * false), or if it is focusable and it is not focusable in touch mode
9860     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9861     *
9862     * A View will not take focus if it is not visible.
9863     *
9864     * A View will not take focus if one of its parents has
9865     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9866     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9867     *
9868     * See also {@link #focusSearch(int)}, which is what you call to say that you
9869     * have focus, and you want your parent to look for the next one.
9870     *
9871     * You may wish to override this method if your custom {@link View} has an internal
9872     * {@link View} that it wishes to forward the request to.
9873     *
9874     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9875     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9876     *        to give a finer grained hint about where focus is coming from.  May be null
9877     *        if there is no hint.
9878     * @return Whether this view or one of its descendants actually took focus.
9879     */
9880    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9881        return requestFocusNoSearch(direction, previouslyFocusedRect);
9882    }
9883
9884    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9885        // need to be focusable
9886        if ((mViewFlags & FOCUSABLE) != FOCUSABLE
9887                || (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9888            return false;
9889        }
9890
9891        // need to be focusable in touch mode if in touch mode
9892        if (isInTouchMode() &&
9893            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9894               return false;
9895        }
9896
9897        // need to not have any parents blocking us
9898        if (hasAncestorThatBlocksDescendantFocus()) {
9899            return false;
9900        }
9901
9902        handleFocusGainInternal(direction, previouslyFocusedRect);
9903        return true;
9904    }
9905
9906    /**
9907     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9908     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9909     * touch mode to request focus when they are touched.
9910     *
9911     * @return Whether this view or one of its descendants actually took focus.
9912     *
9913     * @see #isInTouchMode()
9914     *
9915     */
9916    public final boolean requestFocusFromTouch() {
9917        // Leave touch mode if we need to
9918        if (isInTouchMode()) {
9919            ViewRootImpl viewRoot = getViewRootImpl();
9920            if (viewRoot != null) {
9921                viewRoot.ensureTouchMode(false);
9922            }
9923        }
9924        return requestFocus(View.FOCUS_DOWN);
9925    }
9926
9927    /**
9928     * @return Whether any ancestor of this view blocks descendant focus.
9929     */
9930    private boolean hasAncestorThatBlocksDescendantFocus() {
9931        final boolean focusableInTouchMode = isFocusableInTouchMode();
9932        ViewParent ancestor = mParent;
9933        while (ancestor instanceof ViewGroup) {
9934            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9935            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9936                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9937                return true;
9938            } else {
9939                ancestor = vgAncestor.getParent();
9940            }
9941        }
9942        return false;
9943    }
9944
9945    /**
9946     * Gets the mode for determining whether this View is important for accessibility.
9947     * A view is important for accessibility if it fires accessibility events and if it
9948     * is reported to accessibility services that query the screen.
9949     *
9950     * @return The mode for determining whether a view is important for accessibility, one
9951     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
9952     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
9953     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
9954     *
9955     * @attr ref android.R.styleable#View_importantForAccessibility
9956     *
9957     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9958     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9959     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9960     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9961     */
9962    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9963            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9964            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9965            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9966            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9967                    to = "noHideDescendants")
9968        })
9969    public int getImportantForAccessibility() {
9970        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9971                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9972    }
9973
9974    /**
9975     * Sets the live region mode for this view. This indicates to accessibility
9976     * services whether they should automatically notify the user about changes
9977     * to the view's content description or text, or to the content descriptions
9978     * or text of the view's children (where applicable).
9979     * <p>
9980     * For example, in a login screen with a TextView that displays an "incorrect
9981     * password" notification, that view should be marked as a live region with
9982     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9983     * <p>
9984     * To disable change notifications for this view, use
9985     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9986     * mode for most views.
9987     * <p>
9988     * To indicate that the user should be notified of changes, use
9989     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9990     * <p>
9991     * If the view's changes should interrupt ongoing speech and notify the user
9992     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9993     *
9994     * @param mode The live region mode for this view, one of:
9995     *        <ul>
9996     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9997     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9998     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9999     *        </ul>
10000     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10001     */
10002    public void setAccessibilityLiveRegion(int mode) {
10003        if (mode != getAccessibilityLiveRegion()) {
10004            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10005            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
10006                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10007            notifyViewAccessibilityStateChangedIfNeeded(
10008                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10009        }
10010    }
10011
10012    /**
10013     * Gets the live region mode for this View.
10014     *
10015     * @return The live region mode for the view.
10016     *
10017     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10018     *
10019     * @see #setAccessibilityLiveRegion(int)
10020     */
10021    public int getAccessibilityLiveRegion() {
10022        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
10023                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
10024    }
10025
10026    /**
10027     * Sets how to determine whether this view is important for accessibility
10028     * which is if it fires accessibility events and if it is reported to
10029     * accessibility services that query the screen.
10030     *
10031     * @param mode How to determine whether this view is important for accessibility.
10032     *
10033     * @attr ref android.R.styleable#View_importantForAccessibility
10034     *
10035     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
10036     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
10037     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
10038     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
10039     */
10040    public void setImportantForAccessibility(int mode) {
10041        final int oldMode = getImportantForAccessibility();
10042        if (mode != oldMode) {
10043            final boolean hideDescendants =
10044                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
10045
10046            // If this node or its descendants are no longer important, try to
10047            // clear accessibility focus.
10048            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
10049                final View focusHost = findAccessibilityFocusHost(hideDescendants);
10050                if (focusHost != null) {
10051                    focusHost.clearAccessibilityFocus();
10052                }
10053            }
10054
10055            // If we're moving between AUTO and another state, we might not need
10056            // to send a subtree changed notification. We'll store the computed
10057            // importance, since we'll need to check it later to make sure.
10058            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
10059                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
10060            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
10061            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10062            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
10063                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10064            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
10065                notifySubtreeAccessibilityStateChangedIfNeeded();
10066            } else {
10067                notifyViewAccessibilityStateChangedIfNeeded(
10068                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10069            }
10070        }
10071    }
10072
10073    /**
10074     * Returns the view within this view's hierarchy that is hosting
10075     * accessibility focus.
10076     *
10077     * @param searchDescendants whether to search for focus in descendant views
10078     * @return the view hosting accessibility focus, or {@code null}
10079     */
10080    private View findAccessibilityFocusHost(boolean searchDescendants) {
10081        if (isAccessibilityFocusedViewOrHost()) {
10082            return this;
10083        }
10084
10085        if (searchDescendants) {
10086            final ViewRootImpl viewRoot = getViewRootImpl();
10087            if (viewRoot != null) {
10088                final View focusHost = viewRoot.getAccessibilityFocusedHost();
10089                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
10090                    return focusHost;
10091                }
10092            }
10093        }
10094
10095        return null;
10096    }
10097
10098    /**
10099     * Computes whether this view should be exposed for accessibility. In
10100     * general, views that are interactive or provide information are exposed
10101     * while views that serve only as containers are hidden.
10102     * <p>
10103     * If an ancestor of this view has importance
10104     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
10105     * returns <code>false</code>.
10106     * <p>
10107     * Otherwise, the value is computed according to the view's
10108     * {@link #getImportantForAccessibility()} value:
10109     * <ol>
10110     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
10111     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
10112     * </code>
10113     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
10114     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
10115     * view satisfies any of the following:
10116     * <ul>
10117     * <li>Is actionable, e.g. {@link #isClickable()},
10118     * {@link #isLongClickable()}, or {@link #isFocusable()}
10119     * <li>Has an {@link AccessibilityDelegate}
10120     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
10121     * {@link OnKeyListener}, etc.
10122     * <li>Is an accessibility live region, e.g.
10123     * {@link #getAccessibilityLiveRegion()} is not
10124     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
10125     * </ul>
10126     * </ol>
10127     *
10128     * @return Whether the view is exposed for accessibility.
10129     * @see #setImportantForAccessibility(int)
10130     * @see #getImportantForAccessibility()
10131     */
10132    public boolean isImportantForAccessibility() {
10133        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
10134                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
10135        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
10136                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10137            return false;
10138        }
10139
10140        // Check parent mode to ensure we're not hidden.
10141        ViewParent parent = mParent;
10142        while (parent instanceof View) {
10143            if (((View) parent).getImportantForAccessibility()
10144                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10145                return false;
10146            }
10147            parent = parent.getParent();
10148        }
10149
10150        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
10151                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
10152                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
10153    }
10154
10155    /**
10156     * Gets the parent for accessibility purposes. Note that the parent for
10157     * accessibility is not necessary the immediate parent. It is the first
10158     * predecessor that is important for accessibility.
10159     *
10160     * @return The parent for accessibility purposes.
10161     */
10162    public ViewParent getParentForAccessibility() {
10163        if (mParent instanceof View) {
10164            View parentView = (View) mParent;
10165            if (parentView.includeForAccessibility()) {
10166                return mParent;
10167            } else {
10168                return mParent.getParentForAccessibility();
10169            }
10170        }
10171        return null;
10172    }
10173
10174    /**
10175     * Adds the children of this View relevant for accessibility to the given list
10176     * as output. Since some Views are not important for accessibility the added
10177     * child views are not necessarily direct children of this view, rather they are
10178     * the first level of descendants important for accessibility.
10179     *
10180     * @param outChildren The output list that will receive children for accessibility.
10181     */
10182    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
10183
10184    }
10185
10186    /**
10187     * Whether to regard this view for accessibility. A view is regarded for
10188     * accessibility if it is important for accessibility or the querying
10189     * accessibility service has explicitly requested that view not
10190     * important for accessibility are regarded.
10191     *
10192     * @return Whether to regard the view for accessibility.
10193     *
10194     * @hide
10195     */
10196    public boolean includeForAccessibility() {
10197        if (mAttachInfo != null) {
10198            return (mAttachInfo.mAccessibilityFetchFlags
10199                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
10200                    || isImportantForAccessibility();
10201        }
10202        return false;
10203    }
10204
10205    /**
10206     * Returns whether the View is considered actionable from
10207     * accessibility perspective. Such view are important for
10208     * accessibility.
10209     *
10210     * @return True if the view is actionable for accessibility.
10211     *
10212     * @hide
10213     */
10214    public boolean isActionableForAccessibility() {
10215        return (isClickable() || isLongClickable() || isFocusable());
10216    }
10217
10218    /**
10219     * Returns whether the View has registered callbacks which makes it
10220     * important for accessibility.
10221     *
10222     * @return True if the view is actionable for accessibility.
10223     */
10224    private boolean hasListenersForAccessibility() {
10225        ListenerInfo info = getListenerInfo();
10226        return mTouchDelegate != null || info.mOnKeyListener != null
10227                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
10228                || info.mOnHoverListener != null || info.mOnDragListener != null;
10229    }
10230
10231    /**
10232     * Notifies that the accessibility state of this view changed. The change
10233     * is local to this view and does not represent structural changes such
10234     * as children and parent. For example, the view became focusable. The
10235     * notification is at at most once every
10236     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10237     * to avoid unnecessary load to the system. Also once a view has a pending
10238     * notification this method is a NOP until the notification has been sent.
10239     *
10240     * @hide
10241     */
10242    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
10243        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10244            return;
10245        }
10246        if (mSendViewStateChangedAccessibilityEvent == null) {
10247            mSendViewStateChangedAccessibilityEvent =
10248                    new SendViewStateChangedAccessibilityEvent();
10249        }
10250        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
10251    }
10252
10253    /**
10254     * Notifies that the accessibility state of this view changed. The change
10255     * is *not* local to this view and does represent structural changes such
10256     * as children and parent. For example, the view size changed. The
10257     * notification is at at most once every
10258     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10259     * to avoid unnecessary load to the system. Also once a view has a pending
10260     * notification this method is a NOP until the notification has been sent.
10261     *
10262     * @hide
10263     */
10264    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
10265        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10266            return;
10267        }
10268        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
10269            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10270            if (mParent != null) {
10271                try {
10272                    mParent.notifySubtreeAccessibilityStateChanged(
10273                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
10274                } catch (AbstractMethodError e) {
10275                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10276                            " does not fully implement ViewParent", e);
10277                }
10278            }
10279        }
10280    }
10281
10282    /**
10283     * Change the visibility of the View without triggering any other changes. This is
10284     * important for transitions, where visibility changes should not adjust focus or
10285     * trigger a new layout. This is only used when the visibility has already been changed
10286     * and we need a transient value during an animation. When the animation completes,
10287     * the original visibility value is always restored.
10288     *
10289     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
10290     * @hide
10291     */
10292    public void setTransitionVisibility(@Visibility int visibility) {
10293        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
10294    }
10295
10296    /**
10297     * Reset the flag indicating the accessibility state of the subtree rooted
10298     * at this view changed.
10299     */
10300    void resetSubtreeAccessibilityStateChanged() {
10301        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10302    }
10303
10304    /**
10305     * Report an accessibility action to this view's parents for delegated processing.
10306     *
10307     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
10308     * call this method to delegate an accessibility action to a supporting parent. If the parent
10309     * returns true from its
10310     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
10311     * method this method will return true to signify that the action was consumed.</p>
10312     *
10313     * <p>This method is useful for implementing nested scrolling child views. If
10314     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
10315     * a custom view implementation may invoke this method to allow a parent to consume the
10316     * scroll first. If this method returns true the custom view should skip its own scrolling
10317     * behavior.</p>
10318     *
10319     * @param action Accessibility action to delegate
10320     * @param arguments Optional action arguments
10321     * @return true if the action was consumed by a parent
10322     */
10323    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
10324        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
10325            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
10326                return true;
10327            }
10328        }
10329        return false;
10330    }
10331
10332    /**
10333     * Performs the specified accessibility action on the view. For
10334     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
10335     * <p>
10336     * If an {@link AccessibilityDelegate} has been specified via calling
10337     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
10338     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
10339     * is responsible for handling this call.
10340     * </p>
10341     *
10342     * <p>The default implementation will delegate
10343     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
10344     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
10345     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
10346     *
10347     * @param action The action to perform.
10348     * @param arguments Optional action arguments.
10349     * @return Whether the action was performed.
10350     */
10351    public boolean performAccessibilityAction(int action, Bundle arguments) {
10352      if (mAccessibilityDelegate != null) {
10353          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
10354      } else {
10355          return performAccessibilityActionInternal(action, arguments);
10356      }
10357    }
10358
10359   /**
10360    * @see #performAccessibilityAction(int, Bundle)
10361    *
10362    * Note: Called from the default {@link AccessibilityDelegate}.
10363    *
10364    * @hide
10365    */
10366    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
10367        if (isNestedScrollingEnabled()
10368                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
10369                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
10370                || action == R.id.accessibilityActionScrollUp
10371                || action == R.id.accessibilityActionScrollLeft
10372                || action == R.id.accessibilityActionScrollDown
10373                || action == R.id.accessibilityActionScrollRight)) {
10374            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
10375                return true;
10376            }
10377        }
10378
10379        switch (action) {
10380            case AccessibilityNodeInfo.ACTION_CLICK: {
10381                if (isClickable()) {
10382                    performClick();
10383                    return true;
10384                }
10385            } break;
10386            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
10387                if (isLongClickable()) {
10388                    performLongClick();
10389                    return true;
10390                }
10391            } break;
10392            case AccessibilityNodeInfo.ACTION_FOCUS: {
10393                if (!hasFocus()) {
10394                    // Get out of touch mode since accessibility
10395                    // wants to move focus around.
10396                    getViewRootImpl().ensureTouchMode(false);
10397                    return requestFocus();
10398                }
10399            } break;
10400            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
10401                if (hasFocus()) {
10402                    clearFocus();
10403                    return !isFocused();
10404                }
10405            } break;
10406            case AccessibilityNodeInfo.ACTION_SELECT: {
10407                if (!isSelected()) {
10408                    setSelected(true);
10409                    return isSelected();
10410                }
10411            } break;
10412            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
10413                if (isSelected()) {
10414                    setSelected(false);
10415                    return !isSelected();
10416                }
10417            } break;
10418            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
10419                if (!isAccessibilityFocused()) {
10420                    return requestAccessibilityFocus();
10421                }
10422            } break;
10423            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
10424                if (isAccessibilityFocused()) {
10425                    clearAccessibilityFocus();
10426                    return true;
10427                }
10428            } break;
10429            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
10430                if (arguments != null) {
10431                    final int granularity = arguments.getInt(
10432                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10433                    final boolean extendSelection = arguments.getBoolean(
10434                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10435                    return traverseAtGranularity(granularity, true, extendSelection);
10436                }
10437            } break;
10438            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
10439                if (arguments != null) {
10440                    final int granularity = arguments.getInt(
10441                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10442                    final boolean extendSelection = arguments.getBoolean(
10443                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10444                    return traverseAtGranularity(granularity, false, extendSelection);
10445                }
10446            } break;
10447            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
10448                CharSequence text = getIterableTextForAccessibility();
10449                if (text == null) {
10450                    return false;
10451                }
10452                final int start = (arguments != null) ? arguments.getInt(
10453                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
10454                final int end = (arguments != null) ? arguments.getInt(
10455                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
10456                // Only cursor position can be specified (selection length == 0)
10457                if ((getAccessibilitySelectionStart() != start
10458                        || getAccessibilitySelectionEnd() != end)
10459                        && (start == end)) {
10460                    setAccessibilitySelection(start, end);
10461                    notifyViewAccessibilityStateChangedIfNeeded(
10462                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10463                    return true;
10464                }
10465            } break;
10466            case R.id.accessibilityActionShowOnScreen: {
10467                if (mAttachInfo != null) {
10468                    final Rect r = mAttachInfo.mTmpInvalRect;
10469                    getDrawingRect(r);
10470                    return requestRectangleOnScreen(r, true);
10471                }
10472            } break;
10473            case R.id.accessibilityActionContextClick: {
10474                if (isContextClickable()) {
10475                    performContextClick();
10476                    return true;
10477                }
10478            } break;
10479        }
10480        return false;
10481    }
10482
10483    private boolean traverseAtGranularity(int granularity, boolean forward,
10484            boolean extendSelection) {
10485        CharSequence text = getIterableTextForAccessibility();
10486        if (text == null || text.length() == 0) {
10487            return false;
10488        }
10489        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
10490        if (iterator == null) {
10491            return false;
10492        }
10493        int current = getAccessibilitySelectionEnd();
10494        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10495            current = forward ? 0 : text.length();
10496        }
10497        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
10498        if (range == null) {
10499            return false;
10500        }
10501        final int segmentStart = range[0];
10502        final int segmentEnd = range[1];
10503        int selectionStart;
10504        int selectionEnd;
10505        if (extendSelection && isAccessibilitySelectionExtendable()) {
10506            selectionStart = getAccessibilitySelectionStart();
10507            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10508                selectionStart = forward ? segmentStart : segmentEnd;
10509            }
10510            selectionEnd = forward ? segmentEnd : segmentStart;
10511        } else {
10512            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
10513        }
10514        setAccessibilitySelection(selectionStart, selectionEnd);
10515        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
10516                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
10517        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
10518        return true;
10519    }
10520
10521    /**
10522     * Gets the text reported for accessibility purposes.
10523     *
10524     * @return The accessibility text.
10525     *
10526     * @hide
10527     */
10528    public CharSequence getIterableTextForAccessibility() {
10529        return getContentDescription();
10530    }
10531
10532    /**
10533     * Gets whether accessibility selection can be extended.
10534     *
10535     * @return If selection is extensible.
10536     *
10537     * @hide
10538     */
10539    public boolean isAccessibilitySelectionExtendable() {
10540        return false;
10541    }
10542
10543    /**
10544     * @hide
10545     */
10546    public int getAccessibilitySelectionStart() {
10547        return mAccessibilityCursorPosition;
10548    }
10549
10550    /**
10551     * @hide
10552     */
10553    public int getAccessibilitySelectionEnd() {
10554        return getAccessibilitySelectionStart();
10555    }
10556
10557    /**
10558     * @hide
10559     */
10560    public void setAccessibilitySelection(int start, int end) {
10561        if (start ==  end && end == mAccessibilityCursorPosition) {
10562            return;
10563        }
10564        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
10565            mAccessibilityCursorPosition = start;
10566        } else {
10567            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
10568        }
10569        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
10570    }
10571
10572    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
10573            int fromIndex, int toIndex) {
10574        if (mParent == null) {
10575            return;
10576        }
10577        AccessibilityEvent event = AccessibilityEvent.obtain(
10578                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
10579        onInitializeAccessibilityEvent(event);
10580        onPopulateAccessibilityEvent(event);
10581        event.setFromIndex(fromIndex);
10582        event.setToIndex(toIndex);
10583        event.setAction(action);
10584        event.setMovementGranularity(granularity);
10585        mParent.requestSendAccessibilityEvent(this, event);
10586    }
10587
10588    /**
10589     * @hide
10590     */
10591    public TextSegmentIterator getIteratorForGranularity(int granularity) {
10592        switch (granularity) {
10593            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
10594                CharSequence text = getIterableTextForAccessibility();
10595                if (text != null && text.length() > 0) {
10596                    CharacterTextSegmentIterator iterator =
10597                        CharacterTextSegmentIterator.getInstance(
10598                                mContext.getResources().getConfiguration().locale);
10599                    iterator.initialize(text.toString());
10600                    return iterator;
10601                }
10602            } break;
10603            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
10604                CharSequence text = getIterableTextForAccessibility();
10605                if (text != null && text.length() > 0) {
10606                    WordTextSegmentIterator iterator =
10607                        WordTextSegmentIterator.getInstance(
10608                                mContext.getResources().getConfiguration().locale);
10609                    iterator.initialize(text.toString());
10610                    return iterator;
10611                }
10612            } break;
10613            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
10614                CharSequence text = getIterableTextForAccessibility();
10615                if (text != null && text.length() > 0) {
10616                    ParagraphTextSegmentIterator iterator =
10617                        ParagraphTextSegmentIterator.getInstance();
10618                    iterator.initialize(text.toString());
10619                    return iterator;
10620                }
10621            } break;
10622        }
10623        return null;
10624    }
10625
10626    /**
10627     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
10628     * and {@link #onFinishTemporaryDetach()}.
10629     *
10630     * <p>This method always returns {@code true} when called directly or indirectly from
10631     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
10632     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
10633     * <ul>
10634     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
10635     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
10636     * </ul>
10637     * </p>
10638     *
10639     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
10640     * and {@link #onFinishTemporaryDetach()}.
10641     */
10642    public final boolean isTemporarilyDetached() {
10643        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
10644    }
10645
10646    /**
10647     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
10648     * a container View.
10649     */
10650    @CallSuper
10651    public void dispatchStartTemporaryDetach() {
10652        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
10653        onStartTemporaryDetach();
10654    }
10655
10656    /**
10657     * This is called when a container is going to temporarily detach a child, with
10658     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
10659     * It will either be followed by {@link #onFinishTemporaryDetach()} or
10660     * {@link #onDetachedFromWindow()} when the container is done.
10661     */
10662    public void onStartTemporaryDetach() {
10663        removeUnsetPressCallback();
10664        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
10665    }
10666
10667    /**
10668     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
10669     * a container View.
10670     */
10671    @CallSuper
10672    public void dispatchFinishTemporaryDetach() {
10673        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
10674        onFinishTemporaryDetach();
10675        if (hasWindowFocus() && hasFocus()) {
10676            InputMethodManager.getInstance().focusIn(this);
10677        }
10678    }
10679
10680    /**
10681     * Called after {@link #onStartTemporaryDetach} when the container is done
10682     * changing the view.
10683     */
10684    public void onFinishTemporaryDetach() {
10685    }
10686
10687    /**
10688     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
10689     * for this view's window.  Returns null if the view is not currently attached
10690     * to the window.  Normally you will not need to use this directly, but
10691     * just use the standard high-level event callbacks like
10692     * {@link #onKeyDown(int, KeyEvent)}.
10693     */
10694    public KeyEvent.DispatcherState getKeyDispatcherState() {
10695        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
10696    }
10697
10698    /**
10699     * Dispatch a key event before it is processed by any input method
10700     * associated with the view hierarchy.  This can be used to intercept
10701     * key events in special situations before the IME consumes them; a
10702     * typical example would be handling the BACK key to update the application's
10703     * UI instead of allowing the IME to see it and close itself.
10704     *
10705     * @param event The key event to be dispatched.
10706     * @return True if the event was handled, false otherwise.
10707     */
10708    public boolean dispatchKeyEventPreIme(KeyEvent event) {
10709        return onKeyPreIme(event.getKeyCode(), event);
10710    }
10711
10712    /**
10713     * Dispatch a key event to the next view on the focus path. This path runs
10714     * from the top of the view tree down to the currently focused view. If this
10715     * view has focus, it will dispatch to itself. Otherwise it will dispatch
10716     * the next node down the focus path. This method also fires any key
10717     * listeners.
10718     *
10719     * @param event The key event to be dispatched.
10720     * @return True if the event was handled, false otherwise.
10721     */
10722    public boolean dispatchKeyEvent(KeyEvent event) {
10723        if (mInputEventConsistencyVerifier != null) {
10724            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
10725        }
10726
10727        // Give any attached key listener a first crack at the event.
10728        //noinspection SimplifiableIfStatement
10729        ListenerInfo li = mListenerInfo;
10730        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10731                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
10732            return true;
10733        }
10734
10735        if (event.dispatch(this, mAttachInfo != null
10736                ? mAttachInfo.mKeyDispatchState : null, this)) {
10737            return true;
10738        }
10739
10740        if (mInputEventConsistencyVerifier != null) {
10741            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10742        }
10743        return false;
10744    }
10745
10746    /**
10747     * Dispatches a key shortcut event.
10748     *
10749     * @param event The key event to be dispatched.
10750     * @return True if the event was handled by the view, false otherwise.
10751     */
10752    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
10753        return onKeyShortcut(event.getKeyCode(), event);
10754    }
10755
10756    /**
10757     * Pass the touch screen motion event down to the target view, or this
10758     * view if it is the target.
10759     *
10760     * @param event The motion event to be dispatched.
10761     * @return True if the event was handled by the view, false otherwise.
10762     */
10763    public boolean dispatchTouchEvent(MotionEvent event) {
10764        // If the event should be handled by accessibility focus first.
10765        if (event.isTargetAccessibilityFocus()) {
10766            // We don't have focus or no virtual descendant has it, do not handle the event.
10767            if (!isAccessibilityFocusedViewOrHost()) {
10768                return false;
10769            }
10770            // We have focus and got the event, then use normal event dispatch.
10771            event.setTargetAccessibilityFocus(false);
10772        }
10773
10774        boolean result = false;
10775
10776        if (mInputEventConsistencyVerifier != null) {
10777            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
10778        }
10779
10780        final int actionMasked = event.getActionMasked();
10781        if (actionMasked == MotionEvent.ACTION_DOWN) {
10782            // Defensive cleanup for new gesture
10783            stopNestedScroll();
10784        }
10785
10786        if (onFilterTouchEventForSecurity(event)) {
10787            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10788                result = true;
10789            }
10790            //noinspection SimplifiableIfStatement
10791            ListenerInfo li = mListenerInfo;
10792            if (li != null && li.mOnTouchListener != null
10793                    && (mViewFlags & ENABLED_MASK) == ENABLED
10794                    && li.mOnTouchListener.onTouch(this, event)) {
10795                result = true;
10796            }
10797
10798            if (!result && onTouchEvent(event)) {
10799                result = true;
10800            }
10801        }
10802
10803        if (!result && mInputEventConsistencyVerifier != null) {
10804            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10805        }
10806
10807        // Clean up after nested scrolls if this is the end of a gesture;
10808        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10809        // of the gesture.
10810        if (actionMasked == MotionEvent.ACTION_UP ||
10811                actionMasked == MotionEvent.ACTION_CANCEL ||
10812                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10813            stopNestedScroll();
10814        }
10815
10816        return result;
10817    }
10818
10819    boolean isAccessibilityFocusedViewOrHost() {
10820        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10821                .getAccessibilityFocusedHost() == this);
10822    }
10823
10824    /**
10825     * Filter the touch event to apply security policies.
10826     *
10827     * @param event The motion event to be filtered.
10828     * @return True if the event should be dispatched, false if the event should be dropped.
10829     *
10830     * @see #getFilterTouchesWhenObscured
10831     */
10832    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10833        //noinspection RedundantIfStatement
10834        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10835                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10836            // Window is obscured, drop this touch.
10837            return false;
10838        }
10839        return true;
10840    }
10841
10842    /**
10843     * Pass a trackball motion event down to the focused view.
10844     *
10845     * @param event The motion event to be dispatched.
10846     * @return True if the event was handled by the view, false otherwise.
10847     */
10848    public boolean dispatchTrackballEvent(MotionEvent event) {
10849        if (mInputEventConsistencyVerifier != null) {
10850            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10851        }
10852
10853        return onTrackballEvent(event);
10854    }
10855
10856    /**
10857     * Pass a captured pointer event down to the focused view.
10858     *
10859     * @param event The motion event to be dispatched.
10860     * @return True if the event was handled by the view, false otherwise.
10861     */
10862    public boolean dispatchCapturedPointerEvent(MotionEvent event) {
10863        if (!hasPointerCapture()) {
10864            return false;
10865        }
10866        //noinspection SimplifiableIfStatement
10867        ListenerInfo li = mListenerInfo;
10868        if (li != null && li.mOnCapturedPointerListener != null
10869                && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
10870            return true;
10871        }
10872        return onCapturedPointerEvent(event);
10873    }
10874
10875    /**
10876     * Dispatch a generic motion event.
10877     * <p>
10878     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10879     * are delivered to the view under the pointer.  All other generic motion events are
10880     * delivered to the focused view.  Hover events are handled specially and are delivered
10881     * to {@link #onHoverEvent(MotionEvent)}.
10882     * </p>
10883     *
10884     * @param event The motion event to be dispatched.
10885     * @return True if the event was handled by the view, false otherwise.
10886     */
10887    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10888        if (mInputEventConsistencyVerifier != null) {
10889            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10890        }
10891
10892        final int source = event.getSource();
10893        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10894            final int action = event.getAction();
10895            if (action == MotionEvent.ACTION_HOVER_ENTER
10896                    || action == MotionEvent.ACTION_HOVER_MOVE
10897                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10898                if (dispatchHoverEvent(event)) {
10899                    return true;
10900                }
10901            } else if (dispatchGenericPointerEvent(event)) {
10902                return true;
10903            }
10904        } else if (dispatchGenericFocusedEvent(event)) {
10905            return true;
10906        }
10907
10908        if (dispatchGenericMotionEventInternal(event)) {
10909            return true;
10910        }
10911
10912        if (mInputEventConsistencyVerifier != null) {
10913            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10914        }
10915        return false;
10916    }
10917
10918    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10919        //noinspection SimplifiableIfStatement
10920        ListenerInfo li = mListenerInfo;
10921        if (li != null && li.mOnGenericMotionListener != null
10922                && (mViewFlags & ENABLED_MASK) == ENABLED
10923                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10924            return true;
10925        }
10926
10927        if (onGenericMotionEvent(event)) {
10928            return true;
10929        }
10930
10931        final int actionButton = event.getActionButton();
10932        switch (event.getActionMasked()) {
10933            case MotionEvent.ACTION_BUTTON_PRESS:
10934                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10935                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10936                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10937                    if (performContextClick(event.getX(), event.getY())) {
10938                        mInContextButtonPress = true;
10939                        setPressed(true, event.getX(), event.getY());
10940                        removeTapCallback();
10941                        removeLongPressCallback();
10942                        return true;
10943                    }
10944                }
10945                break;
10946
10947            case MotionEvent.ACTION_BUTTON_RELEASE:
10948                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10949                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10950                    mInContextButtonPress = false;
10951                    mIgnoreNextUpEvent = true;
10952                }
10953                break;
10954        }
10955
10956        if (mInputEventConsistencyVerifier != null) {
10957            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10958        }
10959        return false;
10960    }
10961
10962    /**
10963     * Dispatch a hover event.
10964     * <p>
10965     * Do not call this method directly.
10966     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10967     * </p>
10968     *
10969     * @param event The motion event to be dispatched.
10970     * @return True if the event was handled by the view, false otherwise.
10971     */
10972    protected boolean dispatchHoverEvent(MotionEvent event) {
10973        ListenerInfo li = mListenerInfo;
10974        //noinspection SimplifiableIfStatement
10975        if (li != null && li.mOnHoverListener != null
10976                && (mViewFlags & ENABLED_MASK) == ENABLED
10977                && li.mOnHoverListener.onHover(this, event)) {
10978            return true;
10979        }
10980
10981        return onHoverEvent(event);
10982    }
10983
10984    /**
10985     * Returns true if the view has a child to which it has recently sent
10986     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10987     * it does not have a hovered child, then it must be the innermost hovered view.
10988     * @hide
10989     */
10990    protected boolean hasHoveredChild() {
10991        return false;
10992    }
10993
10994    /**
10995     * Dispatch a generic motion event to the view under the first pointer.
10996     * <p>
10997     * Do not call this method directly.
10998     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10999     * </p>
11000     *
11001     * @param event The motion event to be dispatched.
11002     * @return True if the event was handled by the view, false otherwise.
11003     */
11004    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
11005        return false;
11006    }
11007
11008    /**
11009     * Dispatch a generic motion event to the currently focused view.
11010     * <p>
11011     * Do not call this method directly.
11012     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11013     * </p>
11014     *
11015     * @param event The motion event to be dispatched.
11016     * @return True if the event was handled by the view, false otherwise.
11017     */
11018    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
11019        return false;
11020    }
11021
11022    /**
11023     * Dispatch a pointer event.
11024     * <p>
11025     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
11026     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
11027     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
11028     * and should not be expected to handle other pointing device features.
11029     * </p>
11030     *
11031     * @param event The motion event to be dispatched.
11032     * @return True if the event was handled by the view, false otherwise.
11033     * @hide
11034     */
11035    public final boolean dispatchPointerEvent(MotionEvent event) {
11036        if (event.isTouchEvent()) {
11037            return dispatchTouchEvent(event);
11038        } else {
11039            return dispatchGenericMotionEvent(event);
11040        }
11041    }
11042
11043    /**
11044     * Called when the window containing this view gains or loses window focus.
11045     * ViewGroups should override to route to their children.
11046     *
11047     * @param hasFocus True if the window containing this view now has focus,
11048     *        false otherwise.
11049     */
11050    public void dispatchWindowFocusChanged(boolean hasFocus) {
11051        onWindowFocusChanged(hasFocus);
11052    }
11053
11054    /**
11055     * Called when the window containing this view gains or loses focus.  Note
11056     * that this is separate from view focus: to receive key events, both
11057     * your view and its window must have focus.  If a window is displayed
11058     * on top of yours that takes input focus, then your own window will lose
11059     * focus but the view focus will remain unchanged.
11060     *
11061     * @param hasWindowFocus True if the window containing this view now has
11062     *        focus, false otherwise.
11063     */
11064    public void onWindowFocusChanged(boolean hasWindowFocus) {
11065        InputMethodManager imm = InputMethodManager.peekInstance();
11066        if (!hasWindowFocus) {
11067            if (isPressed()) {
11068                setPressed(false);
11069            }
11070            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11071            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11072                imm.focusOut(this);
11073            }
11074            removeLongPressCallback();
11075            removeTapCallback();
11076            onFocusLost();
11077        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11078            imm.focusIn(this);
11079        }
11080        refreshDrawableState();
11081    }
11082
11083    /**
11084     * Returns true if this view is in a window that currently has window focus.
11085     * Note that this is not the same as the view itself having focus.
11086     *
11087     * @return True if this view is in a window that currently has window focus.
11088     */
11089    public boolean hasWindowFocus() {
11090        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
11091    }
11092
11093    /**
11094     * Dispatch a view visibility change down the view hierarchy.
11095     * ViewGroups should override to route to their children.
11096     * @param changedView The view whose visibility changed. Could be 'this' or
11097     * an ancestor view.
11098     * @param visibility The new visibility of changedView: {@link #VISIBLE},
11099     * {@link #INVISIBLE} or {@link #GONE}.
11100     */
11101    protected void dispatchVisibilityChanged(@NonNull View changedView,
11102            @Visibility int visibility) {
11103        onVisibilityChanged(changedView, visibility);
11104    }
11105
11106    /**
11107     * Called when the visibility of the view or an ancestor of the view has
11108     * changed.
11109     *
11110     * @param changedView The view whose visibility changed. May be
11111     *                    {@code this} or an ancestor view.
11112     * @param visibility The new visibility, one of {@link #VISIBLE},
11113     *                   {@link #INVISIBLE} or {@link #GONE}.
11114     */
11115    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
11116    }
11117
11118    /**
11119     * Dispatch a hint about whether this view is displayed. For instance, when
11120     * a View moves out of the screen, it might receives a display hint indicating
11121     * the view is not displayed. Applications should not <em>rely</em> on this hint
11122     * as there is no guarantee that they will receive one.
11123     *
11124     * @param hint A hint about whether or not this view is displayed:
11125     * {@link #VISIBLE} or {@link #INVISIBLE}.
11126     */
11127    public void dispatchDisplayHint(@Visibility int hint) {
11128        onDisplayHint(hint);
11129    }
11130
11131    /**
11132     * Gives this view a hint about whether is displayed or not. For instance, when
11133     * a View moves out of the screen, it might receives a display hint indicating
11134     * the view is not displayed. Applications should not <em>rely</em> on this hint
11135     * as there is no guarantee that they will receive one.
11136     *
11137     * @param hint A hint about whether or not this view is displayed:
11138     * {@link #VISIBLE} or {@link #INVISIBLE}.
11139     */
11140    protected void onDisplayHint(@Visibility int hint) {
11141    }
11142
11143    /**
11144     * Dispatch a window visibility change down the view hierarchy.
11145     * ViewGroups should override to route to their children.
11146     *
11147     * @param visibility The new visibility of the window.
11148     *
11149     * @see #onWindowVisibilityChanged(int)
11150     */
11151    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
11152        onWindowVisibilityChanged(visibility);
11153    }
11154
11155    /**
11156     * Called when the window containing has change its visibility
11157     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
11158     * that this tells you whether or not your window is being made visible
11159     * to the window manager; this does <em>not</em> tell you whether or not
11160     * your window is obscured by other windows on the screen, even if it
11161     * is itself visible.
11162     *
11163     * @param visibility The new visibility of the window.
11164     */
11165    protected void onWindowVisibilityChanged(@Visibility int visibility) {
11166        if (visibility == VISIBLE) {
11167            initialAwakenScrollBars();
11168        }
11169    }
11170
11171    /**
11172     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
11173     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
11174     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
11175     *
11176     * @param isVisible true if this view's visibility to the user is uninterrupted by its
11177     *                  ancestors or by window visibility
11178     * @return true if this view is visible to the user, not counting clipping or overlapping
11179     */
11180    boolean dispatchVisibilityAggregated(boolean isVisible) {
11181        final boolean thisVisible = getVisibility() == VISIBLE;
11182        // If we're not visible but something is telling us we are, ignore it.
11183        if (thisVisible || !isVisible) {
11184            onVisibilityAggregated(isVisible);
11185        }
11186        return thisVisible && isVisible;
11187    }
11188
11189    /**
11190     * Called when the user-visibility of this View is potentially affected by a change
11191     * to this view itself, an ancestor view or the window this view is attached to.
11192     *
11193     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
11194     *                  and this view's window is also visible
11195     */
11196    @CallSuper
11197    public void onVisibilityAggregated(boolean isVisible) {
11198        if (isVisible && mAttachInfo != null) {
11199            initialAwakenScrollBars();
11200        }
11201
11202        final Drawable dr = mBackground;
11203        if (dr != null && isVisible != dr.isVisible()) {
11204            dr.setVisible(isVisible, false);
11205        }
11206        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
11207        if (fg != null && isVisible != fg.isVisible()) {
11208            fg.setVisible(isVisible, false);
11209        }
11210    }
11211
11212    /**
11213     * Returns the current visibility of the window this view is attached to
11214     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
11215     *
11216     * @return Returns the current visibility of the view's window.
11217     */
11218    @Visibility
11219    public int getWindowVisibility() {
11220        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
11221    }
11222
11223    /**
11224     * Retrieve the overall visible display size in which the window this view is
11225     * attached to has been positioned in.  This takes into account screen
11226     * decorations above the window, for both cases where the window itself
11227     * is being position inside of them or the window is being placed under
11228     * then and covered insets are used for the window to position its content
11229     * inside.  In effect, this tells you the available area where content can
11230     * be placed and remain visible to users.
11231     *
11232     * <p>This function requires an IPC back to the window manager to retrieve
11233     * the requested information, so should not be used in performance critical
11234     * code like drawing.
11235     *
11236     * @param outRect Filled in with the visible display frame.  If the view
11237     * is not attached to a window, this is simply the raw display size.
11238     */
11239    public void getWindowVisibleDisplayFrame(Rect outRect) {
11240        if (mAttachInfo != null) {
11241            try {
11242                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11243            } catch (RemoteException e) {
11244                return;
11245            }
11246            // XXX This is really broken, and probably all needs to be done
11247            // in the window manager, and we need to know more about whether
11248            // we want the area behind or in front of the IME.
11249            final Rect insets = mAttachInfo.mVisibleInsets;
11250            outRect.left += insets.left;
11251            outRect.top += insets.top;
11252            outRect.right -= insets.right;
11253            outRect.bottom -= insets.bottom;
11254            return;
11255        }
11256        // The view is not attached to a display so we don't have a context.
11257        // Make a best guess about the display size.
11258        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11259        d.getRectSize(outRect);
11260    }
11261
11262    /**
11263     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
11264     * is currently in without any insets.
11265     *
11266     * @hide
11267     */
11268    public void getWindowDisplayFrame(Rect outRect) {
11269        if (mAttachInfo != null) {
11270            try {
11271                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11272            } catch (RemoteException e) {
11273                return;
11274            }
11275            return;
11276        }
11277        // The view is not attached to a display so we don't have a context.
11278        // Make a best guess about the display size.
11279        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11280        d.getRectSize(outRect);
11281    }
11282
11283    /**
11284     * Dispatch a notification about a resource configuration change down
11285     * the view hierarchy.
11286     * ViewGroups should override to route to their children.
11287     *
11288     * @param newConfig The new resource configuration.
11289     *
11290     * @see #onConfigurationChanged(android.content.res.Configuration)
11291     */
11292    public void dispatchConfigurationChanged(Configuration newConfig) {
11293        onConfigurationChanged(newConfig);
11294    }
11295
11296    /**
11297     * Called when the current configuration of the resources being used
11298     * by the application have changed.  You can use this to decide when
11299     * to reload resources that can changed based on orientation and other
11300     * configuration characteristics.  You only need to use this if you are
11301     * not relying on the normal {@link android.app.Activity} mechanism of
11302     * recreating the activity instance upon a configuration change.
11303     *
11304     * @param newConfig The new resource configuration.
11305     */
11306    protected void onConfigurationChanged(Configuration newConfig) {
11307    }
11308
11309    /**
11310     * Private function to aggregate all per-view attributes in to the view
11311     * root.
11312     */
11313    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11314        performCollectViewAttributes(attachInfo, visibility);
11315    }
11316
11317    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11318        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
11319            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
11320                attachInfo.mKeepScreenOn = true;
11321            }
11322            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
11323            ListenerInfo li = mListenerInfo;
11324            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
11325                attachInfo.mHasSystemUiListeners = true;
11326            }
11327        }
11328    }
11329
11330    void needGlobalAttributesUpdate(boolean force) {
11331        final AttachInfo ai = mAttachInfo;
11332        if (ai != null && !ai.mRecomputeGlobalAttributes) {
11333            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
11334                    || ai.mHasSystemUiListeners) {
11335                ai.mRecomputeGlobalAttributes = true;
11336            }
11337        }
11338    }
11339
11340    /**
11341     * Returns whether the device is currently in touch mode.  Touch mode is entered
11342     * once the user begins interacting with the device by touch, and affects various
11343     * things like whether focus is always visible to the user.
11344     *
11345     * @return Whether the device is in touch mode.
11346     */
11347    @ViewDebug.ExportedProperty
11348    public boolean isInTouchMode() {
11349        if (mAttachInfo != null) {
11350            return mAttachInfo.mInTouchMode;
11351        } else {
11352            return ViewRootImpl.isInTouchMode();
11353        }
11354    }
11355
11356    /**
11357     * Returns the context the view is running in, through which it can
11358     * access the current theme, resources, etc.
11359     *
11360     * @return The view's Context.
11361     */
11362    @ViewDebug.CapturedViewProperty
11363    public final Context getContext() {
11364        return mContext;
11365    }
11366
11367    /**
11368     * Handle a key event before it is processed by any input method
11369     * associated with the view hierarchy.  This can be used to intercept
11370     * key events in special situations before the IME consumes them; a
11371     * typical example would be handling the BACK key to update the application's
11372     * UI instead of allowing the IME to see it and close itself.
11373     *
11374     * @param keyCode The value in event.getKeyCode().
11375     * @param event Description of the key event.
11376     * @return If you handled the event, return true. If you want to allow the
11377     *         event to be handled by the next receiver, return false.
11378     */
11379    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
11380        return false;
11381    }
11382
11383    /**
11384     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
11385     * KeyEvent.Callback.onKeyDown()}: perform press of the view
11386     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
11387     * is released, if the view is enabled and clickable.
11388     * <p>
11389     * Key presses in software keyboards will generally NOT trigger this
11390     * listener, although some may elect to do so in some situations. Do not
11391     * rely on this to catch software key presses.
11392     *
11393     * @param keyCode a key code that represents the button pressed, from
11394     *                {@link android.view.KeyEvent}
11395     * @param event the KeyEvent object that defines the button action
11396     */
11397    public boolean onKeyDown(int keyCode, KeyEvent event) {
11398        if (KeyEvent.isConfirmKey(keyCode)) {
11399            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11400                return true;
11401            }
11402
11403            if (event.getRepeatCount() == 0) {
11404                // Long clickable items don't necessarily have to be clickable.
11405                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
11406                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
11407                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
11408                    // For the purposes of menu anchoring and drawable hotspots,
11409                    // key events are considered to be at the center of the view.
11410                    final float x = getWidth() / 2f;
11411                    final float y = getHeight() / 2f;
11412                    if (clickable) {
11413                        setPressed(true, x, y);
11414                    }
11415                    checkForLongClick(0, x, y);
11416                    return true;
11417                }
11418            }
11419        }
11420
11421        return false;
11422    }
11423
11424    /**
11425     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
11426     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
11427     * the event).
11428     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11429     * although some may elect to do so in some situations. Do not rely on this to
11430     * catch software key presses.
11431     */
11432    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
11433        return false;
11434    }
11435
11436    /**
11437     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
11438     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
11439     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
11440     * or {@link KeyEvent#KEYCODE_SPACE} is released.
11441     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11442     * although some may elect to do so in some situations. Do not rely on this to
11443     * catch software key presses.
11444     *
11445     * @param keyCode A key code that represents the button pressed, from
11446     *                {@link android.view.KeyEvent}.
11447     * @param event   The KeyEvent object that defines the button action.
11448     */
11449    public boolean onKeyUp(int keyCode, KeyEvent event) {
11450        if (KeyEvent.isConfirmKey(keyCode)) {
11451            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11452                return true;
11453            }
11454            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
11455                setPressed(false);
11456
11457                if (!mHasPerformedLongPress) {
11458                    // This is a tap, so remove the longpress check
11459                    removeLongPressCallback();
11460                    return performClick();
11461                }
11462            }
11463        }
11464        return false;
11465    }
11466
11467    /**
11468     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
11469     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
11470     * the event).
11471     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11472     * although some may elect to do so in some situations. Do not rely on this to
11473     * catch software key presses.
11474     *
11475     * @param keyCode     A key code that represents the button pressed, from
11476     *                    {@link android.view.KeyEvent}.
11477     * @param repeatCount The number of times the action was made.
11478     * @param event       The KeyEvent object that defines the button action.
11479     */
11480    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
11481        return false;
11482    }
11483
11484    /**
11485     * Called on the focused view when a key shortcut event is not handled.
11486     * Override this method to implement local key shortcuts for the View.
11487     * Key shortcuts can also be implemented by setting the
11488     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
11489     *
11490     * @param keyCode The value in event.getKeyCode().
11491     * @param event Description of the key event.
11492     * @return If you handled the event, return true. If you want to allow the
11493     *         event to be handled by the next receiver, return false.
11494     */
11495    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
11496        return false;
11497    }
11498
11499    /**
11500     * Check whether the called view is a text editor, in which case it
11501     * would make sense to automatically display a soft input window for
11502     * it.  Subclasses should override this if they implement
11503     * {@link #onCreateInputConnection(EditorInfo)} to return true if
11504     * a call on that method would return a non-null InputConnection, and
11505     * they are really a first-class editor that the user would normally
11506     * start typing on when the go into a window containing your view.
11507     *
11508     * <p>The default implementation always returns false.  This does
11509     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
11510     * will not be called or the user can not otherwise perform edits on your
11511     * view; it is just a hint to the system that this is not the primary
11512     * purpose of this view.
11513     *
11514     * @return Returns true if this view is a text editor, else false.
11515     */
11516    public boolean onCheckIsTextEditor() {
11517        return false;
11518    }
11519
11520    /**
11521     * Create a new InputConnection for an InputMethod to interact
11522     * with the view.  The default implementation returns null, since it doesn't
11523     * support input methods.  You can override this to implement such support.
11524     * This is only needed for views that take focus and text input.
11525     *
11526     * <p>When implementing this, you probably also want to implement
11527     * {@link #onCheckIsTextEditor()} to indicate you will return a
11528     * non-null InputConnection.</p>
11529     *
11530     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
11531     * object correctly and in its entirety, so that the connected IME can rely
11532     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
11533     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
11534     * must be filled in with the correct cursor position for IMEs to work correctly
11535     * with your application.</p>
11536     *
11537     * @param outAttrs Fill in with attribute information about the connection.
11538     */
11539    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
11540        return null;
11541    }
11542
11543    /**
11544     * Called by the {@link android.view.inputmethod.InputMethodManager}
11545     * when a view who is not the current
11546     * input connection target is trying to make a call on the manager.  The
11547     * default implementation returns false; you can override this to return
11548     * true for certain views if you are performing InputConnection proxying
11549     * to them.
11550     * @param view The View that is making the InputMethodManager call.
11551     * @return Return true to allow the call, false to reject.
11552     */
11553    public boolean checkInputConnectionProxy(View view) {
11554        return false;
11555    }
11556
11557    /**
11558     * Show the context menu for this view. It is not safe to hold on to the
11559     * menu after returning from this method.
11560     *
11561     * You should normally not overload this method. Overload
11562     * {@link #onCreateContextMenu(ContextMenu)} or define an
11563     * {@link OnCreateContextMenuListener} to add items to the context menu.
11564     *
11565     * @param menu The context menu to populate
11566     */
11567    public void createContextMenu(ContextMenu menu) {
11568        ContextMenuInfo menuInfo = getContextMenuInfo();
11569
11570        // Sets the current menu info so all items added to menu will have
11571        // my extra info set.
11572        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
11573
11574        onCreateContextMenu(menu);
11575        ListenerInfo li = mListenerInfo;
11576        if (li != null && li.mOnCreateContextMenuListener != null) {
11577            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
11578        }
11579
11580        // Clear the extra information so subsequent items that aren't mine don't
11581        // have my extra info.
11582        ((MenuBuilder)menu).setCurrentMenuInfo(null);
11583
11584        if (mParent != null) {
11585            mParent.createContextMenu(menu);
11586        }
11587    }
11588
11589    /**
11590     * Views should implement this if they have extra information to associate
11591     * with the context menu. The return result is supplied as a parameter to
11592     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
11593     * callback.
11594     *
11595     * @return Extra information about the item for which the context menu
11596     *         should be shown. This information will vary across different
11597     *         subclasses of View.
11598     */
11599    protected ContextMenuInfo getContextMenuInfo() {
11600        return null;
11601    }
11602
11603    /**
11604     * Views should implement this if the view itself is going to add items to
11605     * the context menu.
11606     *
11607     * @param menu the context menu to populate
11608     */
11609    protected void onCreateContextMenu(ContextMenu menu) {
11610    }
11611
11612    /**
11613     * Implement this method to handle trackball motion events.  The
11614     * <em>relative</em> movement of the trackball since the last event
11615     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
11616     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
11617     * that a movement of 1 corresponds to the user pressing one DPAD key (so
11618     * they will often be fractional values, representing the more fine-grained
11619     * movement information available from a trackball).
11620     *
11621     * @param event The motion event.
11622     * @return True if the event was handled, false otherwise.
11623     */
11624    public boolean onTrackballEvent(MotionEvent event) {
11625        return false;
11626    }
11627
11628    /**
11629     * Implement this method to handle generic motion events.
11630     * <p>
11631     * Generic motion events describe joystick movements, mouse hovers, track pad
11632     * touches, scroll wheel movements and other input events.  The
11633     * {@link MotionEvent#getSource() source} of the motion event specifies
11634     * the class of input that was received.  Implementations of this method
11635     * must examine the bits in the source before processing the event.
11636     * The following code example shows how this is done.
11637     * </p><p>
11638     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11639     * are delivered to the view under the pointer.  All other generic motion events are
11640     * delivered to the focused view.
11641     * </p>
11642     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
11643     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
11644     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
11645     *             // process the joystick movement...
11646     *             return true;
11647     *         }
11648     *     }
11649     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
11650     *         switch (event.getAction()) {
11651     *             case MotionEvent.ACTION_HOVER_MOVE:
11652     *                 // process the mouse hover movement...
11653     *                 return true;
11654     *             case MotionEvent.ACTION_SCROLL:
11655     *                 // process the scroll wheel movement...
11656     *                 return true;
11657     *         }
11658     *     }
11659     *     return super.onGenericMotionEvent(event);
11660     * }</pre>
11661     *
11662     * @param event The generic motion event being processed.
11663     * @return True if the event was handled, false otherwise.
11664     */
11665    public boolean onGenericMotionEvent(MotionEvent event) {
11666        return false;
11667    }
11668
11669    /**
11670     * Implement this method to handle hover events.
11671     * <p>
11672     * This method is called whenever a pointer is hovering into, over, or out of the
11673     * bounds of a view and the view is not currently being touched.
11674     * Hover events are represented as pointer events with action
11675     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
11676     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
11677     * </p>
11678     * <ul>
11679     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
11680     * when the pointer enters the bounds of the view.</li>
11681     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
11682     * when the pointer has already entered the bounds of the view and has moved.</li>
11683     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
11684     * when the pointer has exited the bounds of the view or when the pointer is
11685     * about to go down due to a button click, tap, or similar user action that
11686     * causes the view to be touched.</li>
11687     * </ul>
11688     * <p>
11689     * The view should implement this method to return true to indicate that it is
11690     * handling the hover event, such as by changing its drawable state.
11691     * </p><p>
11692     * The default implementation calls {@link #setHovered} to update the hovered state
11693     * of the view when a hover enter or hover exit event is received, if the view
11694     * is enabled and is clickable.  The default implementation also sends hover
11695     * accessibility events.
11696     * </p>
11697     *
11698     * @param event The motion event that describes the hover.
11699     * @return True if the view handled the hover event.
11700     *
11701     * @see #isHovered
11702     * @see #setHovered
11703     * @see #onHoverChanged
11704     */
11705    public boolean onHoverEvent(MotionEvent event) {
11706        // The root view may receive hover (or touch) events that are outside the bounds of
11707        // the window.  This code ensures that we only send accessibility events for
11708        // hovers that are actually within the bounds of the root view.
11709        final int action = event.getActionMasked();
11710        if (!mSendingHoverAccessibilityEvents) {
11711            if ((action == MotionEvent.ACTION_HOVER_ENTER
11712                    || action == MotionEvent.ACTION_HOVER_MOVE)
11713                    && !hasHoveredChild()
11714                    && pointInView(event.getX(), event.getY())) {
11715                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
11716                mSendingHoverAccessibilityEvents = true;
11717            }
11718        } else {
11719            if (action == MotionEvent.ACTION_HOVER_EXIT
11720                    || (action == MotionEvent.ACTION_MOVE
11721                            && !pointInView(event.getX(), event.getY()))) {
11722                mSendingHoverAccessibilityEvents = false;
11723                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
11724            }
11725        }
11726
11727        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
11728                && event.isFromSource(InputDevice.SOURCE_MOUSE)
11729                && isOnScrollbar(event.getX(), event.getY())) {
11730            awakenScrollBars();
11731        }
11732        if (isHoverable()) {
11733            switch (action) {
11734                case MotionEvent.ACTION_HOVER_ENTER:
11735                    setHovered(true);
11736                    break;
11737                case MotionEvent.ACTION_HOVER_EXIT:
11738                    setHovered(false);
11739                    break;
11740            }
11741
11742            // Dispatch the event to onGenericMotionEvent before returning true.
11743            // This is to provide compatibility with existing applications that
11744            // handled HOVER_MOVE events in onGenericMotionEvent and that would
11745            // break because of the new default handling for hoverable views
11746            // in onHoverEvent.
11747            // Note that onGenericMotionEvent will be called by default when
11748            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
11749            dispatchGenericMotionEventInternal(event);
11750            // The event was already handled by calling setHovered(), so always
11751            // return true.
11752            return true;
11753        }
11754
11755        return false;
11756    }
11757
11758    /**
11759     * Returns true if the view should handle {@link #onHoverEvent}
11760     * by calling {@link #setHovered} to change its hovered state.
11761     *
11762     * @return True if the view is hoverable.
11763     */
11764    private boolean isHoverable() {
11765        final int viewFlags = mViewFlags;
11766        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11767            return false;
11768        }
11769
11770        return (viewFlags & CLICKABLE) == CLICKABLE
11771                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
11772                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11773    }
11774
11775    /**
11776     * Returns true if the view is currently hovered.
11777     *
11778     * @return True if the view is currently hovered.
11779     *
11780     * @see #setHovered
11781     * @see #onHoverChanged
11782     */
11783    @ViewDebug.ExportedProperty
11784    public boolean isHovered() {
11785        return (mPrivateFlags & PFLAG_HOVERED) != 0;
11786    }
11787
11788    /**
11789     * Sets whether the view is currently hovered.
11790     * <p>
11791     * Calling this method also changes the drawable state of the view.  This
11792     * enables the view to react to hover by using different drawable resources
11793     * to change its appearance.
11794     * </p><p>
11795     * The {@link #onHoverChanged} method is called when the hovered state changes.
11796     * </p>
11797     *
11798     * @param hovered True if the view is hovered.
11799     *
11800     * @see #isHovered
11801     * @see #onHoverChanged
11802     */
11803    public void setHovered(boolean hovered) {
11804        if (hovered) {
11805            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11806                mPrivateFlags |= PFLAG_HOVERED;
11807                refreshDrawableState();
11808                onHoverChanged(true);
11809            }
11810        } else {
11811            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11812                mPrivateFlags &= ~PFLAG_HOVERED;
11813                refreshDrawableState();
11814                onHoverChanged(false);
11815            }
11816        }
11817    }
11818
11819    /**
11820     * Implement this method to handle hover state changes.
11821     * <p>
11822     * This method is called whenever the hover state changes as a result of a
11823     * call to {@link #setHovered}.
11824     * </p>
11825     *
11826     * @param hovered The current hover state, as returned by {@link #isHovered}.
11827     *
11828     * @see #isHovered
11829     * @see #setHovered
11830     */
11831    public void onHoverChanged(boolean hovered) {
11832    }
11833
11834    /**
11835     * Handles scroll bar dragging by mouse input.
11836     *
11837     * @hide
11838     * @param event The motion event.
11839     *
11840     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11841     */
11842    protected boolean handleScrollBarDragging(MotionEvent event) {
11843        if (mScrollCache == null) {
11844            return false;
11845        }
11846        final float x = event.getX();
11847        final float y = event.getY();
11848        final int action = event.getAction();
11849        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11850                && action != MotionEvent.ACTION_DOWN)
11851                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11852                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11853            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11854            return false;
11855        }
11856
11857        switch (action) {
11858            case MotionEvent.ACTION_MOVE:
11859                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11860                    return false;
11861                }
11862                if (mScrollCache.mScrollBarDraggingState
11863                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11864                    final Rect bounds = mScrollCache.mScrollBarBounds;
11865                    getVerticalScrollBarBounds(bounds, null);
11866                    final int range = computeVerticalScrollRange();
11867                    final int offset = computeVerticalScrollOffset();
11868                    final int extent = computeVerticalScrollExtent();
11869
11870                    final int thumbLength = ScrollBarUtils.getThumbLength(
11871                            bounds.height(), bounds.width(), extent, range);
11872                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11873                            bounds.height(), thumbLength, extent, range, offset);
11874
11875                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11876                    final float maxThumbOffset = bounds.height() - thumbLength;
11877                    final float newThumbOffset =
11878                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11879                    final int height = getHeight();
11880                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11881                            && height > 0 && extent > 0) {
11882                        final int newY = Math.round((range - extent)
11883                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11884                        if (newY != getScrollY()) {
11885                            mScrollCache.mScrollBarDraggingPos = y;
11886                            setScrollY(newY);
11887                        }
11888                    }
11889                    return true;
11890                }
11891                if (mScrollCache.mScrollBarDraggingState
11892                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11893                    final Rect bounds = mScrollCache.mScrollBarBounds;
11894                    getHorizontalScrollBarBounds(bounds, null);
11895                    final int range = computeHorizontalScrollRange();
11896                    final int offset = computeHorizontalScrollOffset();
11897                    final int extent = computeHorizontalScrollExtent();
11898
11899                    final int thumbLength = ScrollBarUtils.getThumbLength(
11900                            bounds.width(), bounds.height(), extent, range);
11901                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11902                            bounds.width(), thumbLength, extent, range, offset);
11903
11904                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11905                    final float maxThumbOffset = bounds.width() - thumbLength;
11906                    final float newThumbOffset =
11907                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11908                    final int width = getWidth();
11909                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11910                            && width > 0 && extent > 0) {
11911                        final int newX = Math.round((range - extent)
11912                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11913                        if (newX != getScrollX()) {
11914                            mScrollCache.mScrollBarDraggingPos = x;
11915                            setScrollX(newX);
11916                        }
11917                    }
11918                    return true;
11919                }
11920            case MotionEvent.ACTION_DOWN:
11921                if (mScrollCache.state == ScrollabilityCache.OFF) {
11922                    return false;
11923                }
11924                if (isOnVerticalScrollbarThumb(x, y)) {
11925                    mScrollCache.mScrollBarDraggingState =
11926                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11927                    mScrollCache.mScrollBarDraggingPos = y;
11928                    return true;
11929                }
11930                if (isOnHorizontalScrollbarThumb(x, y)) {
11931                    mScrollCache.mScrollBarDraggingState =
11932                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11933                    mScrollCache.mScrollBarDraggingPos = x;
11934                    return true;
11935                }
11936        }
11937        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11938        return false;
11939    }
11940
11941    /**
11942     * Implement this method to handle touch screen motion events.
11943     * <p>
11944     * If this method is used to detect click actions, it is recommended that
11945     * the actions be performed by implementing and calling
11946     * {@link #performClick()}. This will ensure consistent system behavior,
11947     * including:
11948     * <ul>
11949     * <li>obeying click sound preferences
11950     * <li>dispatching OnClickListener calls
11951     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11952     * accessibility features are enabled
11953     * </ul>
11954     *
11955     * @param event The motion event.
11956     * @return True if the event was handled, false otherwise.
11957     */
11958    public boolean onTouchEvent(MotionEvent event) {
11959        final float x = event.getX();
11960        final float y = event.getY();
11961        final int viewFlags = mViewFlags;
11962        final int action = event.getAction();
11963
11964        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
11965                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11966                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11967
11968        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11969            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11970                setPressed(false);
11971            }
11972            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11973            // A disabled view that is clickable still consumes the touch
11974            // events, it just doesn't respond to them.
11975            return clickable;
11976        }
11977        if (mTouchDelegate != null) {
11978            if (mTouchDelegate.onTouchEvent(event)) {
11979                return true;
11980            }
11981        }
11982
11983        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
11984            switch (action) {
11985                case MotionEvent.ACTION_UP:
11986                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11987                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
11988                        handleTooltipUp();
11989                    }
11990                    if (!clickable) {
11991                        removeTapCallback();
11992                        removeLongPressCallback();
11993                        mInContextButtonPress = false;
11994                        mHasPerformedLongPress = false;
11995                        mIgnoreNextUpEvent = false;
11996                        break;
11997                    }
11998                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11999                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
12000                        // take focus if we don't have it already and we should in
12001                        // touch mode.
12002                        boolean focusTaken = false;
12003                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
12004                            focusTaken = requestFocus();
12005                        }
12006
12007                        if (prepressed) {
12008                            // The button is being released before we actually
12009                            // showed it as pressed.  Make it show the pressed
12010                            // state now (before scheduling the click) to ensure
12011                            // the user sees it.
12012                            setPressed(true, x, y);
12013                        }
12014
12015                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
12016                            // This is a tap, so remove the longpress check
12017                            removeLongPressCallback();
12018
12019                            // Only perform take click actions if we were in the pressed state
12020                            if (!focusTaken) {
12021                                // Use a Runnable and post this rather than calling
12022                                // performClick directly. This lets other visual state
12023                                // of the view update before click actions start.
12024                                if (mPerformClick == null) {
12025                                    mPerformClick = new PerformClick();
12026                                }
12027                                if (!post(mPerformClick)) {
12028                                    performClick();
12029                                }
12030                            }
12031                        }
12032
12033                        if (mUnsetPressedState == null) {
12034                            mUnsetPressedState = new UnsetPressedState();
12035                        }
12036
12037                        if (prepressed) {
12038                            postDelayed(mUnsetPressedState,
12039                                    ViewConfiguration.getPressedStateDuration());
12040                        } else if (!post(mUnsetPressedState)) {
12041                            // If the post failed, unpress right now
12042                            mUnsetPressedState.run();
12043                        }
12044
12045                        removeTapCallback();
12046                    }
12047                    mIgnoreNextUpEvent = false;
12048                    break;
12049
12050                case MotionEvent.ACTION_DOWN:
12051                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
12052                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
12053                    }
12054                    mHasPerformedLongPress = false;
12055
12056                    if (!clickable) {
12057                        checkForLongClick(0, x, y);
12058                        break;
12059                    }
12060
12061                    if (performButtonActionOnTouchDown(event)) {
12062                        break;
12063                    }
12064
12065                    // Walk up the hierarchy to determine if we're inside a scrolling container.
12066                    boolean isInScrollingContainer = isInScrollingContainer();
12067
12068                    // For views inside a scrolling container, delay the pressed feedback for
12069                    // a short period in case this is a scroll.
12070                    if (isInScrollingContainer) {
12071                        mPrivateFlags |= PFLAG_PREPRESSED;
12072                        if (mPendingCheckForTap == null) {
12073                            mPendingCheckForTap = new CheckForTap();
12074                        }
12075                        mPendingCheckForTap.x = event.getX();
12076                        mPendingCheckForTap.y = event.getY();
12077                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
12078                    } else {
12079                        // Not inside a scrolling container, so show the feedback right away
12080                        setPressed(true, x, y);
12081                        checkForLongClick(0, x, y);
12082                    }
12083                    break;
12084
12085                case MotionEvent.ACTION_CANCEL:
12086                    if (clickable) {
12087                        setPressed(false);
12088                    }
12089                    removeTapCallback();
12090                    removeLongPressCallback();
12091                    mInContextButtonPress = false;
12092                    mHasPerformedLongPress = false;
12093                    mIgnoreNextUpEvent = false;
12094                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12095                    break;
12096
12097                case MotionEvent.ACTION_MOVE:
12098                    if (clickable) {
12099                        drawableHotspotChanged(x, y);
12100                    }
12101
12102                    // Be lenient about moving outside of buttons
12103                    if (!pointInView(x, y, mTouchSlop)) {
12104                        // Outside button
12105                        // Remove any future long press/tap checks
12106                        removeTapCallback();
12107                        removeLongPressCallback();
12108                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
12109                            setPressed(false);
12110                        }
12111                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12112                    }
12113                    break;
12114            }
12115
12116            return true;
12117        }
12118
12119        return false;
12120    }
12121
12122    /**
12123     * @hide
12124     */
12125    public boolean isInScrollingContainer() {
12126        ViewParent p = getParent();
12127        while (p != null && p instanceof ViewGroup) {
12128            if (((ViewGroup) p).shouldDelayChildPressedState()) {
12129                return true;
12130            }
12131            p = p.getParent();
12132        }
12133        return false;
12134    }
12135
12136    /**
12137     * Remove the longpress detection timer.
12138     */
12139    private void removeLongPressCallback() {
12140        if (mPendingCheckForLongPress != null) {
12141            removeCallbacks(mPendingCheckForLongPress);
12142        }
12143    }
12144
12145    /**
12146     * Remove the pending click action
12147     */
12148    private void removePerformClickCallback() {
12149        if (mPerformClick != null) {
12150            removeCallbacks(mPerformClick);
12151        }
12152    }
12153
12154    /**
12155     * Remove the prepress detection timer.
12156     */
12157    private void removeUnsetPressCallback() {
12158        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
12159            setPressed(false);
12160            removeCallbacks(mUnsetPressedState);
12161        }
12162    }
12163
12164    /**
12165     * Remove the tap detection timer.
12166     */
12167    private void removeTapCallback() {
12168        if (mPendingCheckForTap != null) {
12169            mPrivateFlags &= ~PFLAG_PREPRESSED;
12170            removeCallbacks(mPendingCheckForTap);
12171        }
12172    }
12173
12174    /**
12175     * Cancels a pending long press.  Your subclass can use this if you
12176     * want the context menu to come up if the user presses and holds
12177     * at the same place, but you don't want it to come up if they press
12178     * and then move around enough to cause scrolling.
12179     */
12180    public void cancelLongPress() {
12181        removeLongPressCallback();
12182
12183        /*
12184         * The prepressed state handled by the tap callback is a display
12185         * construct, but the tap callback will post a long press callback
12186         * less its own timeout. Remove it here.
12187         */
12188        removeTapCallback();
12189    }
12190
12191    /**
12192     * Remove the pending callback for sending a
12193     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
12194     */
12195    private void removeSendViewScrolledAccessibilityEventCallback() {
12196        if (mSendViewScrolledAccessibilityEvent != null) {
12197            removeCallbacks(mSendViewScrolledAccessibilityEvent);
12198            mSendViewScrolledAccessibilityEvent.mIsPending = false;
12199        }
12200    }
12201
12202    /**
12203     * Sets the TouchDelegate for this View.
12204     */
12205    public void setTouchDelegate(TouchDelegate delegate) {
12206        mTouchDelegate = delegate;
12207    }
12208
12209    /**
12210     * Gets the TouchDelegate for this View.
12211     */
12212    public TouchDelegate getTouchDelegate() {
12213        return mTouchDelegate;
12214    }
12215
12216    /**
12217     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
12218     *
12219     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
12220     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
12221     * available. This method should only be called for touch events.
12222     *
12223     * <p class="note">This api is not intended for most applications. Buffered dispatch
12224     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
12225     * streams will not improve your input latency. Side effects include: increased latency,
12226     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
12227     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
12228     * you.</p>
12229     */
12230    public final void requestUnbufferedDispatch(MotionEvent event) {
12231        final int action = event.getAction();
12232        if (mAttachInfo == null
12233                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
12234                || !event.isTouchEvent()) {
12235            return;
12236        }
12237        mAttachInfo.mUnbufferedDispatchRequested = true;
12238    }
12239
12240    /**
12241     * Set flags controlling behavior of this view.
12242     *
12243     * @param flags Constant indicating the value which should be set
12244     * @param mask Constant indicating the bit range that should be changed
12245     */
12246    void setFlags(int flags, int mask) {
12247        final boolean accessibilityEnabled =
12248                AccessibilityManager.getInstance(mContext).isEnabled();
12249        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
12250
12251        int old = mViewFlags;
12252        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
12253
12254        int changed = mViewFlags ^ old;
12255        if (changed == 0) {
12256            return;
12257        }
12258        int privateFlags = mPrivateFlags;
12259
12260        // If focusable is auto, update the FOCUSABLE bit.
12261        int focusableChangedByAuto = 0;
12262        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
12263                && (changed & (FOCUSABLE_MASK | CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12264            int newFocus = NOT_FOCUSABLE;
12265            if ((mViewFlags & (CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12266                newFocus = FOCUSABLE;
12267            } else {
12268                mViewFlags = (mViewFlags & ~FOCUSABLE_IN_TOUCH_MODE);
12269            }
12270            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
12271            focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
12272            changed = (changed & ~FOCUSABLE) | focusableChangedByAuto;
12273        }
12274
12275        /* Check if the FOCUSABLE bit has changed */
12276        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
12277            if (((old & FOCUSABLE) == FOCUSABLE)
12278                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
12279                /* Give up focus if we are no longer focusable */
12280                clearFocus();
12281            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
12282                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
12283                /*
12284                 * Tell the view system that we are now available to take focus
12285                 * if no one else already has it.
12286                 */
12287                if (mParent != null) {
12288                    ViewRootImpl viewRootImpl = getViewRootImpl();
12289                    if (!sAutoFocusableOffUIThreadWontNotifyParents
12290                            || focusableChangedByAuto == 0
12291                            || viewRootImpl == null
12292                            || viewRootImpl.mThread == Thread.currentThread()) {
12293                        mParent.focusableViewAvailable(this);
12294                    }
12295                }
12296            }
12297        }
12298
12299        final int newVisibility = flags & VISIBILITY_MASK;
12300        if (newVisibility == VISIBLE) {
12301            if ((changed & VISIBILITY_MASK) != 0) {
12302                /*
12303                 * If this view is becoming visible, invalidate it in case it changed while
12304                 * it was not visible. Marking it drawn ensures that the invalidation will
12305                 * go through.
12306                 */
12307                mPrivateFlags |= PFLAG_DRAWN;
12308                invalidate(true);
12309
12310                needGlobalAttributesUpdate(true);
12311
12312                // a view becoming visible is worth notifying the parent
12313                // about in case nothing has focus.  even if this specific view
12314                // isn't focusable, it may contain something that is, so let
12315                // the root view try to give this focus if nothing else does.
12316                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
12317                    mParent.focusableViewAvailable(this);
12318                }
12319            }
12320        }
12321
12322        /* Check if the GONE bit has changed */
12323        if ((changed & GONE) != 0) {
12324            needGlobalAttributesUpdate(false);
12325            requestLayout();
12326
12327            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
12328                if (hasFocus()) clearFocus();
12329                clearAccessibilityFocus();
12330                destroyDrawingCache();
12331                if (mParent instanceof View) {
12332                    // GONE views noop invalidation, so invalidate the parent
12333                    ((View) mParent).invalidate(true);
12334                }
12335                // Mark the view drawn to ensure that it gets invalidated properly the next
12336                // time it is visible and gets invalidated
12337                mPrivateFlags |= PFLAG_DRAWN;
12338            }
12339            if (mAttachInfo != null) {
12340                mAttachInfo.mViewVisibilityChanged = true;
12341            }
12342        }
12343
12344        /* Check if the VISIBLE bit has changed */
12345        if ((changed & INVISIBLE) != 0) {
12346            needGlobalAttributesUpdate(false);
12347            /*
12348             * If this view is becoming invisible, set the DRAWN flag so that
12349             * the next invalidate() will not be skipped.
12350             */
12351            mPrivateFlags |= PFLAG_DRAWN;
12352
12353            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
12354                // root view becoming invisible shouldn't clear focus and accessibility focus
12355                if (getRootView() != this) {
12356                    if (hasFocus()) clearFocus();
12357                    clearAccessibilityFocus();
12358                }
12359            }
12360            if (mAttachInfo != null) {
12361                mAttachInfo.mViewVisibilityChanged = true;
12362            }
12363        }
12364
12365        if ((changed & VISIBILITY_MASK) != 0) {
12366            // If the view is invisible, cleanup its display list to free up resources
12367            if (newVisibility != VISIBLE && mAttachInfo != null) {
12368                cleanupDraw();
12369            }
12370
12371            if (mParent instanceof ViewGroup) {
12372                ((ViewGroup) mParent).onChildVisibilityChanged(this,
12373                        (changed & VISIBILITY_MASK), newVisibility);
12374                ((View) mParent).invalidate(true);
12375            } else if (mParent != null) {
12376                mParent.invalidateChild(this, null);
12377            }
12378
12379            if (mAttachInfo != null) {
12380                dispatchVisibilityChanged(this, newVisibility);
12381
12382                // Aggregated visibility changes are dispatched to attached views
12383                // in visible windows where the parent is currently shown/drawn
12384                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
12385                // discounting clipping or overlapping. This makes it a good place
12386                // to change animation states.
12387                if (mParent != null && getWindowVisibility() == VISIBLE &&
12388                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
12389                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
12390                }
12391                notifySubtreeAccessibilityStateChangedIfNeeded();
12392            }
12393        }
12394
12395        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
12396            destroyDrawingCache();
12397        }
12398
12399        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
12400            destroyDrawingCache();
12401            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12402            invalidateParentCaches();
12403        }
12404
12405        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
12406            destroyDrawingCache();
12407            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12408        }
12409
12410        if ((changed & DRAW_MASK) != 0) {
12411            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
12412                if (mBackground != null
12413                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
12414                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12415                } else {
12416                    mPrivateFlags |= PFLAG_SKIP_DRAW;
12417                }
12418            } else {
12419                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12420            }
12421            requestLayout();
12422            invalidate(true);
12423        }
12424
12425        if ((changed & KEEP_SCREEN_ON) != 0) {
12426            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12427                mParent.recomputeViewAttributes(this);
12428            }
12429        }
12430
12431        if (accessibilityEnabled) {
12432            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
12433                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
12434                    || (changed & CONTEXT_CLICKABLE) != 0) {
12435                if (oldIncludeForAccessibility != includeForAccessibility()) {
12436                    notifySubtreeAccessibilityStateChangedIfNeeded();
12437                } else {
12438                    notifyViewAccessibilityStateChangedIfNeeded(
12439                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12440                }
12441            } else if ((changed & ENABLED_MASK) != 0) {
12442                notifyViewAccessibilityStateChangedIfNeeded(
12443                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12444            }
12445        }
12446    }
12447
12448    /**
12449     * Change the view's z order in the tree, so it's on top of other sibling
12450     * views. This ordering change may affect layout, if the parent container
12451     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
12452     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
12453     * method should be followed by calls to {@link #requestLayout()} and
12454     * {@link View#invalidate()} on the view's parent to force the parent to redraw
12455     * with the new child ordering.
12456     *
12457     * @see ViewGroup#bringChildToFront(View)
12458     */
12459    public void bringToFront() {
12460        if (mParent != null) {
12461            mParent.bringChildToFront(this);
12462        }
12463    }
12464
12465    /**
12466     * This is called in response to an internal scroll in this view (i.e., the
12467     * view scrolled its own contents). This is typically as a result of
12468     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
12469     * called.
12470     *
12471     * @param l Current horizontal scroll origin.
12472     * @param t Current vertical scroll origin.
12473     * @param oldl Previous horizontal scroll origin.
12474     * @param oldt Previous vertical scroll origin.
12475     */
12476    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
12477        notifySubtreeAccessibilityStateChangedIfNeeded();
12478
12479        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
12480            postSendViewScrolledAccessibilityEventCallback();
12481        }
12482
12483        mBackgroundSizeChanged = true;
12484        if (mForegroundInfo != null) {
12485            mForegroundInfo.mBoundsChanged = true;
12486        }
12487
12488        final AttachInfo ai = mAttachInfo;
12489        if (ai != null) {
12490            ai.mViewScrollChanged = true;
12491        }
12492
12493        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
12494            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
12495        }
12496    }
12497
12498    /**
12499     * Interface definition for a callback to be invoked when the scroll
12500     * X or Y positions of a view change.
12501     * <p>
12502     * <b>Note:</b> Some views handle scrolling independently from View and may
12503     * have their own separate listeners for scroll-type events. For example,
12504     * {@link android.widget.ListView ListView} allows clients to register an
12505     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
12506     * to listen for changes in list scroll position.
12507     *
12508     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
12509     */
12510    public interface OnScrollChangeListener {
12511        /**
12512         * Called when the scroll position of a view changes.
12513         *
12514         * @param v The view whose scroll position has changed.
12515         * @param scrollX Current horizontal scroll origin.
12516         * @param scrollY Current vertical scroll origin.
12517         * @param oldScrollX Previous horizontal scroll origin.
12518         * @param oldScrollY Previous vertical scroll origin.
12519         */
12520        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
12521    }
12522
12523    /**
12524     * Interface definition for a callback to be invoked when the layout bounds of a view
12525     * changes due to layout processing.
12526     */
12527    public interface OnLayoutChangeListener {
12528        /**
12529         * Called when the layout bounds of a view changes due to layout processing.
12530         *
12531         * @param v The view whose bounds have changed.
12532         * @param left The new value of the view's left property.
12533         * @param top The new value of the view's top property.
12534         * @param right The new value of the view's right property.
12535         * @param bottom The new value of the view's bottom property.
12536         * @param oldLeft The previous value of the view's left property.
12537         * @param oldTop The previous value of the view's top property.
12538         * @param oldRight The previous value of the view's right property.
12539         * @param oldBottom The previous value of the view's bottom property.
12540         */
12541        void onLayoutChange(View v, int left, int top, int right, int bottom,
12542            int oldLeft, int oldTop, int oldRight, int oldBottom);
12543    }
12544
12545    /**
12546     * This is called during layout when the size of this view has changed. If
12547     * you were just added to the view hierarchy, you're called with the old
12548     * values of 0.
12549     *
12550     * @param w Current width of this view.
12551     * @param h Current height of this view.
12552     * @param oldw Old width of this view.
12553     * @param oldh Old height of this view.
12554     */
12555    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
12556    }
12557
12558    /**
12559     * Called by draw to draw the child views. This may be overridden
12560     * by derived classes to gain control just before its children are drawn
12561     * (but after its own view has been drawn).
12562     * @param canvas the canvas on which to draw the view
12563     */
12564    protected void dispatchDraw(Canvas canvas) {
12565
12566    }
12567
12568    /**
12569     * Gets the parent of this view. Note that the parent is a
12570     * ViewParent and not necessarily a View.
12571     *
12572     * @return Parent of this view.
12573     */
12574    public final ViewParent getParent() {
12575        return mParent;
12576    }
12577
12578    /**
12579     * Set the horizontal scrolled position of your view. This will cause a call to
12580     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12581     * invalidated.
12582     * @param value the x position to scroll to
12583     */
12584    public void setScrollX(int value) {
12585        scrollTo(value, mScrollY);
12586    }
12587
12588    /**
12589     * Set the vertical scrolled position of your view. This will cause a call to
12590     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12591     * invalidated.
12592     * @param value the y position to scroll to
12593     */
12594    public void setScrollY(int value) {
12595        scrollTo(mScrollX, value);
12596    }
12597
12598    /**
12599     * Return the scrolled left position of this view. This is the left edge of
12600     * the displayed part of your view. You do not need to draw any pixels
12601     * farther left, since those are outside of the frame of your view on
12602     * screen.
12603     *
12604     * @return The left edge of the displayed part of your view, in pixels.
12605     */
12606    public final int getScrollX() {
12607        return mScrollX;
12608    }
12609
12610    /**
12611     * Return the scrolled top position of this view. This is the top edge of
12612     * the displayed part of your view. You do not need to draw any pixels above
12613     * it, since those are outside of the frame of your view on screen.
12614     *
12615     * @return The top edge of the displayed part of your view, in pixels.
12616     */
12617    public final int getScrollY() {
12618        return mScrollY;
12619    }
12620
12621    /**
12622     * Return the width of the your view.
12623     *
12624     * @return The width of your view, in pixels.
12625     */
12626    @ViewDebug.ExportedProperty(category = "layout")
12627    public final int getWidth() {
12628        return mRight - mLeft;
12629    }
12630
12631    /**
12632     * Return the height of your view.
12633     *
12634     * @return The height of your view, in pixels.
12635     */
12636    @ViewDebug.ExportedProperty(category = "layout")
12637    public final int getHeight() {
12638        return mBottom - mTop;
12639    }
12640
12641    /**
12642     * Return the visible drawing bounds of your view. Fills in the output
12643     * rectangle with the values from getScrollX(), getScrollY(),
12644     * getWidth(), and getHeight(). These bounds do not account for any
12645     * transformation properties currently set on the view, such as
12646     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
12647     *
12648     * @param outRect The (scrolled) drawing bounds of the view.
12649     */
12650    public void getDrawingRect(Rect outRect) {
12651        outRect.left = mScrollX;
12652        outRect.top = mScrollY;
12653        outRect.right = mScrollX + (mRight - mLeft);
12654        outRect.bottom = mScrollY + (mBottom - mTop);
12655    }
12656
12657    /**
12658     * Like {@link #getMeasuredWidthAndState()}, but only returns the
12659     * raw width component (that is the result is masked by
12660     * {@link #MEASURED_SIZE_MASK}).
12661     *
12662     * @return The raw measured width of this view.
12663     */
12664    public final int getMeasuredWidth() {
12665        return mMeasuredWidth & MEASURED_SIZE_MASK;
12666    }
12667
12668    /**
12669     * Return the full width measurement information for this view as computed
12670     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12671     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12672     * This should be used during measurement and layout calculations only. Use
12673     * {@link #getWidth()} to see how wide a view is after layout.
12674     *
12675     * @return The measured width of this view as a bit mask.
12676     */
12677    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12678            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12679                    name = "MEASURED_STATE_TOO_SMALL"),
12680    })
12681    public final int getMeasuredWidthAndState() {
12682        return mMeasuredWidth;
12683    }
12684
12685    /**
12686     * Like {@link #getMeasuredHeightAndState()}, but only returns the
12687     * raw height component (that is the result is masked by
12688     * {@link #MEASURED_SIZE_MASK}).
12689     *
12690     * @return The raw measured height of this view.
12691     */
12692    public final int getMeasuredHeight() {
12693        return mMeasuredHeight & MEASURED_SIZE_MASK;
12694    }
12695
12696    /**
12697     * Return the full height measurement information for this view as computed
12698     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12699     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12700     * This should be used during measurement and layout calculations only. Use
12701     * {@link #getHeight()} to see how wide a view is after layout.
12702     *
12703     * @return The measured height of this view as a bit mask.
12704     */
12705    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12706            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12707                    name = "MEASURED_STATE_TOO_SMALL"),
12708    })
12709    public final int getMeasuredHeightAndState() {
12710        return mMeasuredHeight;
12711    }
12712
12713    /**
12714     * Return only the state bits of {@link #getMeasuredWidthAndState()}
12715     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
12716     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
12717     * and the height component is at the shifted bits
12718     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
12719     */
12720    public final int getMeasuredState() {
12721        return (mMeasuredWidth&MEASURED_STATE_MASK)
12722                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
12723                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
12724    }
12725
12726    /**
12727     * The transform matrix of this view, which is calculated based on the current
12728     * rotation, scale, and pivot properties.
12729     *
12730     * @see #getRotation()
12731     * @see #getScaleX()
12732     * @see #getScaleY()
12733     * @see #getPivotX()
12734     * @see #getPivotY()
12735     * @return The current transform matrix for the view
12736     */
12737    public Matrix getMatrix() {
12738        ensureTransformationInfo();
12739        final Matrix matrix = mTransformationInfo.mMatrix;
12740        mRenderNode.getMatrix(matrix);
12741        return matrix;
12742    }
12743
12744    /**
12745     * Returns true if the transform matrix is the identity matrix.
12746     * Recomputes the matrix if necessary.
12747     *
12748     * @return True if the transform matrix is the identity matrix, false otherwise.
12749     */
12750    final boolean hasIdentityMatrix() {
12751        return mRenderNode.hasIdentityMatrix();
12752    }
12753
12754    void ensureTransformationInfo() {
12755        if (mTransformationInfo == null) {
12756            mTransformationInfo = new TransformationInfo();
12757        }
12758    }
12759
12760    /**
12761     * Utility method to retrieve the inverse of the current mMatrix property.
12762     * We cache the matrix to avoid recalculating it when transform properties
12763     * have not changed.
12764     *
12765     * @return The inverse of the current matrix of this view.
12766     * @hide
12767     */
12768    public final Matrix getInverseMatrix() {
12769        ensureTransformationInfo();
12770        if (mTransformationInfo.mInverseMatrix == null) {
12771            mTransformationInfo.mInverseMatrix = new Matrix();
12772        }
12773        final Matrix matrix = mTransformationInfo.mInverseMatrix;
12774        mRenderNode.getInverseMatrix(matrix);
12775        return matrix;
12776    }
12777
12778    /**
12779     * Gets the distance along the Z axis from the camera to this view.
12780     *
12781     * @see #setCameraDistance(float)
12782     *
12783     * @return The distance along the Z axis.
12784     */
12785    public float getCameraDistance() {
12786        final float dpi = mResources.getDisplayMetrics().densityDpi;
12787        return -(mRenderNode.getCameraDistance() * dpi);
12788    }
12789
12790    /**
12791     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
12792     * views are drawn) from the camera to this view. The camera's distance
12793     * affects 3D transformations, for instance rotations around the X and Y
12794     * axis. If the rotationX or rotationY properties are changed and this view is
12795     * large (more than half the size of the screen), it is recommended to always
12796     * use a camera distance that's greater than the height (X axis rotation) or
12797     * the width (Y axis rotation) of this view.</p>
12798     *
12799     * <p>The distance of the camera from the view plane can have an affect on the
12800     * perspective distortion of the view when it is rotated around the x or y axis.
12801     * For example, a large distance will result in a large viewing angle, and there
12802     * will not be much perspective distortion of the view as it rotates. A short
12803     * distance may cause much more perspective distortion upon rotation, and can
12804     * also result in some drawing artifacts if the rotated view ends up partially
12805     * behind the camera (which is why the recommendation is to use a distance at
12806     * least as far as the size of the view, if the view is to be rotated.)</p>
12807     *
12808     * <p>The distance is expressed in "depth pixels." The default distance depends
12809     * on the screen density. For instance, on a medium density display, the
12810     * default distance is 1280. On a high density display, the default distance
12811     * is 1920.</p>
12812     *
12813     * <p>If you want to specify a distance that leads to visually consistent
12814     * results across various densities, use the following formula:</p>
12815     * <pre>
12816     * float scale = context.getResources().getDisplayMetrics().density;
12817     * view.setCameraDistance(distance * scale);
12818     * </pre>
12819     *
12820     * <p>The density scale factor of a high density display is 1.5,
12821     * and 1920 = 1280 * 1.5.</p>
12822     *
12823     * @param distance The distance in "depth pixels", if negative the opposite
12824     *        value is used
12825     *
12826     * @see #setRotationX(float)
12827     * @see #setRotationY(float)
12828     */
12829    public void setCameraDistance(float distance) {
12830        final float dpi = mResources.getDisplayMetrics().densityDpi;
12831
12832        invalidateViewProperty(true, false);
12833        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
12834        invalidateViewProperty(false, false);
12835
12836        invalidateParentIfNeededAndWasQuickRejected();
12837    }
12838
12839    /**
12840     * The degrees that the view is rotated around the pivot point.
12841     *
12842     * @see #setRotation(float)
12843     * @see #getPivotX()
12844     * @see #getPivotY()
12845     *
12846     * @return The degrees of rotation.
12847     */
12848    @ViewDebug.ExportedProperty(category = "drawing")
12849    public float getRotation() {
12850        return mRenderNode.getRotation();
12851    }
12852
12853    /**
12854     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12855     * result in clockwise rotation.
12856     *
12857     * @param rotation The degrees of rotation.
12858     *
12859     * @see #getRotation()
12860     * @see #getPivotX()
12861     * @see #getPivotY()
12862     * @see #setRotationX(float)
12863     * @see #setRotationY(float)
12864     *
12865     * @attr ref android.R.styleable#View_rotation
12866     */
12867    public void setRotation(float rotation) {
12868        if (rotation != getRotation()) {
12869            // Double-invalidation is necessary to capture view's old and new areas
12870            invalidateViewProperty(true, false);
12871            mRenderNode.setRotation(rotation);
12872            invalidateViewProperty(false, true);
12873
12874            invalidateParentIfNeededAndWasQuickRejected();
12875            notifySubtreeAccessibilityStateChangedIfNeeded();
12876        }
12877    }
12878
12879    /**
12880     * The degrees that the view is rotated around the vertical axis through the pivot point.
12881     *
12882     * @see #getPivotX()
12883     * @see #getPivotY()
12884     * @see #setRotationY(float)
12885     *
12886     * @return The degrees of Y rotation.
12887     */
12888    @ViewDebug.ExportedProperty(category = "drawing")
12889    public float getRotationY() {
12890        return mRenderNode.getRotationY();
12891    }
12892
12893    /**
12894     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12895     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12896     * down the y axis.
12897     *
12898     * When rotating large views, it is recommended to adjust the camera distance
12899     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12900     *
12901     * @param rotationY The degrees of Y rotation.
12902     *
12903     * @see #getRotationY()
12904     * @see #getPivotX()
12905     * @see #getPivotY()
12906     * @see #setRotation(float)
12907     * @see #setRotationX(float)
12908     * @see #setCameraDistance(float)
12909     *
12910     * @attr ref android.R.styleable#View_rotationY
12911     */
12912    public void setRotationY(float rotationY) {
12913        if (rotationY != getRotationY()) {
12914            invalidateViewProperty(true, false);
12915            mRenderNode.setRotationY(rotationY);
12916            invalidateViewProperty(false, true);
12917
12918            invalidateParentIfNeededAndWasQuickRejected();
12919            notifySubtreeAccessibilityStateChangedIfNeeded();
12920        }
12921    }
12922
12923    /**
12924     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12925     *
12926     * @see #getPivotX()
12927     * @see #getPivotY()
12928     * @see #setRotationX(float)
12929     *
12930     * @return The degrees of X rotation.
12931     */
12932    @ViewDebug.ExportedProperty(category = "drawing")
12933    public float getRotationX() {
12934        return mRenderNode.getRotationX();
12935    }
12936
12937    /**
12938     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12939     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12940     * x axis.
12941     *
12942     * When rotating large views, it is recommended to adjust the camera distance
12943     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12944     *
12945     * @param rotationX The degrees of X rotation.
12946     *
12947     * @see #getRotationX()
12948     * @see #getPivotX()
12949     * @see #getPivotY()
12950     * @see #setRotation(float)
12951     * @see #setRotationY(float)
12952     * @see #setCameraDistance(float)
12953     *
12954     * @attr ref android.R.styleable#View_rotationX
12955     */
12956    public void setRotationX(float rotationX) {
12957        if (rotationX != getRotationX()) {
12958            invalidateViewProperty(true, false);
12959            mRenderNode.setRotationX(rotationX);
12960            invalidateViewProperty(false, true);
12961
12962            invalidateParentIfNeededAndWasQuickRejected();
12963            notifySubtreeAccessibilityStateChangedIfNeeded();
12964        }
12965    }
12966
12967    /**
12968     * The amount that the view is scaled in x around the pivot point, as a proportion of
12969     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12970     *
12971     * <p>By default, this is 1.0f.
12972     *
12973     * @see #getPivotX()
12974     * @see #getPivotY()
12975     * @return The scaling factor.
12976     */
12977    @ViewDebug.ExportedProperty(category = "drawing")
12978    public float getScaleX() {
12979        return mRenderNode.getScaleX();
12980    }
12981
12982    /**
12983     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12984     * the view's unscaled width. A value of 1 means that no scaling is applied.
12985     *
12986     * @param scaleX The scaling factor.
12987     * @see #getPivotX()
12988     * @see #getPivotY()
12989     *
12990     * @attr ref android.R.styleable#View_scaleX
12991     */
12992    public void setScaleX(float scaleX) {
12993        if (scaleX != getScaleX()) {
12994            invalidateViewProperty(true, false);
12995            mRenderNode.setScaleX(scaleX);
12996            invalidateViewProperty(false, true);
12997
12998            invalidateParentIfNeededAndWasQuickRejected();
12999            notifySubtreeAccessibilityStateChangedIfNeeded();
13000        }
13001    }
13002
13003    /**
13004     * The amount that the view is scaled in y around the pivot point, as a proportion of
13005     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
13006     *
13007     * <p>By default, this is 1.0f.
13008     *
13009     * @see #getPivotX()
13010     * @see #getPivotY()
13011     * @return The scaling factor.
13012     */
13013    @ViewDebug.ExportedProperty(category = "drawing")
13014    public float getScaleY() {
13015        return mRenderNode.getScaleY();
13016    }
13017
13018    /**
13019     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
13020     * the view's unscaled width. A value of 1 means that no scaling is applied.
13021     *
13022     * @param scaleY The scaling factor.
13023     * @see #getPivotX()
13024     * @see #getPivotY()
13025     *
13026     * @attr ref android.R.styleable#View_scaleY
13027     */
13028    public void setScaleY(float scaleY) {
13029        if (scaleY != getScaleY()) {
13030            invalidateViewProperty(true, false);
13031            mRenderNode.setScaleY(scaleY);
13032            invalidateViewProperty(false, true);
13033
13034            invalidateParentIfNeededAndWasQuickRejected();
13035            notifySubtreeAccessibilityStateChangedIfNeeded();
13036        }
13037    }
13038
13039    /**
13040     * The x location of the point around which the view is {@link #setRotation(float) rotated}
13041     * and {@link #setScaleX(float) scaled}.
13042     *
13043     * @see #getRotation()
13044     * @see #getScaleX()
13045     * @see #getScaleY()
13046     * @see #getPivotY()
13047     * @return The x location of the pivot point.
13048     *
13049     * @attr ref android.R.styleable#View_transformPivotX
13050     */
13051    @ViewDebug.ExportedProperty(category = "drawing")
13052    public float getPivotX() {
13053        return mRenderNode.getPivotX();
13054    }
13055
13056    /**
13057     * Sets the x location of the point around which the view is
13058     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
13059     * By default, the pivot point is centered on the object.
13060     * Setting this property disables this behavior and causes the view to use only the
13061     * explicitly set pivotX and pivotY values.
13062     *
13063     * @param pivotX The x location of the pivot point.
13064     * @see #getRotation()
13065     * @see #getScaleX()
13066     * @see #getScaleY()
13067     * @see #getPivotY()
13068     *
13069     * @attr ref android.R.styleable#View_transformPivotX
13070     */
13071    public void setPivotX(float pivotX) {
13072        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
13073            invalidateViewProperty(true, false);
13074            mRenderNode.setPivotX(pivotX);
13075            invalidateViewProperty(false, true);
13076
13077            invalidateParentIfNeededAndWasQuickRejected();
13078        }
13079    }
13080
13081    /**
13082     * The y location of the point around which the view is {@link #setRotation(float) rotated}
13083     * and {@link #setScaleY(float) scaled}.
13084     *
13085     * @see #getRotation()
13086     * @see #getScaleX()
13087     * @see #getScaleY()
13088     * @see #getPivotY()
13089     * @return The y location of the pivot point.
13090     *
13091     * @attr ref android.R.styleable#View_transformPivotY
13092     */
13093    @ViewDebug.ExportedProperty(category = "drawing")
13094    public float getPivotY() {
13095        return mRenderNode.getPivotY();
13096    }
13097
13098    /**
13099     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
13100     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
13101     * Setting this property disables this behavior and causes the view to use only the
13102     * explicitly set pivotX and pivotY values.
13103     *
13104     * @param pivotY The y location of the pivot point.
13105     * @see #getRotation()
13106     * @see #getScaleX()
13107     * @see #getScaleY()
13108     * @see #getPivotY()
13109     *
13110     * @attr ref android.R.styleable#View_transformPivotY
13111     */
13112    public void setPivotY(float pivotY) {
13113        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
13114            invalidateViewProperty(true, false);
13115            mRenderNode.setPivotY(pivotY);
13116            invalidateViewProperty(false, true);
13117
13118            invalidateParentIfNeededAndWasQuickRejected();
13119        }
13120    }
13121
13122    /**
13123     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
13124     * completely transparent and 1 means the view is completely opaque.
13125     *
13126     * <p>By default this is 1.0f.
13127     * @return The opacity of the view.
13128     */
13129    @ViewDebug.ExportedProperty(category = "drawing")
13130    public float getAlpha() {
13131        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
13132    }
13133
13134    /**
13135     * Sets the behavior for overlapping rendering for this view (see {@link
13136     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
13137     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
13138     * providing the value which is then used internally. That is, when {@link
13139     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
13140     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
13141     * instead.
13142     *
13143     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
13144     * instead of that returned by {@link #hasOverlappingRendering()}.
13145     *
13146     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
13147     */
13148    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
13149        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
13150        if (hasOverlappingRendering) {
13151            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13152        } else {
13153            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13154        }
13155    }
13156
13157    /**
13158     * Returns the value for overlapping rendering that is used internally. This is either
13159     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
13160     * the return value of {@link #hasOverlappingRendering()}, otherwise.
13161     *
13162     * @return The value for overlapping rendering being used internally.
13163     */
13164    public final boolean getHasOverlappingRendering() {
13165        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
13166                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
13167                hasOverlappingRendering();
13168    }
13169
13170    /**
13171     * Returns whether this View has content which overlaps.
13172     *
13173     * <p>This function, intended to be overridden by specific View types, is an optimization when
13174     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
13175     * an offscreen buffer and then composited into place, which can be expensive. If the view has
13176     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
13177     * directly. An example of overlapping rendering is a TextView with a background image, such as
13178     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
13179     * ImageView with only the foreground image. The default implementation returns true; subclasses
13180     * should override if they have cases which can be optimized.</p>
13181     *
13182     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
13183     * necessitates that a View return true if it uses the methods internally without passing the
13184     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
13185     *
13186     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
13187     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
13188     *
13189     * @return true if the content in this view might overlap, false otherwise.
13190     */
13191    @ViewDebug.ExportedProperty(category = "drawing")
13192    public boolean hasOverlappingRendering() {
13193        return true;
13194    }
13195
13196    /**
13197     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
13198     * completely transparent and 1 means the view is completely opaque.
13199     *
13200     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
13201     * can have significant performance implications, especially for large views. It is best to use
13202     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
13203     *
13204     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
13205     * strongly recommended for performance reasons to either override
13206     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
13207     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
13208     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
13209     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
13210     * of rendering cost, even for simple or small views. Starting with
13211     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
13212     * applied to the view at the rendering level.</p>
13213     *
13214     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
13215     * responsible for applying the opacity itself.</p>
13216     *
13217     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
13218     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
13219     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
13220     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
13221     *
13222     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
13223     * value will clip a View to its bounds, unless the View returns <code>false</code> from
13224     * {@link #hasOverlappingRendering}.</p>
13225     *
13226     * @param alpha The opacity of the view.
13227     *
13228     * @see #hasOverlappingRendering()
13229     * @see #setLayerType(int, android.graphics.Paint)
13230     *
13231     * @attr ref android.R.styleable#View_alpha
13232     */
13233    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
13234        ensureTransformationInfo();
13235        if (mTransformationInfo.mAlpha != alpha) {
13236            // Report visibility changes, which can affect children, to accessibility
13237            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
13238                notifySubtreeAccessibilityStateChangedIfNeeded();
13239            }
13240            mTransformationInfo.mAlpha = alpha;
13241            if (onSetAlpha((int) (alpha * 255))) {
13242                mPrivateFlags |= PFLAG_ALPHA_SET;
13243                // subclass is handling alpha - don't optimize rendering cache invalidation
13244                invalidateParentCaches();
13245                invalidate(true);
13246            } else {
13247                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13248                invalidateViewProperty(true, false);
13249                mRenderNode.setAlpha(getFinalAlpha());
13250            }
13251        }
13252    }
13253
13254    /**
13255     * Faster version of setAlpha() which performs the same steps except there are
13256     * no calls to invalidate(). The caller of this function should perform proper invalidation
13257     * on the parent and this object. The return value indicates whether the subclass handles
13258     * alpha (the return value for onSetAlpha()).
13259     *
13260     * @param alpha The new value for the alpha property
13261     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
13262     *         the new value for the alpha property is different from the old value
13263     */
13264    boolean setAlphaNoInvalidation(float alpha) {
13265        ensureTransformationInfo();
13266        if (mTransformationInfo.mAlpha != alpha) {
13267            mTransformationInfo.mAlpha = alpha;
13268            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
13269            if (subclassHandlesAlpha) {
13270                mPrivateFlags |= PFLAG_ALPHA_SET;
13271                return true;
13272            } else {
13273                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13274                mRenderNode.setAlpha(getFinalAlpha());
13275            }
13276        }
13277        return false;
13278    }
13279
13280    /**
13281     * This property is hidden and intended only for use by the Fade transition, which
13282     * animates it to produce a visual translucency that does not side-effect (or get
13283     * affected by) the real alpha property. This value is composited with the other
13284     * alpha value (and the AlphaAnimation value, when that is present) to produce
13285     * a final visual translucency result, which is what is passed into the DisplayList.
13286     *
13287     * @hide
13288     */
13289    public void setTransitionAlpha(float alpha) {
13290        ensureTransformationInfo();
13291        if (mTransformationInfo.mTransitionAlpha != alpha) {
13292            mTransformationInfo.mTransitionAlpha = alpha;
13293            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13294            invalidateViewProperty(true, false);
13295            mRenderNode.setAlpha(getFinalAlpha());
13296        }
13297    }
13298
13299    /**
13300     * Calculates the visual alpha of this view, which is a combination of the actual
13301     * alpha value and the transitionAlpha value (if set).
13302     */
13303    private float getFinalAlpha() {
13304        if (mTransformationInfo != null) {
13305            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
13306        }
13307        return 1;
13308    }
13309
13310    /**
13311     * This property is hidden and intended only for use by the Fade transition, which
13312     * animates it to produce a visual translucency that does not side-effect (or get
13313     * affected by) the real alpha property. This value is composited with the other
13314     * alpha value (and the AlphaAnimation value, when that is present) to produce
13315     * a final visual translucency result, which is what is passed into the DisplayList.
13316     *
13317     * @hide
13318     */
13319    @ViewDebug.ExportedProperty(category = "drawing")
13320    public float getTransitionAlpha() {
13321        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
13322    }
13323
13324    /**
13325     * Top position of this view relative to its parent.
13326     *
13327     * @return The top of this view, in pixels.
13328     */
13329    @ViewDebug.CapturedViewProperty
13330    public final int getTop() {
13331        return mTop;
13332    }
13333
13334    /**
13335     * Sets the top position of this view relative to its parent. This method is meant to be called
13336     * by the layout system and should not generally be called otherwise, because the property
13337     * may be changed at any time by the layout.
13338     *
13339     * @param top The top of this view, in pixels.
13340     */
13341    public final void setTop(int top) {
13342        if (top != mTop) {
13343            final boolean matrixIsIdentity = hasIdentityMatrix();
13344            if (matrixIsIdentity) {
13345                if (mAttachInfo != null) {
13346                    int minTop;
13347                    int yLoc;
13348                    if (top < mTop) {
13349                        minTop = top;
13350                        yLoc = top - mTop;
13351                    } else {
13352                        minTop = mTop;
13353                        yLoc = 0;
13354                    }
13355                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
13356                }
13357            } else {
13358                // Double-invalidation is necessary to capture view's old and new areas
13359                invalidate(true);
13360            }
13361
13362            int width = mRight - mLeft;
13363            int oldHeight = mBottom - mTop;
13364
13365            mTop = top;
13366            mRenderNode.setTop(mTop);
13367
13368            sizeChange(width, mBottom - mTop, width, oldHeight);
13369
13370            if (!matrixIsIdentity) {
13371                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13372                invalidate(true);
13373            }
13374            mBackgroundSizeChanged = true;
13375            if (mForegroundInfo != null) {
13376                mForegroundInfo.mBoundsChanged = true;
13377            }
13378            invalidateParentIfNeeded();
13379            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13380                // View was rejected last time it was drawn by its parent; this may have changed
13381                invalidateParentIfNeeded();
13382            }
13383        }
13384    }
13385
13386    /**
13387     * Bottom position of this view relative to its parent.
13388     *
13389     * @return The bottom of this view, in pixels.
13390     */
13391    @ViewDebug.CapturedViewProperty
13392    public final int getBottom() {
13393        return mBottom;
13394    }
13395
13396    /**
13397     * True if this view has changed since the last time being drawn.
13398     *
13399     * @return The dirty state of this view.
13400     */
13401    public boolean isDirty() {
13402        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
13403    }
13404
13405    /**
13406     * Sets the bottom position of this view relative to its parent. This method is meant to be
13407     * called by the layout system and should not generally be called otherwise, because the
13408     * property may be changed at any time by the layout.
13409     *
13410     * @param bottom The bottom of this view, in pixels.
13411     */
13412    public final void setBottom(int bottom) {
13413        if (bottom != mBottom) {
13414            final boolean matrixIsIdentity = hasIdentityMatrix();
13415            if (matrixIsIdentity) {
13416                if (mAttachInfo != null) {
13417                    int maxBottom;
13418                    if (bottom < mBottom) {
13419                        maxBottom = mBottom;
13420                    } else {
13421                        maxBottom = bottom;
13422                    }
13423                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
13424                }
13425            } else {
13426                // Double-invalidation is necessary to capture view's old and new areas
13427                invalidate(true);
13428            }
13429
13430            int width = mRight - mLeft;
13431            int oldHeight = mBottom - mTop;
13432
13433            mBottom = bottom;
13434            mRenderNode.setBottom(mBottom);
13435
13436            sizeChange(width, mBottom - mTop, width, oldHeight);
13437
13438            if (!matrixIsIdentity) {
13439                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13440                invalidate(true);
13441            }
13442            mBackgroundSizeChanged = true;
13443            if (mForegroundInfo != null) {
13444                mForegroundInfo.mBoundsChanged = true;
13445            }
13446            invalidateParentIfNeeded();
13447            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13448                // View was rejected last time it was drawn by its parent; this may have changed
13449                invalidateParentIfNeeded();
13450            }
13451        }
13452    }
13453
13454    /**
13455     * Left position of this view relative to its parent.
13456     *
13457     * @return The left edge of this view, in pixels.
13458     */
13459    @ViewDebug.CapturedViewProperty
13460    public final int getLeft() {
13461        return mLeft;
13462    }
13463
13464    /**
13465     * Sets the left position of this view relative to its parent. This method is meant to be called
13466     * by the layout system and should not generally be called otherwise, because the property
13467     * may be changed at any time by the layout.
13468     *
13469     * @param left The left of this view, in pixels.
13470     */
13471    public final void setLeft(int left) {
13472        if (left != mLeft) {
13473            final boolean matrixIsIdentity = hasIdentityMatrix();
13474            if (matrixIsIdentity) {
13475                if (mAttachInfo != null) {
13476                    int minLeft;
13477                    int xLoc;
13478                    if (left < mLeft) {
13479                        minLeft = left;
13480                        xLoc = left - mLeft;
13481                    } else {
13482                        minLeft = mLeft;
13483                        xLoc = 0;
13484                    }
13485                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
13486                }
13487            } else {
13488                // Double-invalidation is necessary to capture view's old and new areas
13489                invalidate(true);
13490            }
13491
13492            int oldWidth = mRight - mLeft;
13493            int height = mBottom - mTop;
13494
13495            mLeft = left;
13496            mRenderNode.setLeft(left);
13497
13498            sizeChange(mRight - mLeft, height, oldWidth, height);
13499
13500            if (!matrixIsIdentity) {
13501                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13502                invalidate(true);
13503            }
13504            mBackgroundSizeChanged = true;
13505            if (mForegroundInfo != null) {
13506                mForegroundInfo.mBoundsChanged = true;
13507            }
13508            invalidateParentIfNeeded();
13509            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13510                // View was rejected last time it was drawn by its parent; this may have changed
13511                invalidateParentIfNeeded();
13512            }
13513        }
13514    }
13515
13516    /**
13517     * Right position of this view relative to its parent.
13518     *
13519     * @return The right edge of this view, in pixels.
13520     */
13521    @ViewDebug.CapturedViewProperty
13522    public final int getRight() {
13523        return mRight;
13524    }
13525
13526    /**
13527     * Sets the right position of this view relative to its parent. This method is meant to be called
13528     * by the layout system and should not generally be called otherwise, because the property
13529     * may be changed at any time by the layout.
13530     *
13531     * @param right The right of this view, in pixels.
13532     */
13533    public final void setRight(int right) {
13534        if (right != mRight) {
13535            final boolean matrixIsIdentity = hasIdentityMatrix();
13536            if (matrixIsIdentity) {
13537                if (mAttachInfo != null) {
13538                    int maxRight;
13539                    if (right < mRight) {
13540                        maxRight = mRight;
13541                    } else {
13542                        maxRight = right;
13543                    }
13544                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
13545                }
13546            } else {
13547                // Double-invalidation is necessary to capture view's old and new areas
13548                invalidate(true);
13549            }
13550
13551            int oldWidth = mRight - mLeft;
13552            int height = mBottom - mTop;
13553
13554            mRight = right;
13555            mRenderNode.setRight(mRight);
13556
13557            sizeChange(mRight - mLeft, height, oldWidth, height);
13558
13559            if (!matrixIsIdentity) {
13560                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13561                invalidate(true);
13562            }
13563            mBackgroundSizeChanged = true;
13564            if (mForegroundInfo != null) {
13565                mForegroundInfo.mBoundsChanged = true;
13566            }
13567            invalidateParentIfNeeded();
13568            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13569                // View was rejected last time it was drawn by its parent; this may have changed
13570                invalidateParentIfNeeded();
13571            }
13572        }
13573    }
13574
13575    /**
13576     * The visual x position of this view, in pixels. This is equivalent to the
13577     * {@link #setTranslationX(float) translationX} property plus the current
13578     * {@link #getLeft() left} property.
13579     *
13580     * @return The visual x position of this view, in pixels.
13581     */
13582    @ViewDebug.ExportedProperty(category = "drawing")
13583    public float getX() {
13584        return mLeft + getTranslationX();
13585    }
13586
13587    /**
13588     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
13589     * {@link #setTranslationX(float) translationX} property to be the difference between
13590     * the x value passed in and the current {@link #getLeft() left} property.
13591     *
13592     * @param x The visual x position of this view, in pixels.
13593     */
13594    public void setX(float x) {
13595        setTranslationX(x - mLeft);
13596    }
13597
13598    /**
13599     * The visual y position of this view, in pixels. This is equivalent to the
13600     * {@link #setTranslationY(float) translationY} property plus the current
13601     * {@link #getTop() top} property.
13602     *
13603     * @return The visual y position of this view, in pixels.
13604     */
13605    @ViewDebug.ExportedProperty(category = "drawing")
13606    public float getY() {
13607        return mTop + getTranslationY();
13608    }
13609
13610    /**
13611     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
13612     * {@link #setTranslationY(float) translationY} property to be the difference between
13613     * the y value passed in and the current {@link #getTop() top} property.
13614     *
13615     * @param y The visual y position of this view, in pixels.
13616     */
13617    public void setY(float y) {
13618        setTranslationY(y - mTop);
13619    }
13620
13621    /**
13622     * The visual z position of this view, in pixels. This is equivalent to the
13623     * {@link #setTranslationZ(float) translationZ} property plus the current
13624     * {@link #getElevation() elevation} property.
13625     *
13626     * @return The visual z position of this view, in pixels.
13627     */
13628    @ViewDebug.ExportedProperty(category = "drawing")
13629    public float getZ() {
13630        return getElevation() + getTranslationZ();
13631    }
13632
13633    /**
13634     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
13635     * {@link #setTranslationZ(float) translationZ} property to be the difference between
13636     * the x value passed in and the current {@link #getElevation() elevation} property.
13637     *
13638     * @param z The visual z position of this view, in pixels.
13639     */
13640    public void setZ(float z) {
13641        setTranslationZ(z - getElevation());
13642    }
13643
13644    /**
13645     * The base elevation of this view relative to its parent, in pixels.
13646     *
13647     * @return The base depth position of the view, in pixels.
13648     */
13649    @ViewDebug.ExportedProperty(category = "drawing")
13650    public float getElevation() {
13651        return mRenderNode.getElevation();
13652    }
13653
13654    /**
13655     * Sets the base elevation of this view, in pixels.
13656     *
13657     * @attr ref android.R.styleable#View_elevation
13658     */
13659    public void setElevation(float elevation) {
13660        if (elevation != getElevation()) {
13661            invalidateViewProperty(true, false);
13662            mRenderNode.setElevation(elevation);
13663            invalidateViewProperty(false, true);
13664
13665            invalidateParentIfNeededAndWasQuickRejected();
13666        }
13667    }
13668
13669    /**
13670     * The horizontal location of this view relative to its {@link #getLeft() left} position.
13671     * This position is post-layout, in addition to wherever the object's
13672     * layout placed it.
13673     *
13674     * @return The horizontal position of this view relative to its left position, in pixels.
13675     */
13676    @ViewDebug.ExportedProperty(category = "drawing")
13677    public float getTranslationX() {
13678        return mRenderNode.getTranslationX();
13679    }
13680
13681    /**
13682     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
13683     * This effectively positions the object post-layout, in addition to wherever the object's
13684     * layout placed it.
13685     *
13686     * @param translationX The horizontal position of this view relative to its left position,
13687     * in pixels.
13688     *
13689     * @attr ref android.R.styleable#View_translationX
13690     */
13691    public void setTranslationX(float translationX) {
13692        if (translationX != getTranslationX()) {
13693            invalidateViewProperty(true, false);
13694            mRenderNode.setTranslationX(translationX);
13695            invalidateViewProperty(false, true);
13696
13697            invalidateParentIfNeededAndWasQuickRejected();
13698            notifySubtreeAccessibilityStateChangedIfNeeded();
13699        }
13700    }
13701
13702    /**
13703     * The vertical location of this view relative to its {@link #getTop() top} position.
13704     * This position is post-layout, in addition to wherever the object's
13705     * layout placed it.
13706     *
13707     * @return The vertical position of this view relative to its top position,
13708     * in pixels.
13709     */
13710    @ViewDebug.ExportedProperty(category = "drawing")
13711    public float getTranslationY() {
13712        return mRenderNode.getTranslationY();
13713    }
13714
13715    /**
13716     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
13717     * This effectively positions the object post-layout, in addition to wherever the object's
13718     * layout placed it.
13719     *
13720     * @param translationY The vertical position of this view relative to its top position,
13721     * in pixels.
13722     *
13723     * @attr ref android.R.styleable#View_translationY
13724     */
13725    public void setTranslationY(float translationY) {
13726        if (translationY != getTranslationY()) {
13727            invalidateViewProperty(true, false);
13728            mRenderNode.setTranslationY(translationY);
13729            invalidateViewProperty(false, true);
13730
13731            invalidateParentIfNeededAndWasQuickRejected();
13732            notifySubtreeAccessibilityStateChangedIfNeeded();
13733        }
13734    }
13735
13736    /**
13737     * The depth location of this view relative to its {@link #getElevation() elevation}.
13738     *
13739     * @return The depth of this view relative to its elevation.
13740     */
13741    @ViewDebug.ExportedProperty(category = "drawing")
13742    public float getTranslationZ() {
13743        return mRenderNode.getTranslationZ();
13744    }
13745
13746    /**
13747     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
13748     *
13749     * @attr ref android.R.styleable#View_translationZ
13750     */
13751    public void setTranslationZ(float translationZ) {
13752        if (translationZ != getTranslationZ()) {
13753            invalidateViewProperty(true, false);
13754            mRenderNode.setTranslationZ(translationZ);
13755            invalidateViewProperty(false, true);
13756
13757            invalidateParentIfNeededAndWasQuickRejected();
13758        }
13759    }
13760
13761    /** @hide */
13762    public void setAnimationMatrix(Matrix matrix) {
13763        invalidateViewProperty(true, false);
13764        mRenderNode.setAnimationMatrix(matrix);
13765        invalidateViewProperty(false, true);
13766
13767        invalidateParentIfNeededAndWasQuickRejected();
13768    }
13769
13770    /**
13771     * Returns the current StateListAnimator if exists.
13772     *
13773     * @return StateListAnimator or null if it does not exists
13774     * @see    #setStateListAnimator(android.animation.StateListAnimator)
13775     */
13776    public StateListAnimator getStateListAnimator() {
13777        return mStateListAnimator;
13778    }
13779
13780    /**
13781     * Attaches the provided StateListAnimator to this View.
13782     * <p>
13783     * Any previously attached StateListAnimator will be detached.
13784     *
13785     * @param stateListAnimator The StateListAnimator to update the view
13786     * @see android.animation.StateListAnimator
13787     */
13788    public void setStateListAnimator(StateListAnimator stateListAnimator) {
13789        if (mStateListAnimator == stateListAnimator) {
13790            return;
13791        }
13792        if (mStateListAnimator != null) {
13793            mStateListAnimator.setTarget(null);
13794        }
13795        mStateListAnimator = stateListAnimator;
13796        if (stateListAnimator != null) {
13797            stateListAnimator.setTarget(this);
13798            if (isAttachedToWindow()) {
13799                stateListAnimator.setState(getDrawableState());
13800            }
13801        }
13802    }
13803
13804    /**
13805     * Returns whether the Outline should be used to clip the contents of the View.
13806     * <p>
13807     * Note that this flag will only be respected if the View's Outline returns true from
13808     * {@link Outline#canClip()}.
13809     *
13810     * @see #setOutlineProvider(ViewOutlineProvider)
13811     * @see #setClipToOutline(boolean)
13812     */
13813    public final boolean getClipToOutline() {
13814        return mRenderNode.getClipToOutline();
13815    }
13816
13817    /**
13818     * Sets whether the View's Outline should be used to clip the contents of the View.
13819     * <p>
13820     * Only a single non-rectangular clip can be applied on a View at any time.
13821     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
13822     * circular reveal} animation take priority over Outline clipping, and
13823     * child Outline clipping takes priority over Outline clipping done by a
13824     * parent.
13825     * <p>
13826     * Note that this flag will only be respected if the View's Outline returns true from
13827     * {@link Outline#canClip()}.
13828     *
13829     * @see #setOutlineProvider(ViewOutlineProvider)
13830     * @see #getClipToOutline()
13831     */
13832    public void setClipToOutline(boolean clipToOutline) {
13833        damageInParent();
13834        if (getClipToOutline() != clipToOutline) {
13835            mRenderNode.setClipToOutline(clipToOutline);
13836        }
13837    }
13838
13839    // correspond to the enum values of View_outlineProvider
13840    private static final int PROVIDER_BACKGROUND = 0;
13841    private static final int PROVIDER_NONE = 1;
13842    private static final int PROVIDER_BOUNDS = 2;
13843    private static final int PROVIDER_PADDED_BOUNDS = 3;
13844    private void setOutlineProviderFromAttribute(int providerInt) {
13845        switch (providerInt) {
13846            case PROVIDER_BACKGROUND:
13847                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
13848                break;
13849            case PROVIDER_NONE:
13850                setOutlineProvider(null);
13851                break;
13852            case PROVIDER_BOUNDS:
13853                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13854                break;
13855            case PROVIDER_PADDED_BOUNDS:
13856                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13857                break;
13858        }
13859    }
13860
13861    /**
13862     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13863     * the shape of the shadow it casts, and enables outline clipping.
13864     * <p>
13865     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13866     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13867     * outline provider with this method allows this behavior to be overridden.
13868     * <p>
13869     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13870     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13871     * <p>
13872     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13873     *
13874     * @see #setClipToOutline(boolean)
13875     * @see #getClipToOutline()
13876     * @see #getOutlineProvider()
13877     */
13878    public void setOutlineProvider(ViewOutlineProvider provider) {
13879        mOutlineProvider = provider;
13880        invalidateOutline();
13881    }
13882
13883    /**
13884     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13885     * that defines the shape of the shadow it casts, and enables outline clipping.
13886     *
13887     * @see #setOutlineProvider(ViewOutlineProvider)
13888     */
13889    public ViewOutlineProvider getOutlineProvider() {
13890        return mOutlineProvider;
13891    }
13892
13893    /**
13894     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13895     *
13896     * @see #setOutlineProvider(ViewOutlineProvider)
13897     */
13898    public void invalidateOutline() {
13899        rebuildOutline();
13900
13901        notifySubtreeAccessibilityStateChangedIfNeeded();
13902        invalidateViewProperty(false, false);
13903    }
13904
13905    /**
13906     * Internal version of {@link #invalidateOutline()} which invalidates the
13907     * outline without invalidating the view itself. This is intended to be called from
13908     * within methods in the View class itself which are the result of the view being
13909     * invalidated already. For example, when we are drawing the background of a View,
13910     * we invalidate the outline in case it changed in the meantime, but we do not
13911     * need to invalidate the view because we're already drawing the background as part
13912     * of drawing the view in response to an earlier invalidation of the view.
13913     */
13914    private void rebuildOutline() {
13915        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13916        if (mAttachInfo == null) return;
13917
13918        if (mOutlineProvider == null) {
13919            // no provider, remove outline
13920            mRenderNode.setOutline(null);
13921        } else {
13922            final Outline outline = mAttachInfo.mTmpOutline;
13923            outline.setEmpty();
13924            outline.setAlpha(1.0f);
13925
13926            mOutlineProvider.getOutline(this, outline);
13927            mRenderNode.setOutline(outline);
13928        }
13929    }
13930
13931    /**
13932     * HierarchyViewer only
13933     *
13934     * @hide
13935     */
13936    @ViewDebug.ExportedProperty(category = "drawing")
13937    public boolean hasShadow() {
13938        return mRenderNode.hasShadow();
13939    }
13940
13941
13942    /** @hide */
13943    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13944        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13945        invalidateViewProperty(false, false);
13946    }
13947
13948    /**
13949     * Hit rectangle in parent's coordinates
13950     *
13951     * @param outRect The hit rectangle of the view.
13952     */
13953    public void getHitRect(Rect outRect) {
13954        if (hasIdentityMatrix() || mAttachInfo == null) {
13955            outRect.set(mLeft, mTop, mRight, mBottom);
13956        } else {
13957            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13958            tmpRect.set(0, 0, getWidth(), getHeight());
13959            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13960            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13961                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13962        }
13963    }
13964
13965    /**
13966     * Determines whether the given point, in local coordinates is inside the view.
13967     */
13968    /*package*/ final boolean pointInView(float localX, float localY) {
13969        return pointInView(localX, localY, 0);
13970    }
13971
13972    /**
13973     * Utility method to determine whether the given point, in local coordinates,
13974     * is inside the view, where the area of the view is expanded by the slop factor.
13975     * This method is called while processing touch-move events to determine if the event
13976     * is still within the view.
13977     *
13978     * @hide
13979     */
13980    public boolean pointInView(float localX, float localY, float slop) {
13981        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13982                localY < ((mBottom - mTop) + slop);
13983    }
13984
13985    /**
13986     * When a view has focus and the user navigates away from it, the next view is searched for
13987     * starting from the rectangle filled in by this method.
13988     *
13989     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13990     * of the view.  However, if your view maintains some idea of internal selection,
13991     * such as a cursor, or a selected row or column, you should override this method and
13992     * fill in a more specific rectangle.
13993     *
13994     * @param r The rectangle to fill in, in this view's coordinates.
13995     */
13996    public void getFocusedRect(Rect r) {
13997        getDrawingRect(r);
13998    }
13999
14000    /**
14001     * If some part of this view is not clipped by any of its parents, then
14002     * return that area in r in global (root) coordinates. To convert r to local
14003     * coordinates (without taking possible View rotations into account), offset
14004     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
14005     * If the view is completely clipped or translated out, return false.
14006     *
14007     * @param r If true is returned, r holds the global coordinates of the
14008     *        visible portion of this view.
14009     * @param globalOffset If true is returned, globalOffset holds the dx,dy
14010     *        between this view and its root. globalOffet may be null.
14011     * @return true if r is non-empty (i.e. part of the view is visible at the
14012     *         root level.
14013     */
14014    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
14015        int width = mRight - mLeft;
14016        int height = mBottom - mTop;
14017        if (width > 0 && height > 0) {
14018            r.set(0, 0, width, height);
14019            if (globalOffset != null) {
14020                globalOffset.set(-mScrollX, -mScrollY);
14021            }
14022            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
14023        }
14024        return false;
14025    }
14026
14027    public final boolean getGlobalVisibleRect(Rect r) {
14028        return getGlobalVisibleRect(r, null);
14029    }
14030
14031    public final boolean getLocalVisibleRect(Rect r) {
14032        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
14033        if (getGlobalVisibleRect(r, offset)) {
14034            r.offset(-offset.x, -offset.y); // make r local
14035            return true;
14036        }
14037        return false;
14038    }
14039
14040    /**
14041     * Offset this view's vertical location by the specified number of pixels.
14042     *
14043     * @param offset the number of pixels to offset the view by
14044     */
14045    public void offsetTopAndBottom(int offset) {
14046        if (offset != 0) {
14047            final boolean matrixIsIdentity = hasIdentityMatrix();
14048            if (matrixIsIdentity) {
14049                if (isHardwareAccelerated()) {
14050                    invalidateViewProperty(false, false);
14051                } else {
14052                    final ViewParent p = mParent;
14053                    if (p != null && mAttachInfo != null) {
14054                        final Rect r = mAttachInfo.mTmpInvalRect;
14055                        int minTop;
14056                        int maxBottom;
14057                        int yLoc;
14058                        if (offset < 0) {
14059                            minTop = mTop + offset;
14060                            maxBottom = mBottom;
14061                            yLoc = offset;
14062                        } else {
14063                            minTop = mTop;
14064                            maxBottom = mBottom + offset;
14065                            yLoc = 0;
14066                        }
14067                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
14068                        p.invalidateChild(this, r);
14069                    }
14070                }
14071            } else {
14072                invalidateViewProperty(false, false);
14073            }
14074
14075            mTop += offset;
14076            mBottom += offset;
14077            mRenderNode.offsetTopAndBottom(offset);
14078            if (isHardwareAccelerated()) {
14079                invalidateViewProperty(false, false);
14080                invalidateParentIfNeededAndWasQuickRejected();
14081            } else {
14082                if (!matrixIsIdentity) {
14083                    invalidateViewProperty(false, true);
14084                }
14085                invalidateParentIfNeeded();
14086            }
14087            notifySubtreeAccessibilityStateChangedIfNeeded();
14088        }
14089    }
14090
14091    /**
14092     * Offset this view's horizontal location by the specified amount of pixels.
14093     *
14094     * @param offset the number of pixels to offset the view by
14095     */
14096    public void offsetLeftAndRight(int offset) {
14097        if (offset != 0) {
14098            final boolean matrixIsIdentity = hasIdentityMatrix();
14099            if (matrixIsIdentity) {
14100                if (isHardwareAccelerated()) {
14101                    invalidateViewProperty(false, false);
14102                } else {
14103                    final ViewParent p = mParent;
14104                    if (p != null && mAttachInfo != null) {
14105                        final Rect r = mAttachInfo.mTmpInvalRect;
14106                        int minLeft;
14107                        int maxRight;
14108                        if (offset < 0) {
14109                            minLeft = mLeft + offset;
14110                            maxRight = mRight;
14111                        } else {
14112                            minLeft = mLeft;
14113                            maxRight = mRight + offset;
14114                        }
14115                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
14116                        p.invalidateChild(this, r);
14117                    }
14118                }
14119            } else {
14120                invalidateViewProperty(false, false);
14121            }
14122
14123            mLeft += offset;
14124            mRight += offset;
14125            mRenderNode.offsetLeftAndRight(offset);
14126            if (isHardwareAccelerated()) {
14127                invalidateViewProperty(false, false);
14128                invalidateParentIfNeededAndWasQuickRejected();
14129            } else {
14130                if (!matrixIsIdentity) {
14131                    invalidateViewProperty(false, true);
14132                }
14133                invalidateParentIfNeeded();
14134            }
14135            notifySubtreeAccessibilityStateChangedIfNeeded();
14136        }
14137    }
14138
14139    /**
14140     * Get the LayoutParams associated with this view. All views should have
14141     * layout parameters. These supply parameters to the <i>parent</i> of this
14142     * view specifying how it should be arranged. There are many subclasses of
14143     * ViewGroup.LayoutParams, and these correspond to the different subclasses
14144     * of ViewGroup that are responsible for arranging their children.
14145     *
14146     * This method may return null if this View is not attached to a parent
14147     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
14148     * was not invoked successfully. When a View is attached to a parent
14149     * ViewGroup, this method must not return null.
14150     *
14151     * @return The LayoutParams associated with this view, or null if no
14152     *         parameters have been set yet
14153     */
14154    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
14155    public ViewGroup.LayoutParams getLayoutParams() {
14156        return mLayoutParams;
14157    }
14158
14159    /**
14160     * Set the layout parameters associated with this view. These supply
14161     * parameters to the <i>parent</i> of this view specifying how it should be
14162     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
14163     * correspond to the different subclasses of ViewGroup that are responsible
14164     * for arranging their children.
14165     *
14166     * @param params The layout parameters for this view, cannot be null
14167     */
14168    public void setLayoutParams(ViewGroup.LayoutParams params) {
14169        if (params == null) {
14170            throw new NullPointerException("Layout parameters cannot be null");
14171        }
14172        mLayoutParams = params;
14173        resolveLayoutParams();
14174        if (mParent instanceof ViewGroup) {
14175            ((ViewGroup) mParent).onSetLayoutParams(this, params);
14176        }
14177        requestLayout();
14178    }
14179
14180    /**
14181     * Resolve the layout parameters depending on the resolved layout direction
14182     *
14183     * @hide
14184     */
14185    public void resolveLayoutParams() {
14186        if (mLayoutParams != null) {
14187            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
14188        }
14189    }
14190
14191    /**
14192     * Set the scrolled position of your view. This will cause a call to
14193     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14194     * invalidated.
14195     * @param x the x position to scroll to
14196     * @param y the y position to scroll to
14197     */
14198    public void scrollTo(int x, int y) {
14199        if (mScrollX != x || mScrollY != y) {
14200            int oldX = mScrollX;
14201            int oldY = mScrollY;
14202            mScrollX = x;
14203            mScrollY = y;
14204            invalidateParentCaches();
14205            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
14206            if (!awakenScrollBars()) {
14207                postInvalidateOnAnimation();
14208            }
14209        }
14210    }
14211
14212    /**
14213     * Move the scrolled position of your view. This will cause a call to
14214     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14215     * invalidated.
14216     * @param x the amount of pixels to scroll by horizontally
14217     * @param y the amount of pixels to scroll by vertically
14218     */
14219    public void scrollBy(int x, int y) {
14220        scrollTo(mScrollX + x, mScrollY + y);
14221    }
14222
14223    /**
14224     * <p>Trigger the scrollbars to draw. When invoked this method starts an
14225     * animation to fade the scrollbars out after a default delay. If a subclass
14226     * provides animated scrolling, the start delay should equal the duration
14227     * of the scrolling animation.</p>
14228     *
14229     * <p>The animation starts only if at least one of the scrollbars is
14230     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
14231     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14232     * this method returns true, and false otherwise. If the animation is
14233     * started, this method calls {@link #invalidate()}; in that case the
14234     * caller should not call {@link #invalidate()}.</p>
14235     *
14236     * <p>This method should be invoked every time a subclass directly updates
14237     * the scroll parameters.</p>
14238     *
14239     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
14240     * and {@link #scrollTo(int, int)}.</p>
14241     *
14242     * @return true if the animation is played, false otherwise
14243     *
14244     * @see #awakenScrollBars(int)
14245     * @see #scrollBy(int, int)
14246     * @see #scrollTo(int, int)
14247     * @see #isHorizontalScrollBarEnabled()
14248     * @see #isVerticalScrollBarEnabled()
14249     * @see #setHorizontalScrollBarEnabled(boolean)
14250     * @see #setVerticalScrollBarEnabled(boolean)
14251     */
14252    protected boolean awakenScrollBars() {
14253        return mScrollCache != null &&
14254                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
14255    }
14256
14257    /**
14258     * Trigger the scrollbars to draw.
14259     * This method differs from awakenScrollBars() only in its default duration.
14260     * initialAwakenScrollBars() will show the scroll bars for longer than
14261     * usual to give the user more of a chance to notice them.
14262     *
14263     * @return true if the animation is played, false otherwise.
14264     */
14265    private boolean initialAwakenScrollBars() {
14266        return mScrollCache != null &&
14267                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
14268    }
14269
14270    /**
14271     * <p>
14272     * Trigger the scrollbars to draw. When invoked this method starts an
14273     * animation to fade the scrollbars out after a fixed delay. If a subclass
14274     * provides animated scrolling, the start delay should equal the duration of
14275     * the scrolling animation.
14276     * </p>
14277     *
14278     * <p>
14279     * The animation starts only if at least one of the scrollbars is enabled,
14280     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14281     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14282     * this method returns true, and false otherwise. If the animation is
14283     * started, this method calls {@link #invalidate()}; in that case the caller
14284     * should not call {@link #invalidate()}.
14285     * </p>
14286     *
14287     * <p>
14288     * This method should be invoked every time a subclass directly updates the
14289     * scroll parameters.
14290     * </p>
14291     *
14292     * @param startDelay the delay, in milliseconds, after which the animation
14293     *        should start; when the delay is 0, the animation starts
14294     *        immediately
14295     * @return true if the animation is played, false otherwise
14296     *
14297     * @see #scrollBy(int, int)
14298     * @see #scrollTo(int, int)
14299     * @see #isHorizontalScrollBarEnabled()
14300     * @see #isVerticalScrollBarEnabled()
14301     * @see #setHorizontalScrollBarEnabled(boolean)
14302     * @see #setVerticalScrollBarEnabled(boolean)
14303     */
14304    protected boolean awakenScrollBars(int startDelay) {
14305        return awakenScrollBars(startDelay, true);
14306    }
14307
14308    /**
14309     * <p>
14310     * Trigger the scrollbars to draw. When invoked this method starts an
14311     * animation to fade the scrollbars out after a fixed delay. If a subclass
14312     * provides animated scrolling, the start delay should equal the duration of
14313     * the scrolling animation.
14314     * </p>
14315     *
14316     * <p>
14317     * The animation starts only if at least one of the scrollbars is enabled,
14318     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14319     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14320     * this method returns true, and false otherwise. If the animation is
14321     * started, this method calls {@link #invalidate()} if the invalidate parameter
14322     * is set to true; in that case the caller
14323     * should not call {@link #invalidate()}.
14324     * </p>
14325     *
14326     * <p>
14327     * This method should be invoked every time a subclass directly updates the
14328     * scroll parameters.
14329     * </p>
14330     *
14331     * @param startDelay the delay, in milliseconds, after which the animation
14332     *        should start; when the delay is 0, the animation starts
14333     *        immediately
14334     *
14335     * @param invalidate Whether this method should call invalidate
14336     *
14337     * @return true if the animation is played, false otherwise
14338     *
14339     * @see #scrollBy(int, int)
14340     * @see #scrollTo(int, int)
14341     * @see #isHorizontalScrollBarEnabled()
14342     * @see #isVerticalScrollBarEnabled()
14343     * @see #setHorizontalScrollBarEnabled(boolean)
14344     * @see #setVerticalScrollBarEnabled(boolean)
14345     */
14346    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
14347        final ScrollabilityCache scrollCache = mScrollCache;
14348
14349        if (scrollCache == null || !scrollCache.fadeScrollBars) {
14350            return false;
14351        }
14352
14353        if (scrollCache.scrollBar == null) {
14354            scrollCache.scrollBar = new ScrollBarDrawable();
14355            scrollCache.scrollBar.setState(getDrawableState());
14356            scrollCache.scrollBar.setCallback(this);
14357        }
14358
14359        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
14360
14361            if (invalidate) {
14362                // Invalidate to show the scrollbars
14363                postInvalidateOnAnimation();
14364            }
14365
14366            if (scrollCache.state == ScrollabilityCache.OFF) {
14367                // FIXME: this is copied from WindowManagerService.
14368                // We should get this value from the system when it
14369                // is possible to do so.
14370                final int KEY_REPEAT_FIRST_DELAY = 750;
14371                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
14372            }
14373
14374            // Tell mScrollCache when we should start fading. This may
14375            // extend the fade start time if one was already scheduled
14376            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
14377            scrollCache.fadeStartTime = fadeStartTime;
14378            scrollCache.state = ScrollabilityCache.ON;
14379
14380            // Schedule our fader to run, unscheduling any old ones first
14381            if (mAttachInfo != null) {
14382                mAttachInfo.mHandler.removeCallbacks(scrollCache);
14383                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
14384            }
14385
14386            return true;
14387        }
14388
14389        return false;
14390    }
14391
14392    /**
14393     * Do not invalidate views which are not visible and which are not running an animation. They
14394     * will not get drawn and they should not set dirty flags as if they will be drawn
14395     */
14396    private boolean skipInvalidate() {
14397        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
14398                (!(mParent instanceof ViewGroup) ||
14399                        !((ViewGroup) mParent).isViewTransitioning(this));
14400    }
14401
14402    /**
14403     * Mark the area defined by dirty as needing to be drawn. If the view is
14404     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14405     * point in the future.
14406     * <p>
14407     * This must be called from a UI thread. To call from a non-UI thread, call
14408     * {@link #postInvalidate()}.
14409     * <p>
14410     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
14411     * {@code dirty}.
14412     *
14413     * @param dirty the rectangle representing the bounds of the dirty region
14414     */
14415    public void invalidate(Rect dirty) {
14416        final int scrollX = mScrollX;
14417        final int scrollY = mScrollY;
14418        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
14419                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
14420    }
14421
14422    /**
14423     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
14424     * coordinates of the dirty rect are relative to the view. If the view is
14425     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14426     * point in the future.
14427     * <p>
14428     * This must be called from a UI thread. To call from a non-UI thread, call
14429     * {@link #postInvalidate()}.
14430     *
14431     * @param l the left position of the dirty region
14432     * @param t the top position of the dirty region
14433     * @param r the right position of the dirty region
14434     * @param b the bottom position of the dirty region
14435     */
14436    public void invalidate(int l, int t, int r, int b) {
14437        final int scrollX = mScrollX;
14438        final int scrollY = mScrollY;
14439        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
14440    }
14441
14442    /**
14443     * Invalidate the whole view. If the view is visible,
14444     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
14445     * the future.
14446     * <p>
14447     * This must be called from a UI thread. To call from a non-UI thread, call
14448     * {@link #postInvalidate()}.
14449     */
14450    public void invalidate() {
14451        invalidate(true);
14452    }
14453
14454    /**
14455     * This is where the invalidate() work actually happens. A full invalidate()
14456     * causes the drawing cache to be invalidated, but this function can be
14457     * called with invalidateCache set to false to skip that invalidation step
14458     * for cases that do not need it (for example, a component that remains at
14459     * the same dimensions with the same content).
14460     *
14461     * @param invalidateCache Whether the drawing cache for this view should be
14462     *            invalidated as well. This is usually true for a full
14463     *            invalidate, but may be set to false if the View's contents or
14464     *            dimensions have not changed.
14465     * @hide
14466     */
14467    public void invalidate(boolean invalidateCache) {
14468        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
14469    }
14470
14471    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
14472            boolean fullInvalidate) {
14473        if (mGhostView != null) {
14474            mGhostView.invalidate(true);
14475            return;
14476        }
14477
14478        if (skipInvalidate()) {
14479            return;
14480        }
14481
14482        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
14483                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
14484                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
14485                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
14486            if (fullInvalidate) {
14487                mLastIsOpaque = isOpaque();
14488                mPrivateFlags &= ~PFLAG_DRAWN;
14489            }
14490
14491            mPrivateFlags |= PFLAG_DIRTY;
14492
14493            if (invalidateCache) {
14494                mPrivateFlags |= PFLAG_INVALIDATED;
14495                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14496            }
14497
14498            // Propagate the damage rectangle to the parent view.
14499            final AttachInfo ai = mAttachInfo;
14500            final ViewParent p = mParent;
14501            if (p != null && ai != null && l < r && t < b) {
14502                final Rect damage = ai.mTmpInvalRect;
14503                damage.set(l, t, r, b);
14504                p.invalidateChild(this, damage);
14505            }
14506
14507            // Damage the entire projection receiver, if necessary.
14508            if (mBackground != null && mBackground.isProjected()) {
14509                final View receiver = getProjectionReceiver();
14510                if (receiver != null) {
14511                    receiver.damageInParent();
14512                }
14513            }
14514        }
14515    }
14516
14517    /**
14518     * @return this view's projection receiver, or {@code null} if none exists
14519     */
14520    private View getProjectionReceiver() {
14521        ViewParent p = getParent();
14522        while (p != null && p instanceof View) {
14523            final View v = (View) p;
14524            if (v.isProjectionReceiver()) {
14525                return v;
14526            }
14527            p = p.getParent();
14528        }
14529
14530        return null;
14531    }
14532
14533    /**
14534     * @return whether the view is a projection receiver
14535     */
14536    private boolean isProjectionReceiver() {
14537        return mBackground != null;
14538    }
14539
14540    /**
14541     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
14542     * set any flags or handle all of the cases handled by the default invalidation methods.
14543     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
14544     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
14545     * walk up the hierarchy, transforming the dirty rect as necessary.
14546     *
14547     * The method also handles normal invalidation logic if display list properties are not
14548     * being used in this view. The invalidateParent and forceRedraw flags are used by that
14549     * backup approach, to handle these cases used in the various property-setting methods.
14550     *
14551     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
14552     * are not being used in this view
14553     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
14554     * list properties are not being used in this view
14555     */
14556    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
14557        if (!isHardwareAccelerated()
14558                || !mRenderNode.isValid()
14559                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
14560            if (invalidateParent) {
14561                invalidateParentCaches();
14562            }
14563            if (forceRedraw) {
14564                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14565            }
14566            invalidate(false);
14567        } else {
14568            damageInParent();
14569        }
14570    }
14571
14572    /**
14573     * Tells the parent view to damage this view's bounds.
14574     *
14575     * @hide
14576     */
14577    protected void damageInParent() {
14578        if (mParent != null && mAttachInfo != null) {
14579            mParent.onDescendantInvalidated(this, this);
14580        }
14581    }
14582
14583    /**
14584     * Utility method to transform a given Rect by the current matrix of this view.
14585     */
14586    void transformRect(final Rect rect) {
14587        if (!getMatrix().isIdentity()) {
14588            RectF boundingRect = mAttachInfo.mTmpTransformRect;
14589            boundingRect.set(rect);
14590            getMatrix().mapRect(boundingRect);
14591            rect.set((int) Math.floor(boundingRect.left),
14592                    (int) Math.floor(boundingRect.top),
14593                    (int) Math.ceil(boundingRect.right),
14594                    (int) Math.ceil(boundingRect.bottom));
14595        }
14596    }
14597
14598    /**
14599     * Used to indicate that the parent of this view should clear its caches. This functionality
14600     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14601     * which is necessary when various parent-managed properties of the view change, such as
14602     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
14603     * clears the parent caches and does not causes an invalidate event.
14604     *
14605     * @hide
14606     */
14607    protected void invalidateParentCaches() {
14608        if (mParent instanceof View) {
14609            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
14610        }
14611    }
14612
14613    /**
14614     * Used to indicate that the parent of this view should be invalidated. This functionality
14615     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14616     * which is necessary when various parent-managed properties of the view change, such as
14617     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
14618     * an invalidation event to the parent.
14619     *
14620     * @hide
14621     */
14622    protected void invalidateParentIfNeeded() {
14623        if (isHardwareAccelerated() && mParent instanceof View) {
14624            ((View) mParent).invalidate(true);
14625        }
14626    }
14627
14628    /**
14629     * @hide
14630     */
14631    protected void invalidateParentIfNeededAndWasQuickRejected() {
14632        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
14633            // View was rejected last time it was drawn by its parent; this may have changed
14634            invalidateParentIfNeeded();
14635        }
14636    }
14637
14638    /**
14639     * Indicates whether this View is opaque. An opaque View guarantees that it will
14640     * draw all the pixels overlapping its bounds using a fully opaque color.
14641     *
14642     * Subclasses of View should override this method whenever possible to indicate
14643     * whether an instance is opaque. Opaque Views are treated in a special way by
14644     * the View hierarchy, possibly allowing it to perform optimizations during
14645     * invalidate/draw passes.
14646     *
14647     * @return True if this View is guaranteed to be fully opaque, false otherwise.
14648     */
14649    @ViewDebug.ExportedProperty(category = "drawing")
14650    public boolean isOpaque() {
14651        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
14652                getFinalAlpha() >= 1.0f;
14653    }
14654
14655    /**
14656     * @hide
14657     */
14658    protected void computeOpaqueFlags() {
14659        // Opaque if:
14660        //   - Has a background
14661        //   - Background is opaque
14662        //   - Doesn't have scrollbars or scrollbars overlay
14663
14664        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
14665            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
14666        } else {
14667            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
14668        }
14669
14670        final int flags = mViewFlags;
14671        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
14672                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
14673                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
14674            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
14675        } else {
14676            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
14677        }
14678    }
14679
14680    /**
14681     * @hide
14682     */
14683    protected boolean hasOpaqueScrollbars() {
14684        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
14685    }
14686
14687    /**
14688     * @return A handler associated with the thread running the View. This
14689     * handler can be used to pump events in the UI events queue.
14690     */
14691    public Handler getHandler() {
14692        final AttachInfo attachInfo = mAttachInfo;
14693        if (attachInfo != null) {
14694            return attachInfo.mHandler;
14695        }
14696        return null;
14697    }
14698
14699    /**
14700     * Returns the queue of runnable for this view.
14701     *
14702     * @return the queue of runnables for this view
14703     */
14704    private HandlerActionQueue getRunQueue() {
14705        if (mRunQueue == null) {
14706            mRunQueue = new HandlerActionQueue();
14707        }
14708        return mRunQueue;
14709    }
14710
14711    /**
14712     * Gets the view root associated with the View.
14713     * @return The view root, or null if none.
14714     * @hide
14715     */
14716    public ViewRootImpl getViewRootImpl() {
14717        if (mAttachInfo != null) {
14718            return mAttachInfo.mViewRootImpl;
14719        }
14720        return null;
14721    }
14722
14723    /**
14724     * @hide
14725     */
14726    public ThreadedRenderer getThreadedRenderer() {
14727        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
14728    }
14729
14730    /**
14731     * <p>Causes the Runnable to be added to the message queue.
14732     * The runnable will be run on the user interface thread.</p>
14733     *
14734     * @param action The Runnable that will be executed.
14735     *
14736     * @return Returns true if the Runnable was successfully placed in to the
14737     *         message queue.  Returns false on failure, usually because the
14738     *         looper processing the message queue is exiting.
14739     *
14740     * @see #postDelayed
14741     * @see #removeCallbacks
14742     */
14743    public boolean post(Runnable action) {
14744        final AttachInfo attachInfo = mAttachInfo;
14745        if (attachInfo != null) {
14746            return attachInfo.mHandler.post(action);
14747        }
14748
14749        // Postpone the runnable until we know on which thread it needs to run.
14750        // Assume that the runnable will be successfully placed after attach.
14751        getRunQueue().post(action);
14752        return true;
14753    }
14754
14755    /**
14756     * <p>Causes the Runnable to be added to the message queue, to be run
14757     * after the specified amount of time elapses.
14758     * The runnable will be run on the user interface thread.</p>
14759     *
14760     * @param action The Runnable that will be executed.
14761     * @param delayMillis The delay (in milliseconds) until the Runnable
14762     *        will be executed.
14763     *
14764     * @return true if the Runnable was successfully placed in to the
14765     *         message queue.  Returns false on failure, usually because the
14766     *         looper processing the message queue is exiting.  Note that a
14767     *         result of true does not mean the Runnable will be processed --
14768     *         if the looper is quit before the delivery time of the message
14769     *         occurs then the message will be dropped.
14770     *
14771     * @see #post
14772     * @see #removeCallbacks
14773     */
14774    public boolean postDelayed(Runnable action, long delayMillis) {
14775        final AttachInfo attachInfo = mAttachInfo;
14776        if (attachInfo != null) {
14777            return attachInfo.mHandler.postDelayed(action, delayMillis);
14778        }
14779
14780        // Postpone the runnable until we know on which thread it needs to run.
14781        // Assume that the runnable will be successfully placed after attach.
14782        getRunQueue().postDelayed(action, delayMillis);
14783        return true;
14784    }
14785
14786    /**
14787     * <p>Causes the Runnable to execute on the next animation time step.
14788     * The runnable will be run on the user interface thread.</p>
14789     *
14790     * @param action The Runnable that will be executed.
14791     *
14792     * @see #postOnAnimationDelayed
14793     * @see #removeCallbacks
14794     */
14795    public void postOnAnimation(Runnable action) {
14796        final AttachInfo attachInfo = mAttachInfo;
14797        if (attachInfo != null) {
14798            attachInfo.mViewRootImpl.mChoreographer.postCallback(
14799                    Choreographer.CALLBACK_ANIMATION, action, null);
14800        } else {
14801            // Postpone the runnable until we know
14802            // on which thread it needs to run.
14803            getRunQueue().post(action);
14804        }
14805    }
14806
14807    /**
14808     * <p>Causes the Runnable to execute on the next animation time step,
14809     * after the specified amount of time elapses.
14810     * The runnable will be run on the user interface thread.</p>
14811     *
14812     * @param action The Runnable that will be executed.
14813     * @param delayMillis The delay (in milliseconds) until the Runnable
14814     *        will be executed.
14815     *
14816     * @see #postOnAnimation
14817     * @see #removeCallbacks
14818     */
14819    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14820        final AttachInfo attachInfo = mAttachInfo;
14821        if (attachInfo != null) {
14822            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14823                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14824        } else {
14825            // Postpone the runnable until we know
14826            // on which thread it needs to run.
14827            getRunQueue().postDelayed(action, delayMillis);
14828        }
14829    }
14830
14831    /**
14832     * <p>Removes the specified Runnable from the message queue.</p>
14833     *
14834     * @param action The Runnable to remove from the message handling queue
14835     *
14836     * @return true if this view could ask the Handler to remove the Runnable,
14837     *         false otherwise. When the returned value is true, the Runnable
14838     *         may or may not have been actually removed from the message queue
14839     *         (for instance, if the Runnable was not in the queue already.)
14840     *
14841     * @see #post
14842     * @see #postDelayed
14843     * @see #postOnAnimation
14844     * @see #postOnAnimationDelayed
14845     */
14846    public boolean removeCallbacks(Runnable action) {
14847        if (action != null) {
14848            final AttachInfo attachInfo = mAttachInfo;
14849            if (attachInfo != null) {
14850                attachInfo.mHandler.removeCallbacks(action);
14851                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14852                        Choreographer.CALLBACK_ANIMATION, action, null);
14853            }
14854            getRunQueue().removeCallbacks(action);
14855        }
14856        return true;
14857    }
14858
14859    /**
14860     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14861     * Use this to invalidate the View from a non-UI thread.</p>
14862     *
14863     * <p>This method can be invoked from outside of the UI thread
14864     * only when this View is attached to a window.</p>
14865     *
14866     * @see #invalidate()
14867     * @see #postInvalidateDelayed(long)
14868     */
14869    public void postInvalidate() {
14870        postInvalidateDelayed(0);
14871    }
14872
14873    /**
14874     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14875     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14876     *
14877     * <p>This method can be invoked from outside of the UI thread
14878     * only when this View is attached to a window.</p>
14879     *
14880     * @param left The left coordinate of the rectangle to invalidate.
14881     * @param top The top coordinate of the rectangle to invalidate.
14882     * @param right The right coordinate of the rectangle to invalidate.
14883     * @param bottom The bottom coordinate of the rectangle to invalidate.
14884     *
14885     * @see #invalidate(int, int, int, int)
14886     * @see #invalidate(Rect)
14887     * @see #postInvalidateDelayed(long, int, int, int, int)
14888     */
14889    public void postInvalidate(int left, int top, int right, int bottom) {
14890        postInvalidateDelayed(0, left, top, right, bottom);
14891    }
14892
14893    /**
14894     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14895     * loop. Waits for the specified amount of time.</p>
14896     *
14897     * <p>This method can be invoked from outside of the UI thread
14898     * only when this View is attached to a window.</p>
14899     *
14900     * @param delayMilliseconds the duration in milliseconds to delay the
14901     *         invalidation by
14902     *
14903     * @see #invalidate()
14904     * @see #postInvalidate()
14905     */
14906    public void postInvalidateDelayed(long delayMilliseconds) {
14907        // We try only with the AttachInfo because there's no point in invalidating
14908        // if we are not attached to our window
14909        final AttachInfo attachInfo = mAttachInfo;
14910        if (attachInfo != null) {
14911            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14912        }
14913    }
14914
14915    /**
14916     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14917     * through the event loop. Waits for the specified amount of time.</p>
14918     *
14919     * <p>This method can be invoked from outside of the UI thread
14920     * only when this View is attached to a window.</p>
14921     *
14922     * @param delayMilliseconds the duration in milliseconds to delay the
14923     *         invalidation by
14924     * @param left The left coordinate of the rectangle to invalidate.
14925     * @param top The top coordinate of the rectangle to invalidate.
14926     * @param right The right coordinate of the rectangle to invalidate.
14927     * @param bottom The bottom coordinate of the rectangle to invalidate.
14928     *
14929     * @see #invalidate(int, int, int, int)
14930     * @see #invalidate(Rect)
14931     * @see #postInvalidate(int, int, int, int)
14932     */
14933    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14934            int right, int bottom) {
14935
14936        // We try only with the AttachInfo because there's no point in invalidating
14937        // if we are not attached to our window
14938        final AttachInfo attachInfo = mAttachInfo;
14939        if (attachInfo != null) {
14940            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14941            info.target = this;
14942            info.left = left;
14943            info.top = top;
14944            info.right = right;
14945            info.bottom = bottom;
14946
14947            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14948        }
14949    }
14950
14951    /**
14952     * <p>Cause an invalidate to happen on the next animation time step, typically the
14953     * next display frame.</p>
14954     *
14955     * <p>This method can be invoked from outside of the UI thread
14956     * only when this View is attached to a window.</p>
14957     *
14958     * @see #invalidate()
14959     */
14960    public void postInvalidateOnAnimation() {
14961        // We try only with the AttachInfo because there's no point in invalidating
14962        // if we are not attached to our window
14963        final AttachInfo attachInfo = mAttachInfo;
14964        if (attachInfo != null) {
14965            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14966        }
14967    }
14968
14969    /**
14970     * <p>Cause an invalidate of the specified area to happen on the next animation
14971     * time step, typically the next display frame.</p>
14972     *
14973     * <p>This method can be invoked from outside of the UI thread
14974     * only when this View is attached to a window.</p>
14975     *
14976     * @param left The left coordinate of the rectangle to invalidate.
14977     * @param top The top coordinate of the rectangle to invalidate.
14978     * @param right The right coordinate of the rectangle to invalidate.
14979     * @param bottom The bottom coordinate of the rectangle to invalidate.
14980     *
14981     * @see #invalidate(int, int, int, int)
14982     * @see #invalidate(Rect)
14983     */
14984    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14985        // We try only with the AttachInfo because there's no point in invalidating
14986        // if we are not attached to our window
14987        final AttachInfo attachInfo = mAttachInfo;
14988        if (attachInfo != null) {
14989            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14990            info.target = this;
14991            info.left = left;
14992            info.top = top;
14993            info.right = right;
14994            info.bottom = bottom;
14995
14996            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14997        }
14998    }
14999
15000    /**
15001     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
15002     * This event is sent at most once every
15003     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
15004     */
15005    private void postSendViewScrolledAccessibilityEventCallback() {
15006        if (mSendViewScrolledAccessibilityEvent == null) {
15007            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
15008        }
15009        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
15010            mSendViewScrolledAccessibilityEvent.mIsPending = true;
15011            postDelayed(mSendViewScrolledAccessibilityEvent,
15012                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
15013        }
15014    }
15015
15016    /**
15017     * Called by a parent to request that a child update its values for mScrollX
15018     * and mScrollY if necessary. This will typically be done if the child is
15019     * animating a scroll using a {@link android.widget.Scroller Scroller}
15020     * object.
15021     */
15022    public void computeScroll() {
15023    }
15024
15025    /**
15026     * <p>Indicate whether the horizontal edges are faded when the view is
15027     * scrolled horizontally.</p>
15028     *
15029     * @return true if the horizontal edges should are faded on scroll, false
15030     *         otherwise
15031     *
15032     * @see #setHorizontalFadingEdgeEnabled(boolean)
15033     *
15034     * @attr ref android.R.styleable#View_requiresFadingEdge
15035     */
15036    public boolean isHorizontalFadingEdgeEnabled() {
15037        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
15038    }
15039
15040    /**
15041     * <p>Define whether the horizontal edges should be faded when this view
15042     * is scrolled horizontally.</p>
15043     *
15044     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
15045     *                                    be faded when the view is scrolled
15046     *                                    horizontally
15047     *
15048     * @see #isHorizontalFadingEdgeEnabled()
15049     *
15050     * @attr ref android.R.styleable#View_requiresFadingEdge
15051     */
15052    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
15053        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
15054            if (horizontalFadingEdgeEnabled) {
15055                initScrollCache();
15056            }
15057
15058            mViewFlags ^= FADING_EDGE_HORIZONTAL;
15059        }
15060    }
15061
15062    /**
15063     * <p>Indicate whether the vertical edges are faded when the view is
15064     * scrolled horizontally.</p>
15065     *
15066     * @return true if the vertical edges should are faded on scroll, false
15067     *         otherwise
15068     *
15069     * @see #setVerticalFadingEdgeEnabled(boolean)
15070     *
15071     * @attr ref android.R.styleable#View_requiresFadingEdge
15072     */
15073    public boolean isVerticalFadingEdgeEnabled() {
15074        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
15075    }
15076
15077    /**
15078     * <p>Define whether the vertical edges should be faded when this view
15079     * is scrolled vertically.</p>
15080     *
15081     * @param verticalFadingEdgeEnabled true if the vertical edges should
15082     *                                  be faded when the view is scrolled
15083     *                                  vertically
15084     *
15085     * @see #isVerticalFadingEdgeEnabled()
15086     *
15087     * @attr ref android.R.styleable#View_requiresFadingEdge
15088     */
15089    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
15090        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
15091            if (verticalFadingEdgeEnabled) {
15092                initScrollCache();
15093            }
15094
15095            mViewFlags ^= FADING_EDGE_VERTICAL;
15096        }
15097    }
15098
15099    /**
15100     * Returns the strength, or intensity, of the top faded edge. The strength is
15101     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15102     * returns 0.0 or 1.0 but no value in between.
15103     *
15104     * Subclasses should override this method to provide a smoother fade transition
15105     * when scrolling occurs.
15106     *
15107     * @return the intensity of the top fade as a float between 0.0f and 1.0f
15108     */
15109    protected float getTopFadingEdgeStrength() {
15110        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
15111    }
15112
15113    /**
15114     * Returns the strength, or intensity, of the bottom faded edge. The strength is
15115     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15116     * returns 0.0 or 1.0 but no value in between.
15117     *
15118     * Subclasses should override this method to provide a smoother fade transition
15119     * when scrolling occurs.
15120     *
15121     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
15122     */
15123    protected float getBottomFadingEdgeStrength() {
15124        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
15125                computeVerticalScrollRange() ? 1.0f : 0.0f;
15126    }
15127
15128    /**
15129     * Returns the strength, or intensity, of the left faded edge. The strength is
15130     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15131     * returns 0.0 or 1.0 but no value in between.
15132     *
15133     * Subclasses should override this method to provide a smoother fade transition
15134     * when scrolling occurs.
15135     *
15136     * @return the intensity of the left fade as a float between 0.0f and 1.0f
15137     */
15138    protected float getLeftFadingEdgeStrength() {
15139        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
15140    }
15141
15142    /**
15143     * Returns the strength, or intensity, of the right faded edge. The strength is
15144     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15145     * returns 0.0 or 1.0 but no value in between.
15146     *
15147     * Subclasses should override this method to provide a smoother fade transition
15148     * when scrolling occurs.
15149     *
15150     * @return the intensity of the right fade as a float between 0.0f and 1.0f
15151     */
15152    protected float getRightFadingEdgeStrength() {
15153        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
15154                computeHorizontalScrollRange() ? 1.0f : 0.0f;
15155    }
15156
15157    /**
15158     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
15159     * scrollbar is not drawn by default.</p>
15160     *
15161     * @return true if the horizontal scrollbar should be painted, false
15162     *         otherwise
15163     *
15164     * @see #setHorizontalScrollBarEnabled(boolean)
15165     */
15166    public boolean isHorizontalScrollBarEnabled() {
15167        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
15168    }
15169
15170    /**
15171     * <p>Define whether the horizontal scrollbar should be drawn or not. The
15172     * scrollbar is not drawn by default.</p>
15173     *
15174     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
15175     *                                   be painted
15176     *
15177     * @see #isHorizontalScrollBarEnabled()
15178     */
15179    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
15180        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
15181            mViewFlags ^= SCROLLBARS_HORIZONTAL;
15182            computeOpaqueFlags();
15183            resolvePadding();
15184        }
15185    }
15186
15187    /**
15188     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
15189     * scrollbar is not drawn by default.</p>
15190     *
15191     * @return true if the vertical scrollbar should be painted, false
15192     *         otherwise
15193     *
15194     * @see #setVerticalScrollBarEnabled(boolean)
15195     */
15196    public boolean isVerticalScrollBarEnabled() {
15197        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
15198    }
15199
15200    /**
15201     * <p>Define whether the vertical scrollbar should be drawn or not. The
15202     * scrollbar is not drawn by default.</p>
15203     *
15204     * @param verticalScrollBarEnabled true if the vertical scrollbar should
15205     *                                 be painted
15206     *
15207     * @see #isVerticalScrollBarEnabled()
15208     */
15209    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
15210        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
15211            mViewFlags ^= SCROLLBARS_VERTICAL;
15212            computeOpaqueFlags();
15213            resolvePadding();
15214        }
15215    }
15216
15217    /**
15218     * @hide
15219     */
15220    protected void recomputePadding() {
15221        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15222    }
15223
15224    /**
15225     * Define whether scrollbars will fade when the view is not scrolling.
15226     *
15227     * @param fadeScrollbars whether to enable fading
15228     *
15229     * @attr ref android.R.styleable#View_fadeScrollbars
15230     */
15231    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
15232        initScrollCache();
15233        final ScrollabilityCache scrollabilityCache = mScrollCache;
15234        scrollabilityCache.fadeScrollBars = fadeScrollbars;
15235        if (fadeScrollbars) {
15236            scrollabilityCache.state = ScrollabilityCache.OFF;
15237        } else {
15238            scrollabilityCache.state = ScrollabilityCache.ON;
15239        }
15240    }
15241
15242    /**
15243     *
15244     * Returns true if scrollbars will fade when this view is not scrolling
15245     *
15246     * @return true if scrollbar fading is enabled
15247     *
15248     * @attr ref android.R.styleable#View_fadeScrollbars
15249     */
15250    public boolean isScrollbarFadingEnabled() {
15251        return mScrollCache != null && mScrollCache.fadeScrollBars;
15252    }
15253
15254    /**
15255     *
15256     * Returns the delay before scrollbars fade.
15257     *
15258     * @return the delay before scrollbars fade
15259     *
15260     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15261     */
15262    public int getScrollBarDefaultDelayBeforeFade() {
15263        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
15264                mScrollCache.scrollBarDefaultDelayBeforeFade;
15265    }
15266
15267    /**
15268     * Define the delay before scrollbars fade.
15269     *
15270     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
15271     *
15272     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15273     */
15274    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
15275        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
15276    }
15277
15278    /**
15279     *
15280     * Returns the scrollbar fade duration.
15281     *
15282     * @return the scrollbar fade duration, in milliseconds
15283     *
15284     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15285     */
15286    public int getScrollBarFadeDuration() {
15287        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
15288                mScrollCache.scrollBarFadeDuration;
15289    }
15290
15291    /**
15292     * Define the scrollbar fade duration.
15293     *
15294     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
15295     *
15296     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15297     */
15298    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
15299        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
15300    }
15301
15302    /**
15303     *
15304     * Returns the scrollbar size.
15305     *
15306     * @return the scrollbar size
15307     *
15308     * @attr ref android.R.styleable#View_scrollbarSize
15309     */
15310    public int getScrollBarSize() {
15311        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
15312                mScrollCache.scrollBarSize;
15313    }
15314
15315    /**
15316     * Define the scrollbar size.
15317     *
15318     * @param scrollBarSize - the scrollbar size
15319     *
15320     * @attr ref android.R.styleable#View_scrollbarSize
15321     */
15322    public void setScrollBarSize(int scrollBarSize) {
15323        getScrollCache().scrollBarSize = scrollBarSize;
15324    }
15325
15326    /**
15327     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
15328     * inset. When inset, they add to the padding of the view. And the scrollbars
15329     * can be drawn inside the padding area or on the edge of the view. For example,
15330     * if a view has a background drawable and you want to draw the scrollbars
15331     * inside the padding specified by the drawable, you can use
15332     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
15333     * appear at the edge of the view, ignoring the padding, then you can use
15334     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
15335     * @param style the style of the scrollbars. Should be one of
15336     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
15337     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
15338     * @see #SCROLLBARS_INSIDE_OVERLAY
15339     * @see #SCROLLBARS_INSIDE_INSET
15340     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15341     * @see #SCROLLBARS_OUTSIDE_INSET
15342     *
15343     * @attr ref android.R.styleable#View_scrollbarStyle
15344     */
15345    public void setScrollBarStyle(@ScrollBarStyle int style) {
15346        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
15347            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
15348            computeOpaqueFlags();
15349            resolvePadding();
15350        }
15351    }
15352
15353    /**
15354     * <p>Returns the current scrollbar style.</p>
15355     * @return the current scrollbar style
15356     * @see #SCROLLBARS_INSIDE_OVERLAY
15357     * @see #SCROLLBARS_INSIDE_INSET
15358     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15359     * @see #SCROLLBARS_OUTSIDE_INSET
15360     *
15361     * @attr ref android.R.styleable#View_scrollbarStyle
15362     */
15363    @ViewDebug.ExportedProperty(mapping = {
15364            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
15365            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
15366            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
15367            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
15368    })
15369    @ScrollBarStyle
15370    public int getScrollBarStyle() {
15371        return mViewFlags & SCROLLBARS_STYLE_MASK;
15372    }
15373
15374    /**
15375     * <p>Compute the horizontal range that the horizontal scrollbar
15376     * represents.</p>
15377     *
15378     * <p>The range is expressed in arbitrary units that must be the same as the
15379     * units used by {@link #computeHorizontalScrollExtent()} and
15380     * {@link #computeHorizontalScrollOffset()}.</p>
15381     *
15382     * <p>The default range is the drawing width of this view.</p>
15383     *
15384     * @return the total horizontal range represented by the horizontal
15385     *         scrollbar
15386     *
15387     * @see #computeHorizontalScrollExtent()
15388     * @see #computeHorizontalScrollOffset()
15389     * @see android.widget.ScrollBarDrawable
15390     */
15391    protected int computeHorizontalScrollRange() {
15392        return getWidth();
15393    }
15394
15395    /**
15396     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
15397     * within the horizontal range. This value is used to compute the position
15398     * of the thumb within the scrollbar's track.</p>
15399     *
15400     * <p>The range is expressed in arbitrary units that must be the same as the
15401     * units used by {@link #computeHorizontalScrollRange()} and
15402     * {@link #computeHorizontalScrollExtent()}.</p>
15403     *
15404     * <p>The default offset is the scroll offset of this view.</p>
15405     *
15406     * @return the horizontal offset of the scrollbar's thumb
15407     *
15408     * @see #computeHorizontalScrollRange()
15409     * @see #computeHorizontalScrollExtent()
15410     * @see android.widget.ScrollBarDrawable
15411     */
15412    protected int computeHorizontalScrollOffset() {
15413        return mScrollX;
15414    }
15415
15416    /**
15417     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
15418     * within the horizontal range. This value is used to compute the length
15419     * of the thumb within the scrollbar's track.</p>
15420     *
15421     * <p>The range is expressed in arbitrary units that must be the same as the
15422     * units used by {@link #computeHorizontalScrollRange()} and
15423     * {@link #computeHorizontalScrollOffset()}.</p>
15424     *
15425     * <p>The default extent is the drawing width of this view.</p>
15426     *
15427     * @return the horizontal extent of the scrollbar's thumb
15428     *
15429     * @see #computeHorizontalScrollRange()
15430     * @see #computeHorizontalScrollOffset()
15431     * @see android.widget.ScrollBarDrawable
15432     */
15433    protected int computeHorizontalScrollExtent() {
15434        return getWidth();
15435    }
15436
15437    /**
15438     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
15439     *
15440     * <p>The range is expressed in arbitrary units that must be the same as the
15441     * units used by {@link #computeVerticalScrollExtent()} and
15442     * {@link #computeVerticalScrollOffset()}.</p>
15443     *
15444     * @return the total vertical range represented by the vertical scrollbar
15445     *
15446     * <p>The default range is the drawing height of this view.</p>
15447     *
15448     * @see #computeVerticalScrollExtent()
15449     * @see #computeVerticalScrollOffset()
15450     * @see android.widget.ScrollBarDrawable
15451     */
15452    protected int computeVerticalScrollRange() {
15453        return getHeight();
15454    }
15455
15456    /**
15457     * <p>Compute the vertical offset of the vertical scrollbar's thumb
15458     * within the horizontal range. This value is used to compute the position
15459     * of the thumb within the scrollbar's track.</p>
15460     *
15461     * <p>The range is expressed in arbitrary units that must be the same as the
15462     * units used by {@link #computeVerticalScrollRange()} and
15463     * {@link #computeVerticalScrollExtent()}.</p>
15464     *
15465     * <p>The default offset is the scroll offset of this view.</p>
15466     *
15467     * @return the vertical offset of the scrollbar's thumb
15468     *
15469     * @see #computeVerticalScrollRange()
15470     * @see #computeVerticalScrollExtent()
15471     * @see android.widget.ScrollBarDrawable
15472     */
15473    protected int computeVerticalScrollOffset() {
15474        return mScrollY;
15475    }
15476
15477    /**
15478     * <p>Compute the vertical extent of the vertical scrollbar's thumb
15479     * within the vertical range. This value is used to compute the length
15480     * of the thumb within the scrollbar's track.</p>
15481     *
15482     * <p>The range is expressed in arbitrary units that must be the same as the
15483     * units used by {@link #computeVerticalScrollRange()} and
15484     * {@link #computeVerticalScrollOffset()}.</p>
15485     *
15486     * <p>The default extent is the drawing height of this view.</p>
15487     *
15488     * @return the vertical extent of the scrollbar's thumb
15489     *
15490     * @see #computeVerticalScrollRange()
15491     * @see #computeVerticalScrollOffset()
15492     * @see android.widget.ScrollBarDrawable
15493     */
15494    protected int computeVerticalScrollExtent() {
15495        return getHeight();
15496    }
15497
15498    /**
15499     * Check if this view can be scrolled horizontally in a certain direction.
15500     *
15501     * @param direction Negative to check scrolling left, positive to check scrolling right.
15502     * @return true if this view can be scrolled in the specified direction, false otherwise.
15503     */
15504    public boolean canScrollHorizontally(int direction) {
15505        final int offset = computeHorizontalScrollOffset();
15506        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
15507        if (range == 0) return false;
15508        if (direction < 0) {
15509            return offset > 0;
15510        } else {
15511            return offset < range - 1;
15512        }
15513    }
15514
15515    /**
15516     * Check if this view can be scrolled vertically in a certain direction.
15517     *
15518     * @param direction Negative to check scrolling up, positive to check scrolling down.
15519     * @return true if this view can be scrolled in the specified direction, false otherwise.
15520     */
15521    public boolean canScrollVertically(int direction) {
15522        final int offset = computeVerticalScrollOffset();
15523        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
15524        if (range == 0) return false;
15525        if (direction < 0) {
15526            return offset > 0;
15527        } else {
15528            return offset < range - 1;
15529        }
15530    }
15531
15532    void getScrollIndicatorBounds(@NonNull Rect out) {
15533        out.left = mScrollX;
15534        out.right = mScrollX + mRight - mLeft;
15535        out.top = mScrollY;
15536        out.bottom = mScrollY + mBottom - mTop;
15537    }
15538
15539    private void onDrawScrollIndicators(Canvas c) {
15540        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
15541            // No scroll indicators enabled.
15542            return;
15543        }
15544
15545        final Drawable dr = mScrollIndicatorDrawable;
15546        if (dr == null) {
15547            // Scroll indicators aren't supported here.
15548            return;
15549        }
15550
15551        final int h = dr.getIntrinsicHeight();
15552        final int w = dr.getIntrinsicWidth();
15553        final Rect rect = mAttachInfo.mTmpInvalRect;
15554        getScrollIndicatorBounds(rect);
15555
15556        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
15557            final boolean canScrollUp = canScrollVertically(-1);
15558            if (canScrollUp) {
15559                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
15560                dr.draw(c);
15561            }
15562        }
15563
15564        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
15565            final boolean canScrollDown = canScrollVertically(1);
15566            if (canScrollDown) {
15567                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
15568                dr.draw(c);
15569            }
15570        }
15571
15572        final int leftRtl;
15573        final int rightRtl;
15574        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15575            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
15576            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
15577        } else {
15578            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
15579            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
15580        }
15581
15582        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
15583        if ((mPrivateFlags3 & leftMask) != 0) {
15584            final boolean canScrollLeft = canScrollHorizontally(-1);
15585            if (canScrollLeft) {
15586                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
15587                dr.draw(c);
15588            }
15589        }
15590
15591        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
15592        if ((mPrivateFlags3 & rightMask) != 0) {
15593            final boolean canScrollRight = canScrollHorizontally(1);
15594            if (canScrollRight) {
15595                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
15596                dr.draw(c);
15597            }
15598        }
15599    }
15600
15601    private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds,
15602            @Nullable Rect touchBounds) {
15603        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
15604        if (bounds == null) {
15605            return;
15606        }
15607        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15608        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15609                && !isVerticalScrollBarHidden();
15610        final int size = getHorizontalScrollbarHeight();
15611        final int verticalScrollBarGap = drawVerticalScrollBar ?
15612                getVerticalScrollbarWidth() : 0;
15613        final int width = mRight - mLeft;
15614        final int height = mBottom - mTop;
15615        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
15616        bounds.left = mScrollX + (mPaddingLeft & inside);
15617        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
15618        bounds.bottom = bounds.top + size;
15619
15620        if (touchBounds == null) {
15621            return;
15622        }
15623        if (touchBounds != bounds) {
15624            touchBounds.set(bounds);
15625        }
15626        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
15627        if (touchBounds.height() < minTouchTarget) {
15628            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
15629            touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height);
15630            touchBounds.top = touchBounds.bottom - minTouchTarget;
15631        }
15632        if (touchBounds.width() < minTouchTarget) {
15633            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
15634            touchBounds.left -= adjust;
15635            touchBounds.right = touchBounds.left + minTouchTarget;
15636        }
15637    }
15638
15639    private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) {
15640        if (mRoundScrollbarRenderer == null) {
15641            getStraightVerticalScrollBarBounds(bounds, touchBounds);
15642        } else {
15643            getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds);
15644        }
15645    }
15646
15647    private void getRoundVerticalScrollBarBounds(Rect bounds) {
15648        final int width = mRight - mLeft;
15649        final int height = mBottom - mTop;
15650        // Do not take padding into account as we always want the scrollbars
15651        // to hug the screen for round wearable devices.
15652        bounds.left = mScrollX;
15653        bounds.top = mScrollY;
15654        bounds.right = bounds.left + width;
15655        bounds.bottom = mScrollY + height;
15656    }
15657
15658    private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds,
15659            @Nullable Rect touchBounds) {
15660        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
15661        if (bounds == null) {
15662            return;
15663        }
15664        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15665        final int size = getVerticalScrollbarWidth();
15666        int verticalScrollbarPosition = mVerticalScrollbarPosition;
15667        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
15668            verticalScrollbarPosition = isLayoutRtl() ?
15669                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
15670        }
15671        final int width = mRight - mLeft;
15672        final int height = mBottom - mTop;
15673        switch (verticalScrollbarPosition) {
15674            default:
15675            case SCROLLBAR_POSITION_RIGHT:
15676                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
15677                break;
15678            case SCROLLBAR_POSITION_LEFT:
15679                bounds.left = mScrollX + (mUserPaddingLeft & inside);
15680                break;
15681        }
15682        bounds.top = mScrollY + (mPaddingTop & inside);
15683        bounds.right = bounds.left + size;
15684        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
15685
15686        if (touchBounds == null) {
15687            return;
15688        }
15689        if (touchBounds != bounds) {
15690            touchBounds.set(bounds);
15691        }
15692        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
15693        if (touchBounds.width() < minTouchTarget) {
15694            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
15695            if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) {
15696                touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width);
15697                touchBounds.left = touchBounds.right - minTouchTarget;
15698            } else {
15699                touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX);
15700                touchBounds.right = touchBounds.left + minTouchTarget;
15701            }
15702        }
15703        if (touchBounds.height() < minTouchTarget) {
15704            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
15705            touchBounds.top -= adjust;
15706            touchBounds.bottom = touchBounds.top + minTouchTarget;
15707        }
15708    }
15709
15710    /**
15711     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
15712     * scrollbars are painted only if they have been awakened first.</p>
15713     *
15714     * @param canvas the canvas on which to draw the scrollbars
15715     *
15716     * @see #awakenScrollBars(int)
15717     */
15718    protected final void onDrawScrollBars(Canvas canvas) {
15719        // scrollbars are drawn only when the animation is running
15720        final ScrollabilityCache cache = mScrollCache;
15721
15722        if (cache != null) {
15723
15724            int state = cache.state;
15725
15726            if (state == ScrollabilityCache.OFF) {
15727                return;
15728            }
15729
15730            boolean invalidate = false;
15731
15732            if (state == ScrollabilityCache.FADING) {
15733                // We're fading -- get our fade interpolation
15734                if (cache.interpolatorValues == null) {
15735                    cache.interpolatorValues = new float[1];
15736                }
15737
15738                float[] values = cache.interpolatorValues;
15739
15740                // Stops the animation if we're done
15741                if (cache.scrollBarInterpolator.timeToValues(values) ==
15742                        Interpolator.Result.FREEZE_END) {
15743                    cache.state = ScrollabilityCache.OFF;
15744                } else {
15745                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
15746                }
15747
15748                // This will make the scroll bars inval themselves after
15749                // drawing. We only want this when we're fading so that
15750                // we prevent excessive redraws
15751                invalidate = true;
15752            } else {
15753                // We're just on -- but we may have been fading before so
15754                // reset alpha
15755                cache.scrollBar.mutate().setAlpha(255);
15756            }
15757
15758            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
15759            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15760                    && !isVerticalScrollBarHidden();
15761
15762            // Fork out the scroll bar drawing for round wearable devices.
15763            if (mRoundScrollbarRenderer != null) {
15764                if (drawVerticalScrollBar) {
15765                    final Rect bounds = cache.mScrollBarBounds;
15766                    getVerticalScrollBarBounds(bounds, null);
15767                    mRoundScrollbarRenderer.drawRoundScrollbars(
15768                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
15769                    if (invalidate) {
15770                        invalidate();
15771                    }
15772                }
15773                // Do not draw horizontal scroll bars for round wearable devices.
15774            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
15775                final ScrollBarDrawable scrollBar = cache.scrollBar;
15776
15777                if (drawHorizontalScrollBar) {
15778                    scrollBar.setParameters(computeHorizontalScrollRange(),
15779                            computeHorizontalScrollOffset(),
15780                            computeHorizontalScrollExtent(), false);
15781                    final Rect bounds = cache.mScrollBarBounds;
15782                    getHorizontalScrollBarBounds(bounds, null);
15783                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15784                            bounds.right, bounds.bottom);
15785                    if (invalidate) {
15786                        invalidate(bounds);
15787                    }
15788                }
15789
15790                if (drawVerticalScrollBar) {
15791                    scrollBar.setParameters(computeVerticalScrollRange(),
15792                            computeVerticalScrollOffset(),
15793                            computeVerticalScrollExtent(), true);
15794                    final Rect bounds = cache.mScrollBarBounds;
15795                    getVerticalScrollBarBounds(bounds, null);
15796                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15797                            bounds.right, bounds.bottom);
15798                    if (invalidate) {
15799                        invalidate(bounds);
15800                    }
15801                }
15802            }
15803        }
15804    }
15805
15806    /**
15807     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
15808     * FastScroller is visible.
15809     * @return whether to temporarily hide the vertical scrollbar
15810     * @hide
15811     */
15812    protected boolean isVerticalScrollBarHidden() {
15813        return false;
15814    }
15815
15816    /**
15817     * <p>Draw the horizontal scrollbar if
15818     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
15819     *
15820     * @param canvas the canvas on which to draw the scrollbar
15821     * @param scrollBar the scrollbar's drawable
15822     *
15823     * @see #isHorizontalScrollBarEnabled()
15824     * @see #computeHorizontalScrollRange()
15825     * @see #computeHorizontalScrollExtent()
15826     * @see #computeHorizontalScrollOffset()
15827     * @see android.widget.ScrollBarDrawable
15828     * @hide
15829     */
15830    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
15831            int l, int t, int r, int b) {
15832        scrollBar.setBounds(l, t, r, b);
15833        scrollBar.draw(canvas);
15834    }
15835
15836    /**
15837     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
15838     * returns true.</p>
15839     *
15840     * @param canvas the canvas on which to draw the scrollbar
15841     * @param scrollBar the scrollbar's drawable
15842     *
15843     * @see #isVerticalScrollBarEnabled()
15844     * @see #computeVerticalScrollRange()
15845     * @see #computeVerticalScrollExtent()
15846     * @see #computeVerticalScrollOffset()
15847     * @see android.widget.ScrollBarDrawable
15848     * @hide
15849     */
15850    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
15851            int l, int t, int r, int b) {
15852        scrollBar.setBounds(l, t, r, b);
15853        scrollBar.draw(canvas);
15854    }
15855
15856    /**
15857     * Implement this to do your drawing.
15858     *
15859     * @param canvas the canvas on which the background will be drawn
15860     */
15861    protected void onDraw(Canvas canvas) {
15862    }
15863
15864    /*
15865     * Caller is responsible for calling requestLayout if necessary.
15866     * (This allows addViewInLayout to not request a new layout.)
15867     */
15868    void assignParent(ViewParent parent) {
15869        if (mParent == null) {
15870            mParent = parent;
15871        } else if (parent == null) {
15872            mParent = null;
15873        } else {
15874            throw new RuntimeException("view " + this + " being added, but"
15875                    + " it already has a parent");
15876        }
15877    }
15878
15879    /**
15880     * This is called when the view is attached to a window.  At this point it
15881     * has a Surface and will start drawing.  Note that this function is
15882     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15883     * however it may be called any time before the first onDraw -- including
15884     * before or after {@link #onMeasure(int, int)}.
15885     *
15886     * @see #onDetachedFromWindow()
15887     */
15888    @CallSuper
15889    protected void onAttachedToWindow() {
15890        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15891            mParent.requestTransparentRegion(this);
15892        }
15893
15894        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15895
15896        jumpDrawablesToCurrentState();
15897
15898        resetSubtreeAccessibilityStateChanged();
15899
15900        // rebuild, since Outline not maintained while View is detached
15901        rebuildOutline();
15902
15903        if (isFocused()) {
15904            InputMethodManager imm = InputMethodManager.peekInstance();
15905            if (imm != null) {
15906                imm.focusIn(this);
15907            }
15908        }
15909    }
15910
15911    /**
15912     * Resolve all RTL related properties.
15913     *
15914     * @return true if resolution of RTL properties has been done
15915     *
15916     * @hide
15917     */
15918    public boolean resolveRtlPropertiesIfNeeded() {
15919        if (!needRtlPropertiesResolution()) return false;
15920
15921        // Order is important here: LayoutDirection MUST be resolved first
15922        if (!isLayoutDirectionResolved()) {
15923            resolveLayoutDirection();
15924            resolveLayoutParams();
15925        }
15926        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15927        if (!isTextDirectionResolved()) {
15928            resolveTextDirection();
15929        }
15930        if (!isTextAlignmentResolved()) {
15931            resolveTextAlignment();
15932        }
15933        // Should resolve Drawables before Padding because we need the layout direction of the
15934        // Drawable to correctly resolve Padding.
15935        if (!areDrawablesResolved()) {
15936            resolveDrawables();
15937        }
15938        if (!isPaddingResolved()) {
15939            resolvePadding();
15940        }
15941        onRtlPropertiesChanged(getLayoutDirection());
15942        return true;
15943    }
15944
15945    /**
15946     * Reset resolution of all RTL related properties.
15947     *
15948     * @hide
15949     */
15950    public void resetRtlProperties() {
15951        resetResolvedLayoutDirection();
15952        resetResolvedTextDirection();
15953        resetResolvedTextAlignment();
15954        resetResolvedPadding();
15955        resetResolvedDrawables();
15956    }
15957
15958    /**
15959     * @see #onScreenStateChanged(int)
15960     */
15961    void dispatchScreenStateChanged(int screenState) {
15962        onScreenStateChanged(screenState);
15963    }
15964
15965    /**
15966     * This method is called whenever the state of the screen this view is
15967     * attached to changes. A state change will usually occurs when the screen
15968     * turns on or off (whether it happens automatically or the user does it
15969     * manually.)
15970     *
15971     * @param screenState The new state of the screen. Can be either
15972     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15973     */
15974    public void onScreenStateChanged(int screenState) {
15975    }
15976
15977    /**
15978     * @see #onMovedToDisplay(int)
15979     */
15980    void dispatchMovedToDisplay(Display display) {
15981        mAttachInfo.mDisplay = display;
15982        mAttachInfo.mDisplayState = display.getState();
15983        onMovedToDisplay(display.getDisplayId());
15984    }
15985
15986    /**
15987     * Called by the system when the hosting activity is moved from one display to another without
15988     * recreation. This means that the activity is declared to handle all changes to configuration
15989     * that happened when it was switched to another display, so it wasn't destroyed and created
15990     * again. This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
15991     * applied configuration actually changed.
15992     *
15993     * <p>Use this callback to track changes to the displays if some functionality relies on an
15994     * association with some display properties.
15995     *
15996     * @param displayId The id of the display to which the view was moved.
15997     *
15998     * @see #onConfigurationChanged(Configuration)
15999     */
16000    public void onMovedToDisplay(int displayId) {
16001    }
16002
16003    /**
16004     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
16005     */
16006    private boolean hasRtlSupport() {
16007        return mContext.getApplicationInfo().hasRtlSupport();
16008    }
16009
16010    /**
16011     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
16012     * RTL not supported)
16013     */
16014    private boolean isRtlCompatibilityMode() {
16015        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
16016        return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport();
16017    }
16018
16019    /**
16020     * @return true if RTL properties need resolution.
16021     *
16022     */
16023    private boolean needRtlPropertiesResolution() {
16024        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
16025    }
16026
16027    /**
16028     * Called when any RTL property (layout direction or text direction or text alignment) has
16029     * been changed.
16030     *
16031     * Subclasses need to override this method to take care of cached information that depends on the
16032     * resolved layout direction, or to inform child views that inherit their layout direction.
16033     *
16034     * The default implementation does nothing.
16035     *
16036     * @param layoutDirection the direction of the layout
16037     *
16038     * @see #LAYOUT_DIRECTION_LTR
16039     * @see #LAYOUT_DIRECTION_RTL
16040     */
16041    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
16042    }
16043
16044    /**
16045     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
16046     * that the parent directionality can and will be resolved before its children.
16047     *
16048     * @return true if resolution has been done, false otherwise.
16049     *
16050     * @hide
16051     */
16052    public boolean resolveLayoutDirection() {
16053        // Clear any previous layout direction resolution
16054        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16055
16056        if (hasRtlSupport()) {
16057            // Set resolved depending on layout direction
16058            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
16059                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
16060                case LAYOUT_DIRECTION_INHERIT:
16061                    // We cannot resolve yet. LTR is by default and let the resolution happen again
16062                    // later to get the correct resolved value
16063                    if (!canResolveLayoutDirection()) return false;
16064
16065                    // Parent has not yet resolved, LTR is still the default
16066                    try {
16067                        if (!mParent.isLayoutDirectionResolved()) return false;
16068
16069                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
16070                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16071                        }
16072                    } catch (AbstractMethodError e) {
16073                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16074                                " does not fully implement ViewParent", e);
16075                    }
16076                    break;
16077                case LAYOUT_DIRECTION_RTL:
16078                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16079                    break;
16080                case LAYOUT_DIRECTION_LOCALE:
16081                    if((LAYOUT_DIRECTION_RTL ==
16082                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
16083                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16084                    }
16085                    break;
16086                default:
16087                    // Nothing to do, LTR by default
16088            }
16089        }
16090
16091        // Set to resolved
16092        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16093        return true;
16094    }
16095
16096    /**
16097     * Check if layout direction resolution can be done.
16098     *
16099     * @return true if layout direction resolution can be done otherwise return false.
16100     */
16101    public boolean canResolveLayoutDirection() {
16102        switch (getRawLayoutDirection()) {
16103            case LAYOUT_DIRECTION_INHERIT:
16104                if (mParent != null) {
16105                    try {
16106                        return mParent.canResolveLayoutDirection();
16107                    } catch (AbstractMethodError e) {
16108                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16109                                " does not fully implement ViewParent", e);
16110                    }
16111                }
16112                return false;
16113
16114            default:
16115                return true;
16116        }
16117    }
16118
16119    /**
16120     * Reset the resolved layout direction. Layout direction will be resolved during a call to
16121     * {@link #onMeasure(int, int)}.
16122     *
16123     * @hide
16124     */
16125    public void resetResolvedLayoutDirection() {
16126        // Reset the current resolved bits
16127        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16128    }
16129
16130    /**
16131     * @return true if the layout direction is inherited.
16132     *
16133     * @hide
16134     */
16135    public boolean isLayoutDirectionInherited() {
16136        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
16137    }
16138
16139    /**
16140     * @return true if layout direction has been resolved.
16141     */
16142    public boolean isLayoutDirectionResolved() {
16143        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16144    }
16145
16146    /**
16147     * Return if padding has been resolved
16148     *
16149     * @hide
16150     */
16151    boolean isPaddingResolved() {
16152        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
16153    }
16154
16155    /**
16156     * Resolves padding depending on layout direction, if applicable, and
16157     * recomputes internal padding values to adjust for scroll bars.
16158     *
16159     * @hide
16160     */
16161    public void resolvePadding() {
16162        final int resolvedLayoutDirection = getLayoutDirection();
16163
16164        if (!isRtlCompatibilityMode()) {
16165            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
16166            // If start / end padding are defined, they will be resolved (hence overriding) to
16167            // left / right or right / left depending on the resolved layout direction.
16168            // If start / end padding are not defined, use the left / right ones.
16169            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
16170                Rect padding = sThreadLocal.get();
16171                if (padding == null) {
16172                    padding = new Rect();
16173                    sThreadLocal.set(padding);
16174                }
16175                mBackground.getPadding(padding);
16176                if (!mLeftPaddingDefined) {
16177                    mUserPaddingLeftInitial = padding.left;
16178                }
16179                if (!mRightPaddingDefined) {
16180                    mUserPaddingRightInitial = padding.right;
16181                }
16182            }
16183            switch (resolvedLayoutDirection) {
16184                case LAYOUT_DIRECTION_RTL:
16185                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16186                        mUserPaddingRight = mUserPaddingStart;
16187                    } else {
16188                        mUserPaddingRight = mUserPaddingRightInitial;
16189                    }
16190                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16191                        mUserPaddingLeft = mUserPaddingEnd;
16192                    } else {
16193                        mUserPaddingLeft = mUserPaddingLeftInitial;
16194                    }
16195                    break;
16196                case LAYOUT_DIRECTION_LTR:
16197                default:
16198                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16199                        mUserPaddingLeft = mUserPaddingStart;
16200                    } else {
16201                        mUserPaddingLeft = mUserPaddingLeftInitial;
16202                    }
16203                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16204                        mUserPaddingRight = mUserPaddingEnd;
16205                    } else {
16206                        mUserPaddingRight = mUserPaddingRightInitial;
16207                    }
16208            }
16209
16210            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
16211        }
16212
16213        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
16214        onRtlPropertiesChanged(resolvedLayoutDirection);
16215
16216        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
16217    }
16218
16219    /**
16220     * Reset the resolved layout direction.
16221     *
16222     * @hide
16223     */
16224    public void resetResolvedPadding() {
16225        resetResolvedPaddingInternal();
16226    }
16227
16228    /**
16229     * Used when we only want to reset *this* view's padding and not trigger overrides
16230     * in ViewGroup that reset children too.
16231     */
16232    void resetResolvedPaddingInternal() {
16233        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
16234    }
16235
16236    /**
16237     * This is called when the view is detached from a window.  At this point it
16238     * no longer has a surface for drawing.
16239     *
16240     * @see #onAttachedToWindow()
16241     */
16242    @CallSuper
16243    protected void onDetachedFromWindow() {
16244    }
16245
16246    /**
16247     * This is a framework-internal mirror of onDetachedFromWindow() that's called
16248     * after onDetachedFromWindow().
16249     *
16250     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
16251     * The super method should be called at the end of the overridden method to ensure
16252     * subclasses are destroyed first
16253     *
16254     * @hide
16255     */
16256    @CallSuper
16257    protected void onDetachedFromWindowInternal() {
16258        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
16259        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
16260        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
16261
16262        removeUnsetPressCallback();
16263        removeLongPressCallback();
16264        removePerformClickCallback();
16265        removeSendViewScrolledAccessibilityEventCallback();
16266        stopNestedScroll();
16267
16268        // Anything that started animating right before detach should already
16269        // be in its final state when re-attached.
16270        jumpDrawablesToCurrentState();
16271
16272        destroyDrawingCache();
16273
16274        cleanupDraw();
16275        mCurrentAnimation = null;
16276
16277        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
16278            hideTooltip();
16279        }
16280    }
16281
16282    private void cleanupDraw() {
16283        resetDisplayList();
16284        if (mAttachInfo != null) {
16285            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
16286        }
16287    }
16288
16289    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
16290    }
16291
16292    /**
16293     * @return The number of times this view has been attached to a window
16294     */
16295    protected int getWindowAttachCount() {
16296        return mWindowAttachCount;
16297    }
16298
16299    /**
16300     * Retrieve a unique token identifying the window this view is attached to.
16301     * @return Return the window's token for use in
16302     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
16303     */
16304    public IBinder getWindowToken() {
16305        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
16306    }
16307
16308    /**
16309     * Retrieve the {@link WindowId} for the window this view is
16310     * currently attached to.
16311     */
16312    public WindowId getWindowId() {
16313        if (mAttachInfo == null) {
16314            return null;
16315        }
16316        if (mAttachInfo.mWindowId == null) {
16317            try {
16318                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
16319                        mAttachInfo.mWindowToken);
16320                mAttachInfo.mWindowId = new WindowId(
16321                        mAttachInfo.mIWindowId);
16322            } catch (RemoteException e) {
16323            }
16324        }
16325        return mAttachInfo.mWindowId;
16326    }
16327
16328    /**
16329     * Retrieve a unique token identifying the top-level "real" window of
16330     * the window that this view is attached to.  That is, this is like
16331     * {@link #getWindowToken}, except if the window this view in is a panel
16332     * window (attached to another containing window), then the token of
16333     * the containing window is returned instead.
16334     *
16335     * @return Returns the associated window token, either
16336     * {@link #getWindowToken()} or the containing window's token.
16337     */
16338    public IBinder getApplicationWindowToken() {
16339        AttachInfo ai = mAttachInfo;
16340        if (ai != null) {
16341            IBinder appWindowToken = ai.mPanelParentWindowToken;
16342            if (appWindowToken == null) {
16343                appWindowToken = ai.mWindowToken;
16344            }
16345            return appWindowToken;
16346        }
16347        return null;
16348    }
16349
16350    /**
16351     * Gets the logical display to which the view's window has been attached.
16352     *
16353     * @return The logical display, or null if the view is not currently attached to a window.
16354     */
16355    public Display getDisplay() {
16356        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
16357    }
16358
16359    /**
16360     * Retrieve private session object this view hierarchy is using to
16361     * communicate with the window manager.
16362     * @return the session object to communicate with the window manager
16363     */
16364    /*package*/ IWindowSession getWindowSession() {
16365        return mAttachInfo != null ? mAttachInfo.mSession : null;
16366    }
16367
16368    /**
16369     * Return the visibility value of the least visible component passed.
16370     */
16371    int combineVisibility(int vis1, int vis2) {
16372        // This works because VISIBLE < INVISIBLE < GONE.
16373        return Math.max(vis1, vis2);
16374    }
16375
16376    /**
16377     * @param info the {@link android.view.View.AttachInfo} to associated with
16378     *        this view
16379     */
16380    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
16381        mAttachInfo = info;
16382        if (mOverlay != null) {
16383            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
16384        }
16385        mWindowAttachCount++;
16386        // We will need to evaluate the drawable state at least once.
16387        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16388        if (mFloatingTreeObserver != null) {
16389            info.mTreeObserver.merge(mFloatingTreeObserver);
16390            mFloatingTreeObserver = null;
16391        }
16392
16393        registerPendingFrameMetricsObservers();
16394
16395        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
16396            mAttachInfo.mScrollContainers.add(this);
16397            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
16398        }
16399        // Transfer all pending runnables.
16400        if (mRunQueue != null) {
16401            mRunQueue.executeActions(info.mHandler);
16402            mRunQueue = null;
16403        }
16404        performCollectViewAttributes(mAttachInfo, visibility);
16405        onAttachedToWindow();
16406
16407        ListenerInfo li = mListenerInfo;
16408        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16409                li != null ? li.mOnAttachStateChangeListeners : null;
16410        if (listeners != null && listeners.size() > 0) {
16411            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16412            // perform the dispatching. The iterator is a safe guard against listeners that
16413            // could mutate the list by calling the various add/remove methods. This prevents
16414            // the array from being modified while we iterate it.
16415            for (OnAttachStateChangeListener listener : listeners) {
16416                listener.onViewAttachedToWindow(this);
16417            }
16418        }
16419
16420        int vis = info.mWindowVisibility;
16421        if (vis != GONE) {
16422            onWindowVisibilityChanged(vis);
16423            if (isShown()) {
16424                // Calling onVisibilityAggregated directly here since the subtree will also
16425                // receive dispatchAttachedToWindow and this same call
16426                onVisibilityAggregated(vis == VISIBLE);
16427            }
16428        }
16429
16430        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
16431        // As all views in the subtree will already receive dispatchAttachedToWindow
16432        // traversing the subtree again here is not desired.
16433        onVisibilityChanged(this, visibility);
16434
16435        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
16436            // If nobody has evaluated the drawable state yet, then do it now.
16437            refreshDrawableState();
16438        }
16439        needGlobalAttributesUpdate(false);
16440    }
16441
16442    void dispatchDetachedFromWindow() {
16443        AttachInfo info = mAttachInfo;
16444        if (info != null) {
16445            int vis = info.mWindowVisibility;
16446            if (vis != GONE) {
16447                onWindowVisibilityChanged(GONE);
16448                if (isShown()) {
16449                    // Invoking onVisibilityAggregated directly here since the subtree
16450                    // will also receive detached from window
16451                    onVisibilityAggregated(false);
16452                }
16453            }
16454        }
16455
16456        onDetachedFromWindow();
16457        onDetachedFromWindowInternal();
16458
16459        InputMethodManager imm = InputMethodManager.peekInstance();
16460        if (imm != null) {
16461            imm.onViewDetachedFromWindow(this);
16462        }
16463
16464        ListenerInfo li = mListenerInfo;
16465        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16466                li != null ? li.mOnAttachStateChangeListeners : null;
16467        if (listeners != null && listeners.size() > 0) {
16468            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16469            // perform the dispatching. The iterator is a safe guard against listeners that
16470            // could mutate the list by calling the various add/remove methods. This prevents
16471            // the array from being modified while we iterate it.
16472            for (OnAttachStateChangeListener listener : listeners) {
16473                listener.onViewDetachedFromWindow(this);
16474            }
16475        }
16476
16477        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
16478            mAttachInfo.mScrollContainers.remove(this);
16479            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
16480        }
16481
16482        mAttachInfo = null;
16483        if (mOverlay != null) {
16484            mOverlay.getOverlayView().dispatchDetachedFromWindow();
16485        }
16486    }
16487
16488    /**
16489     * Cancel any deferred high-level input events that were previously posted to the event queue.
16490     *
16491     * <p>Many views post high-level events such as click handlers to the event queue
16492     * to run deferred in order to preserve a desired user experience - clearing visible
16493     * pressed states before executing, etc. This method will abort any events of this nature
16494     * that are currently in flight.</p>
16495     *
16496     * <p>Custom views that generate their own high-level deferred input events should override
16497     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
16498     *
16499     * <p>This will also cancel pending input events for any child views.</p>
16500     *
16501     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
16502     * This will not impact newer events posted after this call that may occur as a result of
16503     * lower-level input events still waiting in the queue. If you are trying to prevent
16504     * double-submitted  events for the duration of some sort of asynchronous transaction
16505     * you should also take other steps to protect against unexpected double inputs e.g. calling
16506     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
16507     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
16508     */
16509    public final void cancelPendingInputEvents() {
16510        dispatchCancelPendingInputEvents();
16511    }
16512
16513    /**
16514     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
16515     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
16516     */
16517    void dispatchCancelPendingInputEvents() {
16518        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
16519        onCancelPendingInputEvents();
16520        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
16521            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
16522                    " did not call through to super.onCancelPendingInputEvents()");
16523        }
16524    }
16525
16526    /**
16527     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
16528     * a parent view.
16529     *
16530     * <p>This method is responsible for removing any pending high-level input events that were
16531     * posted to the event queue to run later. Custom view classes that post their own deferred
16532     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
16533     * {@link android.os.Handler} should override this method, call
16534     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
16535     * </p>
16536     */
16537    public void onCancelPendingInputEvents() {
16538        removePerformClickCallback();
16539        cancelLongPress();
16540        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
16541    }
16542
16543    /**
16544     * Store this view hierarchy's frozen state into the given container.
16545     *
16546     * @param container The SparseArray in which to save the view's state.
16547     *
16548     * @see #restoreHierarchyState(android.util.SparseArray)
16549     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16550     * @see #onSaveInstanceState()
16551     */
16552    public void saveHierarchyState(SparseArray<Parcelable> container) {
16553        dispatchSaveInstanceState(container);
16554    }
16555
16556    /**
16557     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
16558     * this view and its children. May be overridden to modify how freezing happens to a
16559     * view's children; for example, some views may want to not store state for their children.
16560     *
16561     * @param container The SparseArray in which to save the view's state.
16562     *
16563     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16564     * @see #saveHierarchyState(android.util.SparseArray)
16565     * @see #onSaveInstanceState()
16566     */
16567    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
16568        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
16569            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16570            Parcelable state = onSaveInstanceState();
16571            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16572                throw new IllegalStateException(
16573                        "Derived class did not call super.onSaveInstanceState()");
16574            }
16575            if (state != null) {
16576                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
16577                // + ": " + state);
16578                container.put(mID, state);
16579            }
16580        }
16581    }
16582
16583    /**
16584     * Hook allowing a view to generate a representation of its internal state
16585     * that can later be used to create a new instance with that same state.
16586     * This state should only contain information that is not persistent or can
16587     * not be reconstructed later. For example, you will never store your
16588     * current position on screen because that will be computed again when a
16589     * new instance of the view is placed in its view hierarchy.
16590     * <p>
16591     * Some examples of things you may store here: the current cursor position
16592     * in a text view (but usually not the text itself since that is stored in a
16593     * content provider or other persistent storage), the currently selected
16594     * item in a list view.
16595     *
16596     * @return Returns a Parcelable object containing the view's current dynamic
16597     *         state, or null if there is nothing interesting to save. The
16598     *         default implementation returns null.
16599     * @see #onRestoreInstanceState(android.os.Parcelable)
16600     * @see #saveHierarchyState(android.util.SparseArray)
16601     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16602     * @see #setSaveEnabled(boolean)
16603     */
16604    @CallSuper
16605    protected Parcelable onSaveInstanceState() {
16606        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16607        if (mStartActivityRequestWho != null) {
16608            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
16609            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
16610            return state;
16611        }
16612        return BaseSavedState.EMPTY_STATE;
16613    }
16614
16615    /**
16616     * Restore this view hierarchy's frozen state from the given container.
16617     *
16618     * @param container The SparseArray which holds previously frozen states.
16619     *
16620     * @see #saveHierarchyState(android.util.SparseArray)
16621     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16622     * @see #onRestoreInstanceState(android.os.Parcelable)
16623     */
16624    public void restoreHierarchyState(SparseArray<Parcelable> container) {
16625        dispatchRestoreInstanceState(container);
16626    }
16627
16628    /**
16629     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
16630     * state for this view and its children. May be overridden to modify how restoring
16631     * happens to a view's children; for example, some views may want to not store state
16632     * for their children.
16633     *
16634     * @param container The SparseArray which holds previously saved state.
16635     *
16636     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16637     * @see #restoreHierarchyState(android.util.SparseArray)
16638     * @see #onRestoreInstanceState(android.os.Parcelable)
16639     */
16640    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
16641        if (mID != NO_ID) {
16642            Parcelable state = container.get(mID);
16643            if (state != null) {
16644                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
16645                // + ": " + state);
16646                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16647                onRestoreInstanceState(state);
16648                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16649                    throw new IllegalStateException(
16650                            "Derived class did not call super.onRestoreInstanceState()");
16651                }
16652            }
16653        }
16654    }
16655
16656    /**
16657     * Hook allowing a view to re-apply a representation of its internal state that had previously
16658     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
16659     * null state.
16660     *
16661     * @param state The frozen state that had previously been returned by
16662     *        {@link #onSaveInstanceState}.
16663     *
16664     * @see #onSaveInstanceState()
16665     * @see #restoreHierarchyState(android.util.SparseArray)
16666     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16667     */
16668    @CallSuper
16669    protected void onRestoreInstanceState(Parcelable state) {
16670        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16671        if (state != null && !(state instanceof AbsSavedState)) {
16672            throw new IllegalArgumentException("Wrong state class, expecting View State but "
16673                    + "received " + state.getClass().toString() + " instead. This usually happens "
16674                    + "when two views of different type have the same id in the same hierarchy. "
16675                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
16676                    + "other views do not use the same id.");
16677        }
16678        if (state != null && state instanceof BaseSavedState) {
16679            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
16680        }
16681    }
16682
16683    /**
16684     * <p>Return the time at which the drawing of the view hierarchy started.</p>
16685     *
16686     * @return the drawing start time in milliseconds
16687     */
16688    public long getDrawingTime() {
16689        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
16690    }
16691
16692    /**
16693     * <p>Enables or disables the duplication of the parent's state into this view. When
16694     * duplication is enabled, this view gets its drawable state from its parent rather
16695     * than from its own internal properties.</p>
16696     *
16697     * <p>Note: in the current implementation, setting this property to true after the
16698     * view was added to a ViewGroup might have no effect at all. This property should
16699     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
16700     *
16701     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
16702     * property is enabled, an exception will be thrown.</p>
16703     *
16704     * <p>Note: if the child view uses and updates additional states which are unknown to the
16705     * parent, these states should not be affected by this method.</p>
16706     *
16707     * @param enabled True to enable duplication of the parent's drawable state, false
16708     *                to disable it.
16709     *
16710     * @see #getDrawableState()
16711     * @see #isDuplicateParentStateEnabled()
16712     */
16713    public void setDuplicateParentStateEnabled(boolean enabled) {
16714        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
16715    }
16716
16717    /**
16718     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
16719     *
16720     * @return True if this view's drawable state is duplicated from the parent,
16721     *         false otherwise
16722     *
16723     * @see #getDrawableState()
16724     * @see #setDuplicateParentStateEnabled(boolean)
16725     */
16726    public boolean isDuplicateParentStateEnabled() {
16727        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
16728    }
16729
16730    /**
16731     * <p>Specifies the type of layer backing this view. The layer can be
16732     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16733     * {@link #LAYER_TYPE_HARDWARE}.</p>
16734     *
16735     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16736     * instance that controls how the layer is composed on screen. The following
16737     * properties of the paint are taken into account when composing the layer:</p>
16738     * <ul>
16739     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16740     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16741     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16742     * </ul>
16743     *
16744     * <p>If this view has an alpha value set to < 1.0 by calling
16745     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
16746     * by this view's alpha value.</p>
16747     *
16748     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
16749     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
16750     * for more information on when and how to use layers.</p>
16751     *
16752     * @param layerType The type of layer to use with this view, must be one of
16753     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16754     *        {@link #LAYER_TYPE_HARDWARE}
16755     * @param paint The paint used to compose the layer. This argument is optional
16756     *        and can be null. It is ignored when the layer type is
16757     *        {@link #LAYER_TYPE_NONE}
16758     *
16759     * @see #getLayerType()
16760     * @see #LAYER_TYPE_NONE
16761     * @see #LAYER_TYPE_SOFTWARE
16762     * @see #LAYER_TYPE_HARDWARE
16763     * @see #setAlpha(float)
16764     *
16765     * @attr ref android.R.styleable#View_layerType
16766     */
16767    public void setLayerType(int layerType, @Nullable Paint paint) {
16768        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
16769            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
16770                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
16771        }
16772
16773        boolean typeChanged = mRenderNode.setLayerType(layerType);
16774
16775        if (!typeChanged) {
16776            setLayerPaint(paint);
16777            return;
16778        }
16779
16780        if (layerType != LAYER_TYPE_SOFTWARE) {
16781            // Destroy any previous software drawing cache if present
16782            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
16783            // drawing cache created in View#draw when drawing to a SW canvas.
16784            destroyDrawingCache();
16785        }
16786
16787        mLayerType = layerType;
16788        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
16789        mRenderNode.setLayerPaint(mLayerPaint);
16790
16791        // draw() behaves differently if we are on a layer, so we need to
16792        // invalidate() here
16793        invalidateParentCaches();
16794        invalidate(true);
16795    }
16796
16797    /**
16798     * Updates the {@link Paint} object used with the current layer (used only if the current
16799     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
16800     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
16801     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
16802     * ensure that the view gets redrawn immediately.
16803     *
16804     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16805     * instance that controls how the layer is composed on screen. The following
16806     * properties of the paint are taken into account when composing the layer:</p>
16807     * <ul>
16808     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16809     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16810     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16811     * </ul>
16812     *
16813     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
16814     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
16815     *
16816     * @param paint The paint used to compose the layer. This argument is optional
16817     *        and can be null. It is ignored when the layer type is
16818     *        {@link #LAYER_TYPE_NONE}
16819     *
16820     * @see #setLayerType(int, android.graphics.Paint)
16821     */
16822    public void setLayerPaint(@Nullable Paint paint) {
16823        int layerType = getLayerType();
16824        if (layerType != LAYER_TYPE_NONE) {
16825            mLayerPaint = paint;
16826            if (layerType == LAYER_TYPE_HARDWARE) {
16827                if (mRenderNode.setLayerPaint(paint)) {
16828                    invalidateViewProperty(false, false);
16829                }
16830            } else {
16831                invalidate();
16832            }
16833        }
16834    }
16835
16836    /**
16837     * Indicates what type of layer is currently associated with this view. By default
16838     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
16839     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
16840     * for more information on the different types of layers.
16841     *
16842     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16843     *         {@link #LAYER_TYPE_HARDWARE}
16844     *
16845     * @see #setLayerType(int, android.graphics.Paint)
16846     * @see #buildLayer()
16847     * @see #LAYER_TYPE_NONE
16848     * @see #LAYER_TYPE_SOFTWARE
16849     * @see #LAYER_TYPE_HARDWARE
16850     */
16851    public int getLayerType() {
16852        return mLayerType;
16853    }
16854
16855    /**
16856     * Forces this view's layer to be created and this view to be rendered
16857     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
16858     * invoking this method will have no effect.
16859     *
16860     * This method can for instance be used to render a view into its layer before
16861     * starting an animation. If this view is complex, rendering into the layer
16862     * before starting the animation will avoid skipping frames.
16863     *
16864     * @throws IllegalStateException If this view is not attached to a window
16865     *
16866     * @see #setLayerType(int, android.graphics.Paint)
16867     */
16868    public void buildLayer() {
16869        if (mLayerType == LAYER_TYPE_NONE) return;
16870
16871        final AttachInfo attachInfo = mAttachInfo;
16872        if (attachInfo == null) {
16873            throw new IllegalStateException("This view must be attached to a window first");
16874        }
16875
16876        if (getWidth() == 0 || getHeight() == 0) {
16877            return;
16878        }
16879
16880        switch (mLayerType) {
16881            case LAYER_TYPE_HARDWARE:
16882                updateDisplayListIfDirty();
16883                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
16884                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
16885                }
16886                break;
16887            case LAYER_TYPE_SOFTWARE:
16888                buildDrawingCache(true);
16889                break;
16890        }
16891    }
16892
16893    /**
16894     * Destroys all hardware rendering resources. This method is invoked
16895     * when the system needs to reclaim resources. Upon execution of this
16896     * method, you should free any OpenGL resources created by the view.
16897     *
16898     * Note: you <strong>must</strong> call
16899     * <code>super.destroyHardwareResources()</code> when overriding
16900     * this method.
16901     *
16902     * @hide
16903     */
16904    @CallSuper
16905    protected void destroyHardwareResources() {
16906        if (mOverlay != null) {
16907            mOverlay.getOverlayView().destroyHardwareResources();
16908        }
16909        if (mGhostView != null) {
16910            mGhostView.destroyHardwareResources();
16911        }
16912    }
16913
16914    /**
16915     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16916     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16917     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16918     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16919     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16920     * null.</p>
16921     *
16922     * <p>Enabling the drawing cache is similar to
16923     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16924     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16925     * drawing cache has no effect on rendering because the system uses a different mechanism
16926     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16927     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16928     * for information on how to enable software and hardware layers.</p>
16929     *
16930     * <p>This API can be used to manually generate
16931     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16932     * {@link #getDrawingCache()}.</p>
16933     *
16934     * @param enabled true to enable the drawing cache, false otherwise
16935     *
16936     * @see #isDrawingCacheEnabled()
16937     * @see #getDrawingCache()
16938     * @see #buildDrawingCache()
16939     * @see #setLayerType(int, android.graphics.Paint)
16940     */
16941    public void setDrawingCacheEnabled(boolean enabled) {
16942        mCachingFailed = false;
16943        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16944    }
16945
16946    /**
16947     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16948     *
16949     * @return true if the drawing cache is enabled
16950     *
16951     * @see #setDrawingCacheEnabled(boolean)
16952     * @see #getDrawingCache()
16953     */
16954    @ViewDebug.ExportedProperty(category = "drawing")
16955    public boolean isDrawingCacheEnabled() {
16956        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16957    }
16958
16959    /**
16960     * Debugging utility which recursively outputs the dirty state of a view and its
16961     * descendants.
16962     *
16963     * @hide
16964     */
16965    @SuppressWarnings({"UnusedDeclaration"})
16966    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16967        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16968                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16969                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16970                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16971        if (clear) {
16972            mPrivateFlags &= clearMask;
16973        }
16974        if (this instanceof ViewGroup) {
16975            ViewGroup parent = (ViewGroup) this;
16976            final int count = parent.getChildCount();
16977            for (int i = 0; i < count; i++) {
16978                final View child = parent.getChildAt(i);
16979                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16980            }
16981        }
16982    }
16983
16984    /**
16985     * This method is used by ViewGroup to cause its children to restore or recreate their
16986     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16987     * to recreate its own display list, which would happen if it went through the normal
16988     * draw/dispatchDraw mechanisms.
16989     *
16990     * @hide
16991     */
16992    protected void dispatchGetDisplayList() {}
16993
16994    /**
16995     * A view that is not attached or hardware accelerated cannot create a display list.
16996     * This method checks these conditions and returns the appropriate result.
16997     *
16998     * @return true if view has the ability to create a display list, false otherwise.
16999     *
17000     * @hide
17001     */
17002    public boolean canHaveDisplayList() {
17003        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
17004    }
17005
17006    /**
17007     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
17008     * @hide
17009     */
17010    @NonNull
17011    public RenderNode updateDisplayListIfDirty() {
17012        final RenderNode renderNode = mRenderNode;
17013        if (!canHaveDisplayList()) {
17014            // can't populate RenderNode, don't try
17015            return renderNode;
17016        }
17017
17018        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
17019                || !renderNode.isValid()
17020                || (mRecreateDisplayList)) {
17021            // Don't need to recreate the display list, just need to tell our
17022            // children to restore/recreate theirs
17023            if (renderNode.isValid()
17024                    && !mRecreateDisplayList) {
17025                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17026                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17027                dispatchGetDisplayList();
17028
17029                return renderNode; // no work needed
17030            }
17031
17032            // If we got here, we're recreating it. Mark it as such to ensure that
17033            // we copy in child display lists into ours in drawChild()
17034            mRecreateDisplayList = true;
17035
17036            int width = mRight - mLeft;
17037            int height = mBottom - mTop;
17038            int layerType = getLayerType();
17039
17040            final DisplayListCanvas canvas = renderNode.start(width, height);
17041            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
17042
17043            try {
17044                if (layerType == LAYER_TYPE_SOFTWARE) {
17045                    buildDrawingCache(true);
17046                    Bitmap cache = getDrawingCache(true);
17047                    if (cache != null) {
17048                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
17049                    }
17050                } else {
17051                    computeScroll();
17052
17053                    canvas.translate(-mScrollX, -mScrollY);
17054                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17055                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17056
17057                    // Fast path for layouts with no backgrounds
17058                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17059                        dispatchDraw(canvas);
17060                        if (mOverlay != null && !mOverlay.isEmpty()) {
17061                            mOverlay.getOverlayView().draw(canvas);
17062                        }
17063                        if (debugDraw()) {
17064                            debugDrawFocus(canvas);
17065                        }
17066                    } else {
17067                        draw(canvas);
17068                    }
17069                }
17070            } finally {
17071                renderNode.end(canvas);
17072                setDisplayListProperties(renderNode);
17073            }
17074        } else {
17075            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17076            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17077        }
17078        return renderNode;
17079    }
17080
17081    private void resetDisplayList() {
17082        mRenderNode.discardDisplayList();
17083        if (mBackgroundRenderNode != null) {
17084            mBackgroundRenderNode.discardDisplayList();
17085        }
17086    }
17087
17088    /**
17089     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
17090     *
17091     * @return A non-scaled bitmap representing this view or null if cache is disabled.
17092     *
17093     * @see #getDrawingCache(boolean)
17094     */
17095    public Bitmap getDrawingCache() {
17096        return getDrawingCache(false);
17097    }
17098
17099    /**
17100     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
17101     * is null when caching is disabled. If caching is enabled and the cache is not ready,
17102     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
17103     * draw from the cache when the cache is enabled. To benefit from the cache, you must
17104     * request the drawing cache by calling this method and draw it on screen if the
17105     * returned bitmap is not null.</p>
17106     *
17107     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17108     * this method will create a bitmap of the same size as this view. Because this bitmap
17109     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17110     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17111     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17112     * size than the view. This implies that your application must be able to handle this
17113     * size.</p>
17114     *
17115     * @param autoScale Indicates whether the generated bitmap should be scaled based on
17116     *        the current density of the screen when the application is in compatibility
17117     *        mode.
17118     *
17119     * @return A bitmap representing this view or null if cache is disabled.
17120     *
17121     * @see #setDrawingCacheEnabled(boolean)
17122     * @see #isDrawingCacheEnabled()
17123     * @see #buildDrawingCache(boolean)
17124     * @see #destroyDrawingCache()
17125     */
17126    public Bitmap getDrawingCache(boolean autoScale) {
17127        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
17128            return null;
17129        }
17130        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
17131            buildDrawingCache(autoScale);
17132        }
17133        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
17134    }
17135
17136    /**
17137     * <p>Frees the resources used by the drawing cache. If you call
17138     * {@link #buildDrawingCache()} manually without calling
17139     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17140     * should cleanup the cache with this method afterwards.</p>
17141     *
17142     * @see #setDrawingCacheEnabled(boolean)
17143     * @see #buildDrawingCache()
17144     * @see #getDrawingCache()
17145     */
17146    public void destroyDrawingCache() {
17147        if (mDrawingCache != null) {
17148            mDrawingCache.recycle();
17149            mDrawingCache = null;
17150        }
17151        if (mUnscaledDrawingCache != null) {
17152            mUnscaledDrawingCache.recycle();
17153            mUnscaledDrawingCache = null;
17154        }
17155    }
17156
17157    /**
17158     * Setting a solid background color for the drawing cache's bitmaps will improve
17159     * performance and memory usage. Note, though that this should only be used if this
17160     * view will always be drawn on top of a solid color.
17161     *
17162     * @param color The background color to use for the drawing cache's bitmap
17163     *
17164     * @see #setDrawingCacheEnabled(boolean)
17165     * @see #buildDrawingCache()
17166     * @see #getDrawingCache()
17167     */
17168    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
17169        if (color != mDrawingCacheBackgroundColor) {
17170            mDrawingCacheBackgroundColor = color;
17171            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
17172        }
17173    }
17174
17175    /**
17176     * @see #setDrawingCacheBackgroundColor(int)
17177     *
17178     * @return The background color to used for the drawing cache's bitmap
17179     */
17180    @ColorInt
17181    public int getDrawingCacheBackgroundColor() {
17182        return mDrawingCacheBackgroundColor;
17183    }
17184
17185    /**
17186     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
17187     *
17188     * @see #buildDrawingCache(boolean)
17189     */
17190    public void buildDrawingCache() {
17191        buildDrawingCache(false);
17192    }
17193
17194    /**
17195     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
17196     *
17197     * <p>If you call {@link #buildDrawingCache()} manually without calling
17198     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17199     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
17200     *
17201     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17202     * this method will create a bitmap of the same size as this view. Because this bitmap
17203     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17204     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17205     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17206     * size than the view. This implies that your application must be able to handle this
17207     * size.</p>
17208     *
17209     * <p>You should avoid calling this method when hardware acceleration is enabled. If
17210     * you do not need the drawing cache bitmap, calling this method will increase memory
17211     * usage and cause the view to be rendered in software once, thus negatively impacting
17212     * performance.</p>
17213     *
17214     * @see #getDrawingCache()
17215     * @see #destroyDrawingCache()
17216     */
17217    public void buildDrawingCache(boolean autoScale) {
17218        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
17219                mDrawingCache == null : mUnscaledDrawingCache == null)) {
17220            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
17221                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
17222                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
17223            }
17224            try {
17225                buildDrawingCacheImpl(autoScale);
17226            } finally {
17227                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
17228            }
17229        }
17230    }
17231
17232    /**
17233     * private, internal implementation of buildDrawingCache, used to enable tracing
17234     */
17235    private void buildDrawingCacheImpl(boolean autoScale) {
17236        mCachingFailed = false;
17237
17238        int width = mRight - mLeft;
17239        int height = mBottom - mTop;
17240
17241        final AttachInfo attachInfo = mAttachInfo;
17242        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
17243
17244        if (autoScale && scalingRequired) {
17245            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
17246            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
17247        }
17248
17249        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
17250        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
17251        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
17252
17253        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
17254        final long drawingCacheSize =
17255                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
17256        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
17257            if (width > 0 && height > 0) {
17258                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
17259                        + " too large to fit into a software layer (or drawing cache), needs "
17260                        + projectedBitmapSize + " bytes, only "
17261                        + drawingCacheSize + " available");
17262            }
17263            destroyDrawingCache();
17264            mCachingFailed = true;
17265            return;
17266        }
17267
17268        boolean clear = true;
17269        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
17270
17271        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
17272            Bitmap.Config quality;
17273            if (!opaque) {
17274                // Never pick ARGB_4444 because it looks awful
17275                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
17276                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
17277                    case DRAWING_CACHE_QUALITY_AUTO:
17278                    case DRAWING_CACHE_QUALITY_LOW:
17279                    case DRAWING_CACHE_QUALITY_HIGH:
17280                    default:
17281                        quality = Bitmap.Config.ARGB_8888;
17282                        break;
17283                }
17284            } else {
17285                // Optimization for translucent windows
17286                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
17287                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
17288            }
17289
17290            // Try to cleanup memory
17291            if (bitmap != null) bitmap.recycle();
17292
17293            try {
17294                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17295                        width, height, quality);
17296                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
17297                if (autoScale) {
17298                    mDrawingCache = bitmap;
17299                } else {
17300                    mUnscaledDrawingCache = bitmap;
17301                }
17302                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
17303            } catch (OutOfMemoryError e) {
17304                // If there is not enough memory to create the bitmap cache, just
17305                // ignore the issue as bitmap caches are not required to draw the
17306                // view hierarchy
17307                if (autoScale) {
17308                    mDrawingCache = null;
17309                } else {
17310                    mUnscaledDrawingCache = null;
17311                }
17312                mCachingFailed = true;
17313                return;
17314            }
17315
17316            clear = drawingCacheBackgroundColor != 0;
17317        }
17318
17319        Canvas canvas;
17320        if (attachInfo != null) {
17321            canvas = attachInfo.mCanvas;
17322            if (canvas == null) {
17323                canvas = new Canvas();
17324            }
17325            canvas.setBitmap(bitmap);
17326            // Temporarily clobber the cached Canvas in case one of our children
17327            // is also using a drawing cache. Without this, the children would
17328            // steal the canvas by attaching their own bitmap to it and bad, bad
17329            // thing would happen (invisible views, corrupted drawings, etc.)
17330            attachInfo.mCanvas = null;
17331        } else {
17332            // This case should hopefully never or seldom happen
17333            canvas = new Canvas(bitmap);
17334        }
17335
17336        if (clear) {
17337            bitmap.eraseColor(drawingCacheBackgroundColor);
17338        }
17339
17340        computeScroll();
17341        final int restoreCount = canvas.save();
17342
17343        if (autoScale && scalingRequired) {
17344            final float scale = attachInfo.mApplicationScale;
17345            canvas.scale(scale, scale);
17346        }
17347
17348        canvas.translate(-mScrollX, -mScrollY);
17349
17350        mPrivateFlags |= PFLAG_DRAWN;
17351        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
17352                mLayerType != LAYER_TYPE_NONE) {
17353            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
17354        }
17355
17356        // Fast path for layouts with no backgrounds
17357        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17358            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17359            dispatchDraw(canvas);
17360            if (mOverlay != null && !mOverlay.isEmpty()) {
17361                mOverlay.getOverlayView().draw(canvas);
17362            }
17363        } else {
17364            draw(canvas);
17365        }
17366
17367        canvas.restoreToCount(restoreCount);
17368        canvas.setBitmap(null);
17369
17370        if (attachInfo != null) {
17371            // Restore the cached Canvas for our siblings
17372            attachInfo.mCanvas = canvas;
17373        }
17374    }
17375
17376    /**
17377     * Create a snapshot of the view into a bitmap.  We should probably make
17378     * some form of this public, but should think about the API.
17379     *
17380     * @hide
17381     */
17382    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
17383        int width = mRight - mLeft;
17384        int height = mBottom - mTop;
17385
17386        final AttachInfo attachInfo = mAttachInfo;
17387        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
17388        width = (int) ((width * scale) + 0.5f);
17389        height = (int) ((height * scale) + 0.5f);
17390
17391        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17392                width > 0 ? width : 1, height > 0 ? height : 1, quality);
17393        if (bitmap == null) {
17394            throw new OutOfMemoryError();
17395        }
17396
17397        Resources resources = getResources();
17398        if (resources != null) {
17399            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
17400        }
17401
17402        Canvas canvas;
17403        if (attachInfo != null) {
17404            canvas = attachInfo.mCanvas;
17405            if (canvas == null) {
17406                canvas = new Canvas();
17407            }
17408            canvas.setBitmap(bitmap);
17409            // Temporarily clobber the cached Canvas in case one of our children
17410            // is also using a drawing cache. Without this, the children would
17411            // steal the canvas by attaching their own bitmap to it and bad, bad
17412            // things would happen (invisible views, corrupted drawings, etc.)
17413            attachInfo.mCanvas = null;
17414        } else {
17415            // This case should hopefully never or seldom happen
17416            canvas = new Canvas(bitmap);
17417        }
17418
17419        if ((backgroundColor & 0xff000000) != 0) {
17420            bitmap.eraseColor(backgroundColor);
17421        }
17422
17423        computeScroll();
17424        final int restoreCount = canvas.save();
17425        canvas.scale(scale, scale);
17426        canvas.translate(-mScrollX, -mScrollY);
17427
17428        // Temporarily remove the dirty mask
17429        int flags = mPrivateFlags;
17430        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17431
17432        // Fast path for layouts with no backgrounds
17433        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17434            dispatchDraw(canvas);
17435            if (mOverlay != null && !mOverlay.isEmpty()) {
17436                mOverlay.getOverlayView().draw(canvas);
17437            }
17438        } else {
17439            draw(canvas);
17440        }
17441
17442        mPrivateFlags = flags;
17443
17444        canvas.restoreToCount(restoreCount);
17445        canvas.setBitmap(null);
17446
17447        if (attachInfo != null) {
17448            // Restore the cached Canvas for our siblings
17449            attachInfo.mCanvas = canvas;
17450        }
17451
17452        return bitmap;
17453    }
17454
17455    /**
17456     * Indicates whether this View is currently in edit mode. A View is usually
17457     * in edit mode when displayed within a developer tool. For instance, if
17458     * this View is being drawn by a visual user interface builder, this method
17459     * should return true.
17460     *
17461     * Subclasses should check the return value of this method to provide
17462     * different behaviors if their normal behavior might interfere with the
17463     * host environment. For instance: the class spawns a thread in its
17464     * constructor, the drawing code relies on device-specific features, etc.
17465     *
17466     * This method is usually checked in the drawing code of custom widgets.
17467     *
17468     * @return True if this View is in edit mode, false otherwise.
17469     */
17470    public boolean isInEditMode() {
17471        return false;
17472    }
17473
17474    /**
17475     * If the View draws content inside its padding and enables fading edges,
17476     * it needs to support padding offsets. Padding offsets are added to the
17477     * fading edges to extend the length of the fade so that it covers pixels
17478     * drawn inside the padding.
17479     *
17480     * Subclasses of this class should override this method if they need
17481     * to draw content inside the padding.
17482     *
17483     * @return True if padding offset must be applied, false otherwise.
17484     *
17485     * @see #getLeftPaddingOffset()
17486     * @see #getRightPaddingOffset()
17487     * @see #getTopPaddingOffset()
17488     * @see #getBottomPaddingOffset()
17489     *
17490     * @since CURRENT
17491     */
17492    protected boolean isPaddingOffsetRequired() {
17493        return false;
17494    }
17495
17496    /**
17497     * Amount by which to extend the left fading region. Called only when
17498     * {@link #isPaddingOffsetRequired()} returns true.
17499     *
17500     * @return The left padding offset in pixels.
17501     *
17502     * @see #isPaddingOffsetRequired()
17503     *
17504     * @since CURRENT
17505     */
17506    protected int getLeftPaddingOffset() {
17507        return 0;
17508    }
17509
17510    /**
17511     * Amount by which to extend the right fading region. Called only when
17512     * {@link #isPaddingOffsetRequired()} returns true.
17513     *
17514     * @return The right padding offset in pixels.
17515     *
17516     * @see #isPaddingOffsetRequired()
17517     *
17518     * @since CURRENT
17519     */
17520    protected int getRightPaddingOffset() {
17521        return 0;
17522    }
17523
17524    /**
17525     * Amount by which to extend the top fading region. Called only when
17526     * {@link #isPaddingOffsetRequired()} returns true.
17527     *
17528     * @return The top padding offset in pixels.
17529     *
17530     * @see #isPaddingOffsetRequired()
17531     *
17532     * @since CURRENT
17533     */
17534    protected int getTopPaddingOffset() {
17535        return 0;
17536    }
17537
17538    /**
17539     * Amount by which to extend the bottom fading region. Called only when
17540     * {@link #isPaddingOffsetRequired()} returns true.
17541     *
17542     * @return The bottom padding offset in pixels.
17543     *
17544     * @see #isPaddingOffsetRequired()
17545     *
17546     * @since CURRENT
17547     */
17548    protected int getBottomPaddingOffset() {
17549        return 0;
17550    }
17551
17552    /**
17553     * @hide
17554     * @param offsetRequired
17555     */
17556    protected int getFadeTop(boolean offsetRequired) {
17557        int top = mPaddingTop;
17558        if (offsetRequired) top += getTopPaddingOffset();
17559        return top;
17560    }
17561
17562    /**
17563     * @hide
17564     * @param offsetRequired
17565     */
17566    protected int getFadeHeight(boolean offsetRequired) {
17567        int padding = mPaddingTop;
17568        if (offsetRequired) padding += getTopPaddingOffset();
17569        return mBottom - mTop - mPaddingBottom - padding;
17570    }
17571
17572    /**
17573     * <p>Indicates whether this view is attached to a hardware accelerated
17574     * window or not.</p>
17575     *
17576     * <p>Even if this method returns true, it does not mean that every call
17577     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
17578     * accelerated {@link android.graphics.Canvas}. For instance, if this view
17579     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
17580     * window is hardware accelerated,
17581     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
17582     * return false, and this method will return true.</p>
17583     *
17584     * @return True if the view is attached to a window and the window is
17585     *         hardware accelerated; false in any other case.
17586     */
17587    @ViewDebug.ExportedProperty(category = "drawing")
17588    public boolean isHardwareAccelerated() {
17589        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
17590    }
17591
17592    /**
17593     * Sets a rectangular area on this view to which the view will be clipped
17594     * when it is drawn. Setting the value to null will remove the clip bounds
17595     * and the view will draw normally, using its full bounds.
17596     *
17597     * @param clipBounds The rectangular area, in the local coordinates of
17598     * this view, to which future drawing operations will be clipped.
17599     */
17600    public void setClipBounds(Rect clipBounds) {
17601        if (clipBounds == mClipBounds
17602                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
17603            return;
17604        }
17605        if (clipBounds != null) {
17606            if (mClipBounds == null) {
17607                mClipBounds = new Rect(clipBounds);
17608            } else {
17609                mClipBounds.set(clipBounds);
17610            }
17611        } else {
17612            mClipBounds = null;
17613        }
17614        mRenderNode.setClipBounds(mClipBounds);
17615        invalidateViewProperty(false, false);
17616    }
17617
17618    /**
17619     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
17620     *
17621     * @return A copy of the current clip bounds if clip bounds are set,
17622     * otherwise null.
17623     */
17624    public Rect getClipBounds() {
17625        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
17626    }
17627
17628
17629    /**
17630     * Populates an output rectangle with the clip bounds of the view,
17631     * returning {@code true} if successful or {@code false} if the view's
17632     * clip bounds are {@code null}.
17633     *
17634     * @param outRect rectangle in which to place the clip bounds of the view
17635     * @return {@code true} if successful or {@code false} if the view's
17636     *         clip bounds are {@code null}
17637     */
17638    public boolean getClipBounds(Rect outRect) {
17639        if (mClipBounds != null) {
17640            outRect.set(mClipBounds);
17641            return true;
17642        }
17643        return false;
17644    }
17645
17646    /**
17647     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
17648     * case of an active Animation being run on the view.
17649     */
17650    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
17651            Animation a, boolean scalingRequired) {
17652        Transformation invalidationTransform;
17653        final int flags = parent.mGroupFlags;
17654        final boolean initialized = a.isInitialized();
17655        if (!initialized) {
17656            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
17657            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
17658            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
17659            onAnimationStart();
17660        }
17661
17662        final Transformation t = parent.getChildTransformation();
17663        boolean more = a.getTransformation(drawingTime, t, 1f);
17664        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
17665            if (parent.mInvalidationTransformation == null) {
17666                parent.mInvalidationTransformation = new Transformation();
17667            }
17668            invalidationTransform = parent.mInvalidationTransformation;
17669            a.getTransformation(drawingTime, invalidationTransform, 1f);
17670        } else {
17671            invalidationTransform = t;
17672        }
17673
17674        if (more) {
17675            if (!a.willChangeBounds()) {
17676                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
17677                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
17678                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
17679                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
17680                    // The child need to draw an animation, potentially offscreen, so
17681                    // make sure we do not cancel invalidate requests
17682                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17683                    parent.invalidate(mLeft, mTop, mRight, mBottom);
17684                }
17685            } else {
17686                if (parent.mInvalidateRegion == null) {
17687                    parent.mInvalidateRegion = new RectF();
17688                }
17689                final RectF region = parent.mInvalidateRegion;
17690                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
17691                        invalidationTransform);
17692
17693                // The child need to draw an animation, potentially offscreen, so
17694                // make sure we do not cancel invalidate requests
17695                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17696
17697                final int left = mLeft + (int) region.left;
17698                final int top = mTop + (int) region.top;
17699                parent.invalidate(left, top, left + (int) (region.width() + .5f),
17700                        top + (int) (region.height() + .5f));
17701            }
17702        }
17703        return more;
17704    }
17705
17706    /**
17707     * This method is called by getDisplayList() when a display list is recorded for a View.
17708     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
17709     */
17710    void setDisplayListProperties(RenderNode renderNode) {
17711        if (renderNode != null) {
17712            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
17713            renderNode.setClipToBounds(mParent instanceof ViewGroup
17714                    && ((ViewGroup) mParent).getClipChildren());
17715
17716            float alpha = 1;
17717            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
17718                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17719                ViewGroup parentVG = (ViewGroup) mParent;
17720                final Transformation t = parentVG.getChildTransformation();
17721                if (parentVG.getChildStaticTransformation(this, t)) {
17722                    final int transformType = t.getTransformationType();
17723                    if (transformType != Transformation.TYPE_IDENTITY) {
17724                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
17725                            alpha = t.getAlpha();
17726                        }
17727                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
17728                            renderNode.setStaticMatrix(t.getMatrix());
17729                        }
17730                    }
17731                }
17732            }
17733            if (mTransformationInfo != null) {
17734                alpha *= getFinalAlpha();
17735                if (alpha < 1) {
17736                    final int multipliedAlpha = (int) (255 * alpha);
17737                    if (onSetAlpha(multipliedAlpha)) {
17738                        alpha = 1;
17739                    }
17740                }
17741                renderNode.setAlpha(alpha);
17742            } else if (alpha < 1) {
17743                renderNode.setAlpha(alpha);
17744            }
17745        }
17746    }
17747
17748    /**
17749     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
17750     *
17751     * This is where the View specializes rendering behavior based on layer type,
17752     * and hardware acceleration.
17753     */
17754    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
17755        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
17756        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
17757         *
17758         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
17759         * HW accelerated, it can't handle drawing RenderNodes.
17760         */
17761        boolean drawingWithRenderNode = mAttachInfo != null
17762                && mAttachInfo.mHardwareAccelerated
17763                && hardwareAcceleratedCanvas;
17764
17765        boolean more = false;
17766        final boolean childHasIdentityMatrix = hasIdentityMatrix();
17767        final int parentFlags = parent.mGroupFlags;
17768
17769        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
17770            parent.getChildTransformation().clear();
17771            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17772        }
17773
17774        Transformation transformToApply = null;
17775        boolean concatMatrix = false;
17776        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
17777        final Animation a = getAnimation();
17778        if (a != null) {
17779            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
17780            concatMatrix = a.willChangeTransformationMatrix();
17781            if (concatMatrix) {
17782                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17783            }
17784            transformToApply = parent.getChildTransformation();
17785        } else {
17786            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
17787                // No longer animating: clear out old animation matrix
17788                mRenderNode.setAnimationMatrix(null);
17789                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17790            }
17791            if (!drawingWithRenderNode
17792                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17793                final Transformation t = parent.getChildTransformation();
17794                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
17795                if (hasTransform) {
17796                    final int transformType = t.getTransformationType();
17797                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
17798                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
17799                }
17800            }
17801        }
17802
17803        concatMatrix |= !childHasIdentityMatrix;
17804
17805        // Sets the flag as early as possible to allow draw() implementations
17806        // to call invalidate() successfully when doing animations
17807        mPrivateFlags |= PFLAG_DRAWN;
17808
17809        if (!concatMatrix &&
17810                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
17811                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
17812                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
17813                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
17814            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
17815            return more;
17816        }
17817        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
17818
17819        if (hardwareAcceleratedCanvas) {
17820            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
17821            // retain the flag's value temporarily in the mRecreateDisplayList flag
17822            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
17823            mPrivateFlags &= ~PFLAG_INVALIDATED;
17824        }
17825
17826        RenderNode renderNode = null;
17827        Bitmap cache = null;
17828        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
17829        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
17830             if (layerType != LAYER_TYPE_NONE) {
17831                 // If not drawing with RenderNode, treat HW layers as SW
17832                 layerType = LAYER_TYPE_SOFTWARE;
17833                 buildDrawingCache(true);
17834            }
17835            cache = getDrawingCache(true);
17836        }
17837
17838        if (drawingWithRenderNode) {
17839            // Delay getting the display list until animation-driven alpha values are
17840            // set up and possibly passed on to the view
17841            renderNode = updateDisplayListIfDirty();
17842            if (!renderNode.isValid()) {
17843                // Uncommon, but possible. If a view is removed from the hierarchy during the call
17844                // to getDisplayList(), the display list will be marked invalid and we should not
17845                // try to use it again.
17846                renderNode = null;
17847                drawingWithRenderNode = false;
17848            }
17849        }
17850
17851        int sx = 0;
17852        int sy = 0;
17853        if (!drawingWithRenderNode) {
17854            computeScroll();
17855            sx = mScrollX;
17856            sy = mScrollY;
17857        }
17858
17859        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
17860        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
17861
17862        int restoreTo = -1;
17863        if (!drawingWithRenderNode || transformToApply != null) {
17864            restoreTo = canvas.save();
17865        }
17866        if (offsetForScroll) {
17867            canvas.translate(mLeft - sx, mTop - sy);
17868        } else {
17869            if (!drawingWithRenderNode) {
17870                canvas.translate(mLeft, mTop);
17871            }
17872            if (scalingRequired) {
17873                if (drawingWithRenderNode) {
17874                    // TODO: Might not need this if we put everything inside the DL
17875                    restoreTo = canvas.save();
17876                }
17877                // mAttachInfo cannot be null, otherwise scalingRequired == false
17878                final float scale = 1.0f / mAttachInfo.mApplicationScale;
17879                canvas.scale(scale, scale);
17880            }
17881        }
17882
17883        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
17884        if (transformToApply != null
17885                || alpha < 1
17886                || !hasIdentityMatrix()
17887                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17888            if (transformToApply != null || !childHasIdentityMatrix) {
17889                int transX = 0;
17890                int transY = 0;
17891
17892                if (offsetForScroll) {
17893                    transX = -sx;
17894                    transY = -sy;
17895                }
17896
17897                if (transformToApply != null) {
17898                    if (concatMatrix) {
17899                        if (drawingWithRenderNode) {
17900                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17901                        } else {
17902                            // Undo the scroll translation, apply the transformation matrix,
17903                            // then redo the scroll translate to get the correct result.
17904                            canvas.translate(-transX, -transY);
17905                            canvas.concat(transformToApply.getMatrix());
17906                            canvas.translate(transX, transY);
17907                        }
17908                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17909                    }
17910
17911                    float transformAlpha = transformToApply.getAlpha();
17912                    if (transformAlpha < 1) {
17913                        alpha *= transformAlpha;
17914                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17915                    }
17916                }
17917
17918                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17919                    canvas.translate(-transX, -transY);
17920                    canvas.concat(getMatrix());
17921                    canvas.translate(transX, transY);
17922                }
17923            }
17924
17925            // Deal with alpha if it is or used to be <1
17926            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17927                if (alpha < 1) {
17928                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17929                } else {
17930                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17931                }
17932                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17933                if (!drawingWithDrawingCache) {
17934                    final int multipliedAlpha = (int) (255 * alpha);
17935                    if (!onSetAlpha(multipliedAlpha)) {
17936                        if (drawingWithRenderNode) {
17937                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17938                        } else if (layerType == LAYER_TYPE_NONE) {
17939                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17940                                    multipliedAlpha);
17941                        }
17942                    } else {
17943                        // Alpha is handled by the child directly, clobber the layer's alpha
17944                        mPrivateFlags |= PFLAG_ALPHA_SET;
17945                    }
17946                }
17947            }
17948        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17949            onSetAlpha(255);
17950            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17951        }
17952
17953        if (!drawingWithRenderNode) {
17954            // apply clips directly, since RenderNode won't do it for this draw
17955            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17956                if (offsetForScroll) {
17957                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17958                } else {
17959                    if (!scalingRequired || cache == null) {
17960                        canvas.clipRect(0, 0, getWidth(), getHeight());
17961                    } else {
17962                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17963                    }
17964                }
17965            }
17966
17967            if (mClipBounds != null) {
17968                // clip bounds ignore scroll
17969                canvas.clipRect(mClipBounds);
17970            }
17971        }
17972
17973        if (!drawingWithDrawingCache) {
17974            if (drawingWithRenderNode) {
17975                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17976                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17977            } else {
17978                // Fast path for layouts with no backgrounds
17979                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17980                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17981                    dispatchDraw(canvas);
17982                } else {
17983                    draw(canvas);
17984                }
17985            }
17986        } else if (cache != null) {
17987            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17988            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17989                // no layer paint, use temporary paint to draw bitmap
17990                Paint cachePaint = parent.mCachePaint;
17991                if (cachePaint == null) {
17992                    cachePaint = new Paint();
17993                    cachePaint.setDither(false);
17994                    parent.mCachePaint = cachePaint;
17995                }
17996                cachePaint.setAlpha((int) (alpha * 255));
17997                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17998            } else {
17999                // use layer paint to draw the bitmap, merging the two alphas, but also restore
18000                int layerPaintAlpha = mLayerPaint.getAlpha();
18001                if (alpha < 1) {
18002                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
18003                }
18004                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
18005                if (alpha < 1) {
18006                    mLayerPaint.setAlpha(layerPaintAlpha);
18007                }
18008            }
18009        }
18010
18011        if (restoreTo >= 0) {
18012            canvas.restoreToCount(restoreTo);
18013        }
18014
18015        if (a != null && !more) {
18016            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
18017                onSetAlpha(255);
18018            }
18019            parent.finishAnimatingView(this, a);
18020        }
18021
18022        if (more && hardwareAcceleratedCanvas) {
18023            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
18024                // alpha animations should cause the child to recreate its display list
18025                invalidate(true);
18026            }
18027        }
18028
18029        mRecreateDisplayList = false;
18030
18031        return more;
18032    }
18033
18034    static Paint getDebugPaint() {
18035        if (sDebugPaint == null) {
18036            sDebugPaint = new Paint();
18037            sDebugPaint.setAntiAlias(false);
18038        }
18039        return sDebugPaint;
18040    }
18041
18042    final int dipsToPixels(int dips) {
18043        float scale = getContext().getResources().getDisplayMetrics().density;
18044        return (int) (dips * scale + 0.5f);
18045    }
18046
18047    final private void debugDrawFocus(Canvas canvas) {
18048        if (isFocused()) {
18049            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
18050            final int l = mScrollX;
18051            final int r = l + mRight - mLeft;
18052            final int t = mScrollY;
18053            final int b = t + mBottom - mTop;
18054
18055            final Paint paint = getDebugPaint();
18056            paint.setColor(DEBUG_CORNERS_COLOR);
18057
18058            // Draw squares in corners.
18059            paint.setStyle(Paint.Style.FILL);
18060            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
18061            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
18062            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
18063            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
18064
18065            // Draw big X across the view.
18066            paint.setStyle(Paint.Style.STROKE);
18067            canvas.drawLine(l, t, r, b, paint);
18068            canvas.drawLine(l, b, r, t, paint);
18069        }
18070    }
18071
18072    /**
18073     * Manually render this view (and all of its children) to the given Canvas.
18074     * The view must have already done a full layout before this function is
18075     * called.  When implementing a view, implement
18076     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
18077     * If you do need to override this method, call the superclass version.
18078     *
18079     * @param canvas The Canvas to which the View is rendered.
18080     */
18081    @CallSuper
18082    public void draw(Canvas canvas) {
18083        final int privateFlags = mPrivateFlags;
18084        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
18085                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
18086        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
18087
18088        /*
18089         * Draw traversal performs several drawing steps which must be executed
18090         * in the appropriate order:
18091         *
18092         *      1. Draw the background
18093         *      2. If necessary, save the canvas' layers to prepare for fading
18094         *      3. Draw view's content
18095         *      4. Draw children
18096         *      5. If necessary, draw the fading edges and restore layers
18097         *      6. Draw decorations (scrollbars for instance)
18098         */
18099
18100        // Step 1, draw the background, if needed
18101        int saveCount;
18102
18103        if (!dirtyOpaque) {
18104            drawBackground(canvas);
18105        }
18106
18107        // skip step 2 & 5 if possible (common case)
18108        final int viewFlags = mViewFlags;
18109        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
18110        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
18111        if (!verticalEdges && !horizontalEdges) {
18112            // Step 3, draw the content
18113            if (!dirtyOpaque) onDraw(canvas);
18114
18115            // Step 4, draw the children
18116            dispatchDraw(canvas);
18117
18118            // Overlay is part of the content and draws beneath Foreground
18119            if (mOverlay != null && !mOverlay.isEmpty()) {
18120                mOverlay.getOverlayView().dispatchDraw(canvas);
18121            }
18122
18123            // Step 6, draw decorations (foreground, scrollbars)
18124            onDrawForeground(canvas);
18125
18126            if (debugDraw()) {
18127                debugDrawFocus(canvas);
18128            }
18129
18130            // we're done...
18131            return;
18132        }
18133
18134        /*
18135         * Here we do the full fledged routine...
18136         * (this is an uncommon case where speed matters less,
18137         * this is why we repeat some of the tests that have been
18138         * done above)
18139         */
18140
18141        boolean drawTop = false;
18142        boolean drawBottom = false;
18143        boolean drawLeft = false;
18144        boolean drawRight = false;
18145
18146        float topFadeStrength = 0.0f;
18147        float bottomFadeStrength = 0.0f;
18148        float leftFadeStrength = 0.0f;
18149        float rightFadeStrength = 0.0f;
18150
18151        // Step 2, save the canvas' layers
18152        int paddingLeft = mPaddingLeft;
18153
18154        final boolean offsetRequired = isPaddingOffsetRequired();
18155        if (offsetRequired) {
18156            paddingLeft += getLeftPaddingOffset();
18157        }
18158
18159        int left = mScrollX + paddingLeft;
18160        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
18161        int top = mScrollY + getFadeTop(offsetRequired);
18162        int bottom = top + getFadeHeight(offsetRequired);
18163
18164        if (offsetRequired) {
18165            right += getRightPaddingOffset();
18166            bottom += getBottomPaddingOffset();
18167        }
18168
18169        final ScrollabilityCache scrollabilityCache = mScrollCache;
18170        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
18171        int length = (int) fadeHeight;
18172
18173        // clip the fade length if top and bottom fades overlap
18174        // overlapping fades produce odd-looking artifacts
18175        if (verticalEdges && (top + length > bottom - length)) {
18176            length = (bottom - top) / 2;
18177        }
18178
18179        // also clip horizontal fades if necessary
18180        if (horizontalEdges && (left + length > right - length)) {
18181            length = (right - left) / 2;
18182        }
18183
18184        if (verticalEdges) {
18185            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
18186            drawTop = topFadeStrength * fadeHeight > 1.0f;
18187            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
18188            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
18189        }
18190
18191        if (horizontalEdges) {
18192            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
18193            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
18194            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
18195            drawRight = rightFadeStrength * fadeHeight > 1.0f;
18196        }
18197
18198        saveCount = canvas.getSaveCount();
18199
18200        int solidColor = getSolidColor();
18201        if (solidColor == 0) {
18202            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
18203
18204            if (drawTop) {
18205                canvas.saveLayer(left, top, right, top + length, null, flags);
18206            }
18207
18208            if (drawBottom) {
18209                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
18210            }
18211
18212            if (drawLeft) {
18213                canvas.saveLayer(left, top, left + length, bottom, null, flags);
18214            }
18215
18216            if (drawRight) {
18217                canvas.saveLayer(right - length, top, right, bottom, null, flags);
18218            }
18219        } else {
18220            scrollabilityCache.setFadeColor(solidColor);
18221        }
18222
18223        // Step 3, draw the content
18224        if (!dirtyOpaque) onDraw(canvas);
18225
18226        // Step 4, draw the children
18227        dispatchDraw(canvas);
18228
18229        // Step 5, draw the fade effect and restore layers
18230        final Paint p = scrollabilityCache.paint;
18231        final Matrix matrix = scrollabilityCache.matrix;
18232        final Shader fade = scrollabilityCache.shader;
18233
18234        if (drawTop) {
18235            matrix.setScale(1, fadeHeight * topFadeStrength);
18236            matrix.postTranslate(left, top);
18237            fade.setLocalMatrix(matrix);
18238            p.setShader(fade);
18239            canvas.drawRect(left, top, right, top + length, p);
18240        }
18241
18242        if (drawBottom) {
18243            matrix.setScale(1, fadeHeight * bottomFadeStrength);
18244            matrix.postRotate(180);
18245            matrix.postTranslate(left, bottom);
18246            fade.setLocalMatrix(matrix);
18247            p.setShader(fade);
18248            canvas.drawRect(left, bottom - length, right, bottom, p);
18249        }
18250
18251        if (drawLeft) {
18252            matrix.setScale(1, fadeHeight * leftFadeStrength);
18253            matrix.postRotate(-90);
18254            matrix.postTranslate(left, top);
18255            fade.setLocalMatrix(matrix);
18256            p.setShader(fade);
18257            canvas.drawRect(left, top, left + length, bottom, p);
18258        }
18259
18260        if (drawRight) {
18261            matrix.setScale(1, fadeHeight * rightFadeStrength);
18262            matrix.postRotate(90);
18263            matrix.postTranslate(right, top);
18264            fade.setLocalMatrix(matrix);
18265            p.setShader(fade);
18266            canvas.drawRect(right - length, top, right, bottom, p);
18267        }
18268
18269        canvas.restoreToCount(saveCount);
18270
18271        // Overlay is part of the content and draws beneath Foreground
18272        if (mOverlay != null && !mOverlay.isEmpty()) {
18273            mOverlay.getOverlayView().dispatchDraw(canvas);
18274        }
18275
18276        // Step 6, draw decorations (foreground, scrollbars)
18277        onDrawForeground(canvas);
18278
18279        if (debugDraw()) {
18280            debugDrawFocus(canvas);
18281        }
18282    }
18283
18284    /**
18285     * Draws the background onto the specified canvas.
18286     *
18287     * @param canvas Canvas on which to draw the background
18288     */
18289    private void drawBackground(Canvas canvas) {
18290        final Drawable background = mBackground;
18291        if (background == null) {
18292            return;
18293        }
18294
18295        setBackgroundBounds();
18296
18297        // Attempt to use a display list if requested.
18298        if (canvas.isHardwareAccelerated() && mAttachInfo != null
18299                && mAttachInfo.mThreadedRenderer != null) {
18300            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
18301
18302            final RenderNode renderNode = mBackgroundRenderNode;
18303            if (renderNode != null && renderNode.isValid()) {
18304                setBackgroundRenderNodeProperties(renderNode);
18305                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18306                return;
18307            }
18308        }
18309
18310        final int scrollX = mScrollX;
18311        final int scrollY = mScrollY;
18312        if ((scrollX | scrollY) == 0) {
18313            background.draw(canvas);
18314        } else {
18315            canvas.translate(scrollX, scrollY);
18316            background.draw(canvas);
18317            canvas.translate(-scrollX, -scrollY);
18318        }
18319    }
18320
18321    /**
18322     * Sets the correct background bounds and rebuilds the outline, if needed.
18323     * <p/>
18324     * This is called by LayoutLib.
18325     */
18326    void setBackgroundBounds() {
18327        if (mBackgroundSizeChanged && mBackground != null) {
18328            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
18329            mBackgroundSizeChanged = false;
18330            rebuildOutline();
18331        }
18332    }
18333
18334    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
18335        renderNode.setTranslationX(mScrollX);
18336        renderNode.setTranslationY(mScrollY);
18337    }
18338
18339    /**
18340     * Creates a new display list or updates the existing display list for the
18341     * specified Drawable.
18342     *
18343     * @param drawable Drawable for which to create a display list
18344     * @param renderNode Existing RenderNode, or {@code null}
18345     * @return A valid display list for the specified drawable
18346     */
18347    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
18348        if (renderNode == null) {
18349            renderNode = RenderNode.create(drawable.getClass().getName(), this);
18350        }
18351
18352        final Rect bounds = drawable.getBounds();
18353        final int width = bounds.width();
18354        final int height = bounds.height();
18355        final DisplayListCanvas canvas = renderNode.start(width, height);
18356
18357        // Reverse left/top translation done by drawable canvas, which will
18358        // instead be applied by rendernode's LTRB bounds below. This way, the
18359        // drawable's bounds match with its rendernode bounds and its content
18360        // will lie within those bounds in the rendernode tree.
18361        canvas.translate(-bounds.left, -bounds.top);
18362
18363        try {
18364            drawable.draw(canvas);
18365        } finally {
18366            renderNode.end(canvas);
18367        }
18368
18369        // Set up drawable properties that are view-independent.
18370        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
18371        renderNode.setProjectBackwards(drawable.isProjected());
18372        renderNode.setProjectionReceiver(true);
18373        renderNode.setClipToBounds(false);
18374        return renderNode;
18375    }
18376
18377    /**
18378     * Returns the overlay for this view, creating it if it does not yet exist.
18379     * Adding drawables to the overlay will cause them to be displayed whenever
18380     * the view itself is redrawn. Objects in the overlay should be actively
18381     * managed: remove them when they should not be displayed anymore. The
18382     * overlay will always have the same size as its host view.
18383     *
18384     * <p>Note: Overlays do not currently work correctly with {@link
18385     * SurfaceView} or {@link TextureView}; contents in overlays for these
18386     * types of views may not display correctly.</p>
18387     *
18388     * @return The ViewOverlay object for this view.
18389     * @see ViewOverlay
18390     */
18391    public ViewOverlay getOverlay() {
18392        if (mOverlay == null) {
18393            mOverlay = new ViewOverlay(mContext, this);
18394        }
18395        return mOverlay;
18396    }
18397
18398    /**
18399     * Override this if your view is known to always be drawn on top of a solid color background,
18400     * and needs to draw fading edges. Returning a non-zero color enables the view system to
18401     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
18402     * should be set to 0xFF.
18403     *
18404     * @see #setVerticalFadingEdgeEnabled(boolean)
18405     * @see #setHorizontalFadingEdgeEnabled(boolean)
18406     *
18407     * @return The known solid color background for this view, or 0 if the color may vary
18408     */
18409    @ViewDebug.ExportedProperty(category = "drawing")
18410    @ColorInt
18411    public int getSolidColor() {
18412        return 0;
18413    }
18414
18415    /**
18416     * Build a human readable string representation of the specified view flags.
18417     *
18418     * @param flags the view flags to convert to a string
18419     * @return a String representing the supplied flags
18420     */
18421    private static String printFlags(int flags) {
18422        String output = "";
18423        int numFlags = 0;
18424        if ((flags & FOCUSABLE) == FOCUSABLE) {
18425            output += "TAKES_FOCUS";
18426            numFlags++;
18427        }
18428
18429        switch (flags & VISIBILITY_MASK) {
18430        case INVISIBLE:
18431            if (numFlags > 0) {
18432                output += " ";
18433            }
18434            output += "INVISIBLE";
18435            // USELESS HERE numFlags++;
18436            break;
18437        case GONE:
18438            if (numFlags > 0) {
18439                output += " ";
18440            }
18441            output += "GONE";
18442            // USELESS HERE numFlags++;
18443            break;
18444        default:
18445            break;
18446        }
18447        return output;
18448    }
18449
18450    /**
18451     * Build a human readable string representation of the specified private
18452     * view flags.
18453     *
18454     * @param privateFlags the private view flags to convert to a string
18455     * @return a String representing the supplied flags
18456     */
18457    private static String printPrivateFlags(int privateFlags) {
18458        String output = "";
18459        int numFlags = 0;
18460
18461        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
18462            output += "WANTS_FOCUS";
18463            numFlags++;
18464        }
18465
18466        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
18467            if (numFlags > 0) {
18468                output += " ";
18469            }
18470            output += "FOCUSED";
18471            numFlags++;
18472        }
18473
18474        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
18475            if (numFlags > 0) {
18476                output += " ";
18477            }
18478            output += "SELECTED";
18479            numFlags++;
18480        }
18481
18482        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
18483            if (numFlags > 0) {
18484                output += " ";
18485            }
18486            output += "IS_ROOT_NAMESPACE";
18487            numFlags++;
18488        }
18489
18490        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
18491            if (numFlags > 0) {
18492                output += " ";
18493            }
18494            output += "HAS_BOUNDS";
18495            numFlags++;
18496        }
18497
18498        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
18499            if (numFlags > 0) {
18500                output += " ";
18501            }
18502            output += "DRAWN";
18503            // USELESS HERE numFlags++;
18504        }
18505        return output;
18506    }
18507
18508    /**
18509     * <p>Indicates whether or not this view's layout will be requested during
18510     * the next hierarchy layout pass.</p>
18511     *
18512     * @return true if the layout will be forced during next layout pass
18513     */
18514    public boolean isLayoutRequested() {
18515        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18516    }
18517
18518    /**
18519     * Return true if o is a ViewGroup that is laying out using optical bounds.
18520     * @hide
18521     */
18522    public static boolean isLayoutModeOptical(Object o) {
18523        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
18524    }
18525
18526    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
18527        Insets parentInsets = mParent instanceof View ?
18528                ((View) mParent).getOpticalInsets() : Insets.NONE;
18529        Insets childInsets = getOpticalInsets();
18530        return setFrame(
18531                left   + parentInsets.left - childInsets.left,
18532                top    + parentInsets.top  - childInsets.top,
18533                right  + parentInsets.left + childInsets.right,
18534                bottom + parentInsets.top  + childInsets.bottom);
18535    }
18536
18537    /**
18538     * Assign a size and position to a view and all of its
18539     * descendants
18540     *
18541     * <p>This is the second phase of the layout mechanism.
18542     * (The first is measuring). In this phase, each parent calls
18543     * layout on all of its children to position them.
18544     * This is typically done using the child measurements
18545     * that were stored in the measure pass().</p>
18546     *
18547     * <p>Derived classes should not override this method.
18548     * Derived classes with children should override
18549     * onLayout. In that method, they should
18550     * call layout on each of their children.</p>
18551     *
18552     * @param l Left position, relative to parent
18553     * @param t Top position, relative to parent
18554     * @param r Right position, relative to parent
18555     * @param b Bottom position, relative to parent
18556     */
18557    @SuppressWarnings({"unchecked"})
18558    public void layout(int l, int t, int r, int b) {
18559        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
18560            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
18561            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18562        }
18563
18564        int oldL = mLeft;
18565        int oldT = mTop;
18566        int oldB = mBottom;
18567        int oldR = mRight;
18568
18569        boolean changed = isLayoutModeOptical(mParent) ?
18570                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
18571
18572        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
18573            onLayout(changed, l, t, r, b);
18574
18575            if (shouldDrawRoundScrollbar()) {
18576                if(mRoundScrollbarRenderer == null) {
18577                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
18578                }
18579            } else {
18580                mRoundScrollbarRenderer = null;
18581            }
18582
18583            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
18584
18585            ListenerInfo li = mListenerInfo;
18586            if (li != null && li.mOnLayoutChangeListeners != null) {
18587                ArrayList<OnLayoutChangeListener> listenersCopy =
18588                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
18589                int numListeners = listenersCopy.size();
18590                for (int i = 0; i < numListeners; ++i) {
18591                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
18592                }
18593            }
18594        }
18595
18596        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
18597        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
18598    }
18599
18600    /**
18601     * Called from layout when this view should
18602     * assign a size and position to each of its children.
18603     *
18604     * Derived classes with children should override
18605     * this method and call layout on each of
18606     * their children.
18607     * @param changed This is a new size or position for this view
18608     * @param left Left position, relative to parent
18609     * @param top Top position, relative to parent
18610     * @param right Right position, relative to parent
18611     * @param bottom Bottom position, relative to parent
18612     */
18613    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
18614    }
18615
18616    /**
18617     * Assign a size and position to this view.
18618     *
18619     * This is called from layout.
18620     *
18621     * @param left Left position, relative to parent
18622     * @param top Top position, relative to parent
18623     * @param right Right position, relative to parent
18624     * @param bottom Bottom position, relative to parent
18625     * @return true if the new size and position are different than the
18626     *         previous ones
18627     * {@hide}
18628     */
18629    protected boolean setFrame(int left, int top, int right, int bottom) {
18630        boolean changed = false;
18631
18632        if (DBG) {
18633            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
18634                    + right + "," + bottom + ")");
18635        }
18636
18637        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
18638            changed = true;
18639
18640            // Remember our drawn bit
18641            int drawn = mPrivateFlags & PFLAG_DRAWN;
18642
18643            int oldWidth = mRight - mLeft;
18644            int oldHeight = mBottom - mTop;
18645            int newWidth = right - left;
18646            int newHeight = bottom - top;
18647            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
18648
18649            // Invalidate our old position
18650            invalidate(sizeChanged);
18651
18652            mLeft = left;
18653            mTop = top;
18654            mRight = right;
18655            mBottom = bottom;
18656            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
18657
18658            mPrivateFlags |= PFLAG_HAS_BOUNDS;
18659
18660
18661            if (sizeChanged) {
18662                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
18663            }
18664
18665            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
18666                // If we are visible, force the DRAWN bit to on so that
18667                // this invalidate will go through (at least to our parent).
18668                // This is because someone may have invalidated this view
18669                // before this call to setFrame came in, thereby clearing
18670                // the DRAWN bit.
18671                mPrivateFlags |= PFLAG_DRAWN;
18672                invalidate(sizeChanged);
18673                // parent display list may need to be recreated based on a change in the bounds
18674                // of any child
18675                invalidateParentCaches();
18676            }
18677
18678            // Reset drawn bit to original value (invalidate turns it off)
18679            mPrivateFlags |= drawn;
18680
18681            mBackgroundSizeChanged = true;
18682            if (mForegroundInfo != null) {
18683                mForegroundInfo.mBoundsChanged = true;
18684            }
18685
18686            notifySubtreeAccessibilityStateChangedIfNeeded();
18687        }
18688        return changed;
18689    }
18690
18691    /**
18692     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
18693     * @hide
18694     */
18695    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
18696        setFrame(left, top, right, bottom);
18697    }
18698
18699    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
18700        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
18701        if (mOverlay != null) {
18702            mOverlay.getOverlayView().setRight(newWidth);
18703            mOverlay.getOverlayView().setBottom(newHeight);
18704        }
18705        rebuildOutline();
18706    }
18707
18708    /**
18709     * Finalize inflating a view from XML.  This is called as the last phase
18710     * of inflation, after all child views have been added.
18711     *
18712     * <p>Even if the subclass overrides onFinishInflate, they should always be
18713     * sure to call the super method, so that we get called.
18714     */
18715    @CallSuper
18716    protected void onFinishInflate() {
18717    }
18718
18719    /**
18720     * Returns the resources associated with this view.
18721     *
18722     * @return Resources object.
18723     */
18724    public Resources getResources() {
18725        return mResources;
18726    }
18727
18728    /**
18729     * Invalidates the specified Drawable.
18730     *
18731     * @param drawable the drawable to invalidate
18732     */
18733    @Override
18734    public void invalidateDrawable(@NonNull Drawable drawable) {
18735        if (verifyDrawable(drawable)) {
18736            final Rect dirty = drawable.getDirtyBounds();
18737            final int scrollX = mScrollX;
18738            final int scrollY = mScrollY;
18739
18740            invalidate(dirty.left + scrollX, dirty.top + scrollY,
18741                    dirty.right + scrollX, dirty.bottom + scrollY);
18742            rebuildOutline();
18743        }
18744    }
18745
18746    /**
18747     * Schedules an action on a drawable to occur at a specified time.
18748     *
18749     * @param who the recipient of the action
18750     * @param what the action to run on the drawable
18751     * @param when the time at which the action must occur. Uses the
18752     *        {@link SystemClock#uptimeMillis} timebase.
18753     */
18754    @Override
18755    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
18756        if (verifyDrawable(who) && what != null) {
18757            final long delay = when - SystemClock.uptimeMillis();
18758            if (mAttachInfo != null) {
18759                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
18760                        Choreographer.CALLBACK_ANIMATION, what, who,
18761                        Choreographer.subtractFrameDelay(delay));
18762            } else {
18763                // Postpone the runnable until we know
18764                // on which thread it needs to run.
18765                getRunQueue().postDelayed(what, delay);
18766            }
18767        }
18768    }
18769
18770    /**
18771     * Cancels a scheduled action on a drawable.
18772     *
18773     * @param who the recipient of the action
18774     * @param what the action to cancel
18775     */
18776    @Override
18777    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
18778        if (verifyDrawable(who) && what != null) {
18779            if (mAttachInfo != null) {
18780                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18781                        Choreographer.CALLBACK_ANIMATION, what, who);
18782            }
18783            getRunQueue().removeCallbacks(what);
18784        }
18785    }
18786
18787    /**
18788     * Unschedule any events associated with the given Drawable.  This can be
18789     * used when selecting a new Drawable into a view, so that the previous
18790     * one is completely unscheduled.
18791     *
18792     * @param who The Drawable to unschedule.
18793     *
18794     * @see #drawableStateChanged
18795     */
18796    public void unscheduleDrawable(Drawable who) {
18797        if (mAttachInfo != null && who != null) {
18798            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18799                    Choreographer.CALLBACK_ANIMATION, null, who);
18800        }
18801    }
18802
18803    /**
18804     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
18805     * that the View directionality can and will be resolved before its Drawables.
18806     *
18807     * Will call {@link View#onResolveDrawables} when resolution is done.
18808     *
18809     * @hide
18810     */
18811    protected void resolveDrawables() {
18812        // Drawables resolution may need to happen before resolving the layout direction (which is
18813        // done only during the measure() call).
18814        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
18815        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
18816        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
18817        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
18818        // direction to be resolved as its resolved value will be the same as its raw value.
18819        if (!isLayoutDirectionResolved() &&
18820                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
18821            return;
18822        }
18823
18824        final int layoutDirection = isLayoutDirectionResolved() ?
18825                getLayoutDirection() : getRawLayoutDirection();
18826
18827        if (mBackground != null) {
18828            mBackground.setLayoutDirection(layoutDirection);
18829        }
18830        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18831            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
18832        }
18833        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
18834        onResolveDrawables(layoutDirection);
18835    }
18836
18837    boolean areDrawablesResolved() {
18838        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
18839    }
18840
18841    /**
18842     * Called when layout direction has been resolved.
18843     *
18844     * The default implementation does nothing.
18845     *
18846     * @param layoutDirection The resolved layout direction.
18847     *
18848     * @see #LAYOUT_DIRECTION_LTR
18849     * @see #LAYOUT_DIRECTION_RTL
18850     *
18851     * @hide
18852     */
18853    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
18854    }
18855
18856    /**
18857     * @hide
18858     */
18859    protected void resetResolvedDrawables() {
18860        resetResolvedDrawablesInternal();
18861    }
18862
18863    void resetResolvedDrawablesInternal() {
18864        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
18865    }
18866
18867    /**
18868     * If your view subclass is displaying its own Drawable objects, it should
18869     * override this function and return true for any Drawable it is
18870     * displaying.  This allows animations for those drawables to be
18871     * scheduled.
18872     *
18873     * <p>Be sure to call through to the super class when overriding this
18874     * function.
18875     *
18876     * @param who The Drawable to verify.  Return true if it is one you are
18877     *            displaying, else return the result of calling through to the
18878     *            super class.
18879     *
18880     * @return boolean If true than the Drawable is being displayed in the
18881     *         view; else false and it is not allowed to animate.
18882     *
18883     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
18884     * @see #drawableStateChanged()
18885     */
18886    @CallSuper
18887    protected boolean verifyDrawable(@NonNull Drawable who) {
18888        // Avoid verifying the scroll bar drawable so that we don't end up in
18889        // an invalidation loop. This effectively prevents the scroll bar
18890        // drawable from triggering invalidations and scheduling runnables.
18891        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
18892    }
18893
18894    /**
18895     * This function is called whenever the state of the view changes in such
18896     * a way that it impacts the state of drawables being shown.
18897     * <p>
18898     * If the View has a StateListAnimator, it will also be called to run necessary state
18899     * change animations.
18900     * <p>
18901     * Be sure to call through to the superclass when overriding this function.
18902     *
18903     * @see Drawable#setState(int[])
18904     */
18905    @CallSuper
18906    protected void drawableStateChanged() {
18907        final int[] state = getDrawableState();
18908        boolean changed = false;
18909
18910        final Drawable bg = mBackground;
18911        if (bg != null && bg.isStateful()) {
18912            changed |= bg.setState(state);
18913        }
18914
18915        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18916        if (fg != null && fg.isStateful()) {
18917            changed |= fg.setState(state);
18918        }
18919
18920        if (mScrollCache != null) {
18921            final Drawable scrollBar = mScrollCache.scrollBar;
18922            if (scrollBar != null && scrollBar.isStateful()) {
18923                changed |= scrollBar.setState(state)
18924                        && mScrollCache.state != ScrollabilityCache.OFF;
18925            }
18926        }
18927
18928        if (mStateListAnimator != null) {
18929            mStateListAnimator.setState(state);
18930        }
18931
18932        if (changed) {
18933            invalidate();
18934        }
18935    }
18936
18937    /**
18938     * This function is called whenever the view hotspot changes and needs to
18939     * be propagated to drawables or child views managed by the view.
18940     * <p>
18941     * Dispatching to child views is handled by
18942     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18943     * <p>
18944     * Be sure to call through to the superclass when overriding this function.
18945     *
18946     * @param x hotspot x coordinate
18947     * @param y hotspot y coordinate
18948     */
18949    @CallSuper
18950    public void drawableHotspotChanged(float x, float y) {
18951        if (mBackground != null) {
18952            mBackground.setHotspot(x, y);
18953        }
18954        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18955            mForegroundInfo.mDrawable.setHotspot(x, y);
18956        }
18957
18958        dispatchDrawableHotspotChanged(x, y);
18959    }
18960
18961    /**
18962     * Dispatches drawableHotspotChanged to all of this View's children.
18963     *
18964     * @param x hotspot x coordinate
18965     * @param y hotspot y coordinate
18966     * @see #drawableHotspotChanged(float, float)
18967     */
18968    public void dispatchDrawableHotspotChanged(float x, float y) {
18969    }
18970
18971    /**
18972     * Call this to force a view to update its drawable state. This will cause
18973     * drawableStateChanged to be called on this view. Views that are interested
18974     * in the new state should call getDrawableState.
18975     *
18976     * @see #drawableStateChanged
18977     * @see #getDrawableState
18978     */
18979    public void refreshDrawableState() {
18980        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18981        drawableStateChanged();
18982
18983        ViewParent parent = mParent;
18984        if (parent != null) {
18985            parent.childDrawableStateChanged(this);
18986        }
18987    }
18988
18989    /**
18990     * Return an array of resource IDs of the drawable states representing the
18991     * current state of the view.
18992     *
18993     * @return The current drawable state
18994     *
18995     * @see Drawable#setState(int[])
18996     * @see #drawableStateChanged()
18997     * @see #onCreateDrawableState(int)
18998     */
18999    public final int[] getDrawableState() {
19000        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
19001            return mDrawableState;
19002        } else {
19003            mDrawableState = onCreateDrawableState(0);
19004            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
19005            return mDrawableState;
19006        }
19007    }
19008
19009    /**
19010     * Generate the new {@link android.graphics.drawable.Drawable} state for
19011     * this view. This is called by the view
19012     * system when the cached Drawable state is determined to be invalid.  To
19013     * retrieve the current state, you should use {@link #getDrawableState}.
19014     *
19015     * @param extraSpace if non-zero, this is the number of extra entries you
19016     * would like in the returned array in which you can place your own
19017     * states.
19018     *
19019     * @return Returns an array holding the current {@link Drawable} state of
19020     * the view.
19021     *
19022     * @see #mergeDrawableStates(int[], int[])
19023     */
19024    protected int[] onCreateDrawableState(int extraSpace) {
19025        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
19026                mParent instanceof View) {
19027            return ((View) mParent).onCreateDrawableState(extraSpace);
19028        }
19029
19030        int[] drawableState;
19031
19032        int privateFlags = mPrivateFlags;
19033
19034        int viewStateIndex = 0;
19035        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
19036        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
19037        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
19038        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
19039        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
19040        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
19041        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
19042                ThreadedRenderer.isAvailable()) {
19043            // This is set if HW acceleration is requested, even if the current
19044            // process doesn't allow it.  This is just to allow app preview
19045            // windows to better match their app.
19046            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
19047        }
19048        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
19049
19050        final int privateFlags2 = mPrivateFlags2;
19051        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
19052            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
19053        }
19054        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
19055            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
19056        }
19057
19058        drawableState = StateSet.get(viewStateIndex);
19059
19060        //noinspection ConstantIfStatement
19061        if (false) {
19062            Log.i("View", "drawableStateIndex=" + viewStateIndex);
19063            Log.i("View", toString()
19064                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
19065                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
19066                    + " fo=" + hasFocus()
19067                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
19068                    + " wf=" + hasWindowFocus()
19069                    + ": " + Arrays.toString(drawableState));
19070        }
19071
19072        if (extraSpace == 0) {
19073            return drawableState;
19074        }
19075
19076        final int[] fullState;
19077        if (drawableState != null) {
19078            fullState = new int[drawableState.length + extraSpace];
19079            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
19080        } else {
19081            fullState = new int[extraSpace];
19082        }
19083
19084        return fullState;
19085    }
19086
19087    /**
19088     * Merge your own state values in <var>additionalState</var> into the base
19089     * state values <var>baseState</var> that were returned by
19090     * {@link #onCreateDrawableState(int)}.
19091     *
19092     * @param baseState The base state values returned by
19093     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
19094     * own additional state values.
19095     *
19096     * @param additionalState The additional state values you would like
19097     * added to <var>baseState</var>; this array is not modified.
19098     *
19099     * @return As a convenience, the <var>baseState</var> array you originally
19100     * passed into the function is returned.
19101     *
19102     * @see #onCreateDrawableState(int)
19103     */
19104    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
19105        final int N = baseState.length;
19106        int i = N - 1;
19107        while (i >= 0 && baseState[i] == 0) {
19108            i--;
19109        }
19110        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
19111        return baseState;
19112    }
19113
19114    /**
19115     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
19116     * on all Drawable objects associated with this view.
19117     * <p>
19118     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
19119     * attached to this view.
19120     */
19121    @CallSuper
19122    public void jumpDrawablesToCurrentState() {
19123        if (mBackground != null) {
19124            mBackground.jumpToCurrentState();
19125        }
19126        if (mStateListAnimator != null) {
19127            mStateListAnimator.jumpToCurrentState();
19128        }
19129        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19130            mForegroundInfo.mDrawable.jumpToCurrentState();
19131        }
19132    }
19133
19134    /**
19135     * Sets the background color for this view.
19136     * @param color the color of the background
19137     */
19138    @RemotableViewMethod
19139    public void setBackgroundColor(@ColorInt int color) {
19140        if (mBackground instanceof ColorDrawable) {
19141            ((ColorDrawable) mBackground.mutate()).setColor(color);
19142            computeOpaqueFlags();
19143            mBackgroundResource = 0;
19144        } else {
19145            setBackground(new ColorDrawable(color));
19146        }
19147    }
19148
19149    /**
19150     * Set the background to a given resource. The resource should refer to
19151     * a Drawable object or 0 to remove the background.
19152     * @param resid The identifier of the resource.
19153     *
19154     * @attr ref android.R.styleable#View_background
19155     */
19156    @RemotableViewMethod
19157    public void setBackgroundResource(@DrawableRes int resid) {
19158        if (resid != 0 && resid == mBackgroundResource) {
19159            return;
19160        }
19161
19162        Drawable d = null;
19163        if (resid != 0) {
19164            d = mContext.getDrawable(resid);
19165        }
19166        setBackground(d);
19167
19168        mBackgroundResource = resid;
19169    }
19170
19171    /**
19172     * Set the background to a given Drawable, or remove the background. If the
19173     * background has padding, this View's padding is set to the background's
19174     * padding. However, when a background is removed, this View's padding isn't
19175     * touched. If setting the padding is desired, please use
19176     * {@link #setPadding(int, int, int, int)}.
19177     *
19178     * @param background The Drawable to use as the background, or null to remove the
19179     *        background
19180     */
19181    public void setBackground(Drawable background) {
19182        //noinspection deprecation
19183        setBackgroundDrawable(background);
19184    }
19185
19186    /**
19187     * @deprecated use {@link #setBackground(Drawable)} instead
19188     */
19189    @Deprecated
19190    public void setBackgroundDrawable(Drawable background) {
19191        computeOpaqueFlags();
19192
19193        if (background == mBackground) {
19194            return;
19195        }
19196
19197        boolean requestLayout = false;
19198
19199        mBackgroundResource = 0;
19200
19201        /*
19202         * Regardless of whether we're setting a new background or not, we want
19203         * to clear the previous drawable. setVisible first while we still have the callback set.
19204         */
19205        if (mBackground != null) {
19206            if (isAttachedToWindow()) {
19207                mBackground.setVisible(false, false);
19208            }
19209            mBackground.setCallback(null);
19210            unscheduleDrawable(mBackground);
19211        }
19212
19213        if (background != null) {
19214            Rect padding = sThreadLocal.get();
19215            if (padding == null) {
19216                padding = new Rect();
19217                sThreadLocal.set(padding);
19218            }
19219            resetResolvedDrawablesInternal();
19220            background.setLayoutDirection(getLayoutDirection());
19221            if (background.getPadding(padding)) {
19222                resetResolvedPaddingInternal();
19223                switch (background.getLayoutDirection()) {
19224                    case LAYOUT_DIRECTION_RTL:
19225                        mUserPaddingLeftInitial = padding.right;
19226                        mUserPaddingRightInitial = padding.left;
19227                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
19228                        break;
19229                    case LAYOUT_DIRECTION_LTR:
19230                    default:
19231                        mUserPaddingLeftInitial = padding.left;
19232                        mUserPaddingRightInitial = padding.right;
19233                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
19234                }
19235                mLeftPaddingDefined = false;
19236                mRightPaddingDefined = false;
19237            }
19238
19239            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
19240            // if it has a different minimum size, we should layout again
19241            if (mBackground == null
19242                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
19243                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
19244                requestLayout = true;
19245            }
19246
19247            // Set mBackground before we set this as the callback and start making other
19248            // background drawable state change calls. In particular, the setVisible call below
19249            // can result in drawables attempting to start animations or otherwise invalidate,
19250            // which requires the view set as the callback (us) to recognize the drawable as
19251            // belonging to it as per verifyDrawable.
19252            mBackground = background;
19253            if (background.isStateful()) {
19254                background.setState(getDrawableState());
19255            }
19256            if (isAttachedToWindow()) {
19257                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19258            }
19259
19260            applyBackgroundTint();
19261
19262            // Set callback last, since the view may still be initializing.
19263            background.setCallback(this);
19264
19265            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19266                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19267                requestLayout = true;
19268            }
19269        } else {
19270            /* Remove the background */
19271            mBackground = null;
19272            if ((mViewFlags & WILL_NOT_DRAW) != 0
19273                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
19274                mPrivateFlags |= PFLAG_SKIP_DRAW;
19275            }
19276
19277            /*
19278             * When the background is set, we try to apply its padding to this
19279             * View. When the background is removed, we don't touch this View's
19280             * padding. This is noted in the Javadocs. Hence, we don't need to
19281             * requestLayout(), the invalidate() below is sufficient.
19282             */
19283
19284            // The old background's minimum size could have affected this
19285            // View's layout, so let's requestLayout
19286            requestLayout = true;
19287        }
19288
19289        computeOpaqueFlags();
19290
19291        if (requestLayout) {
19292            requestLayout();
19293        }
19294
19295        mBackgroundSizeChanged = true;
19296        invalidate(true);
19297        invalidateOutline();
19298    }
19299
19300    /**
19301     * Gets the background drawable
19302     *
19303     * @return The drawable used as the background for this view, if any.
19304     *
19305     * @see #setBackground(Drawable)
19306     *
19307     * @attr ref android.R.styleable#View_background
19308     */
19309    public Drawable getBackground() {
19310        return mBackground;
19311    }
19312
19313    /**
19314     * Applies a tint to the background drawable. Does not modify the current tint
19315     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19316     * <p>
19317     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
19318     * mutate the drawable and apply the specified tint and tint mode using
19319     * {@link Drawable#setTintList(ColorStateList)}.
19320     *
19321     * @param tint the tint to apply, may be {@code null} to clear tint
19322     *
19323     * @attr ref android.R.styleable#View_backgroundTint
19324     * @see #getBackgroundTintList()
19325     * @see Drawable#setTintList(ColorStateList)
19326     */
19327    public void setBackgroundTintList(@Nullable ColorStateList tint) {
19328        if (mBackgroundTint == null) {
19329            mBackgroundTint = new TintInfo();
19330        }
19331        mBackgroundTint.mTintList = tint;
19332        mBackgroundTint.mHasTintList = true;
19333
19334        applyBackgroundTint();
19335    }
19336
19337    /**
19338     * Return the tint applied to the background drawable, if specified.
19339     *
19340     * @return the tint applied to the background drawable
19341     * @attr ref android.R.styleable#View_backgroundTint
19342     * @see #setBackgroundTintList(ColorStateList)
19343     */
19344    @Nullable
19345    public ColorStateList getBackgroundTintList() {
19346        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
19347    }
19348
19349    /**
19350     * Specifies the blending mode used to apply the tint specified by
19351     * {@link #setBackgroundTintList(ColorStateList)}} to the background
19352     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19353     *
19354     * @param tintMode the blending mode used to apply the tint, may be
19355     *                 {@code null} to clear tint
19356     * @attr ref android.R.styleable#View_backgroundTintMode
19357     * @see #getBackgroundTintMode()
19358     * @see Drawable#setTintMode(PorterDuff.Mode)
19359     */
19360    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19361        if (mBackgroundTint == null) {
19362            mBackgroundTint = new TintInfo();
19363        }
19364        mBackgroundTint.mTintMode = tintMode;
19365        mBackgroundTint.mHasTintMode = true;
19366
19367        applyBackgroundTint();
19368    }
19369
19370    /**
19371     * Return the blending mode used to apply the tint to the background
19372     * drawable, if specified.
19373     *
19374     * @return the blending mode used to apply the tint to the background
19375     *         drawable
19376     * @attr ref android.R.styleable#View_backgroundTintMode
19377     * @see #setBackgroundTintMode(PorterDuff.Mode)
19378     */
19379    @Nullable
19380    public PorterDuff.Mode getBackgroundTintMode() {
19381        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
19382    }
19383
19384    private void applyBackgroundTint() {
19385        if (mBackground != null && mBackgroundTint != null) {
19386            final TintInfo tintInfo = mBackgroundTint;
19387            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19388                mBackground = mBackground.mutate();
19389
19390                if (tintInfo.mHasTintList) {
19391                    mBackground.setTintList(tintInfo.mTintList);
19392                }
19393
19394                if (tintInfo.mHasTintMode) {
19395                    mBackground.setTintMode(tintInfo.mTintMode);
19396                }
19397
19398                // The drawable (or one of its children) may not have been
19399                // stateful before applying the tint, so let's try again.
19400                if (mBackground.isStateful()) {
19401                    mBackground.setState(getDrawableState());
19402                }
19403            }
19404        }
19405    }
19406
19407    /**
19408     * Returns the drawable used as the foreground of this View. The
19409     * foreground drawable, if non-null, is always drawn on top of the view's content.
19410     *
19411     * @return a Drawable or null if no foreground was set
19412     *
19413     * @see #onDrawForeground(Canvas)
19414     */
19415    public Drawable getForeground() {
19416        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19417    }
19418
19419    /**
19420     * Supply a Drawable that is to be rendered on top of all of the content in the view.
19421     *
19422     * @param foreground the Drawable to be drawn on top of the children
19423     *
19424     * @attr ref android.R.styleable#View_foreground
19425     */
19426    public void setForeground(Drawable foreground) {
19427        if (mForegroundInfo == null) {
19428            if (foreground == null) {
19429                // Nothing to do.
19430                return;
19431            }
19432            mForegroundInfo = new ForegroundInfo();
19433        }
19434
19435        if (foreground == mForegroundInfo.mDrawable) {
19436            // Nothing to do
19437            return;
19438        }
19439
19440        if (mForegroundInfo.mDrawable != null) {
19441            if (isAttachedToWindow()) {
19442                mForegroundInfo.mDrawable.setVisible(false, false);
19443            }
19444            mForegroundInfo.mDrawable.setCallback(null);
19445            unscheduleDrawable(mForegroundInfo.mDrawable);
19446        }
19447
19448        mForegroundInfo.mDrawable = foreground;
19449        mForegroundInfo.mBoundsChanged = true;
19450        if (foreground != null) {
19451            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19452                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19453            }
19454            foreground.setLayoutDirection(getLayoutDirection());
19455            if (foreground.isStateful()) {
19456                foreground.setState(getDrawableState());
19457            }
19458            applyForegroundTint();
19459            if (isAttachedToWindow()) {
19460                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19461            }
19462            // Set callback last, since the view may still be initializing.
19463            foreground.setCallback(this);
19464        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
19465            mPrivateFlags |= PFLAG_SKIP_DRAW;
19466        }
19467        requestLayout();
19468        invalidate();
19469    }
19470
19471    /**
19472     * Magic bit used to support features of framework-internal window decor implementation details.
19473     * This used to live exclusively in FrameLayout.
19474     *
19475     * @return true if the foreground should draw inside the padding region or false
19476     *         if it should draw inset by the view's padding
19477     * @hide internal use only; only used by FrameLayout and internal screen layouts.
19478     */
19479    public boolean isForegroundInsidePadding() {
19480        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
19481    }
19482
19483    /**
19484     * Describes how the foreground is positioned.
19485     *
19486     * @return foreground gravity.
19487     *
19488     * @see #setForegroundGravity(int)
19489     *
19490     * @attr ref android.R.styleable#View_foregroundGravity
19491     */
19492    public int getForegroundGravity() {
19493        return mForegroundInfo != null ? mForegroundInfo.mGravity
19494                : Gravity.START | Gravity.TOP;
19495    }
19496
19497    /**
19498     * Describes how the foreground is positioned. Defaults to START and TOP.
19499     *
19500     * @param gravity see {@link android.view.Gravity}
19501     *
19502     * @see #getForegroundGravity()
19503     *
19504     * @attr ref android.R.styleable#View_foregroundGravity
19505     */
19506    public void setForegroundGravity(int gravity) {
19507        if (mForegroundInfo == null) {
19508            mForegroundInfo = new ForegroundInfo();
19509        }
19510
19511        if (mForegroundInfo.mGravity != gravity) {
19512            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
19513                gravity |= Gravity.START;
19514            }
19515
19516            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
19517                gravity |= Gravity.TOP;
19518            }
19519
19520            mForegroundInfo.mGravity = gravity;
19521            requestLayout();
19522        }
19523    }
19524
19525    /**
19526     * Applies a tint to the foreground drawable. Does not modify the current tint
19527     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19528     * <p>
19529     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
19530     * mutate the drawable and apply the specified tint and tint mode using
19531     * {@link Drawable#setTintList(ColorStateList)}.
19532     *
19533     * @param tint the tint to apply, may be {@code null} to clear tint
19534     *
19535     * @attr ref android.R.styleable#View_foregroundTint
19536     * @see #getForegroundTintList()
19537     * @see Drawable#setTintList(ColorStateList)
19538     */
19539    public void setForegroundTintList(@Nullable ColorStateList tint) {
19540        if (mForegroundInfo == null) {
19541            mForegroundInfo = new ForegroundInfo();
19542        }
19543        if (mForegroundInfo.mTintInfo == null) {
19544            mForegroundInfo.mTintInfo = new TintInfo();
19545        }
19546        mForegroundInfo.mTintInfo.mTintList = tint;
19547        mForegroundInfo.mTintInfo.mHasTintList = true;
19548
19549        applyForegroundTint();
19550    }
19551
19552    /**
19553     * Return the tint applied to the foreground drawable, if specified.
19554     *
19555     * @return the tint applied to the foreground drawable
19556     * @attr ref android.R.styleable#View_foregroundTint
19557     * @see #setForegroundTintList(ColorStateList)
19558     */
19559    @Nullable
19560    public ColorStateList getForegroundTintList() {
19561        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19562                ? mForegroundInfo.mTintInfo.mTintList : null;
19563    }
19564
19565    /**
19566     * Specifies the blending mode used to apply the tint specified by
19567     * {@link #setForegroundTintList(ColorStateList)}} to the background
19568     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19569     *
19570     * @param tintMode the blending mode used to apply the tint, may be
19571     *                 {@code null} to clear tint
19572     * @attr ref android.R.styleable#View_foregroundTintMode
19573     * @see #getForegroundTintMode()
19574     * @see Drawable#setTintMode(PorterDuff.Mode)
19575     */
19576    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19577        if (mForegroundInfo == null) {
19578            mForegroundInfo = new ForegroundInfo();
19579        }
19580        if (mForegroundInfo.mTintInfo == null) {
19581            mForegroundInfo.mTintInfo = new TintInfo();
19582        }
19583        mForegroundInfo.mTintInfo.mTintMode = tintMode;
19584        mForegroundInfo.mTintInfo.mHasTintMode = true;
19585
19586        applyForegroundTint();
19587    }
19588
19589    /**
19590     * Return the blending mode used to apply the tint to the foreground
19591     * drawable, if specified.
19592     *
19593     * @return the blending mode used to apply the tint to the foreground
19594     *         drawable
19595     * @attr ref android.R.styleable#View_foregroundTintMode
19596     * @see #setForegroundTintMode(PorterDuff.Mode)
19597     */
19598    @Nullable
19599    public PorterDuff.Mode getForegroundTintMode() {
19600        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19601                ? mForegroundInfo.mTintInfo.mTintMode : null;
19602    }
19603
19604    private void applyForegroundTint() {
19605        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19606                && mForegroundInfo.mTintInfo != null) {
19607            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
19608            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19609                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
19610
19611                if (tintInfo.mHasTintList) {
19612                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
19613                }
19614
19615                if (tintInfo.mHasTintMode) {
19616                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
19617                }
19618
19619                // The drawable (or one of its children) may not have been
19620                // stateful before applying the tint, so let's try again.
19621                if (mForegroundInfo.mDrawable.isStateful()) {
19622                    mForegroundInfo.mDrawable.setState(getDrawableState());
19623                }
19624            }
19625        }
19626    }
19627
19628    /**
19629     * Draw any foreground content for this view.
19630     *
19631     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
19632     * drawable or other view-specific decorations. The foreground is drawn on top of the
19633     * primary view content.</p>
19634     *
19635     * @param canvas canvas to draw into
19636     */
19637    public void onDrawForeground(Canvas canvas) {
19638        onDrawScrollIndicators(canvas);
19639        onDrawScrollBars(canvas);
19640
19641        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19642        if (foreground != null) {
19643            if (mForegroundInfo.mBoundsChanged) {
19644                mForegroundInfo.mBoundsChanged = false;
19645                final Rect selfBounds = mForegroundInfo.mSelfBounds;
19646                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
19647
19648                if (mForegroundInfo.mInsidePadding) {
19649                    selfBounds.set(0, 0, getWidth(), getHeight());
19650                } else {
19651                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
19652                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
19653                }
19654
19655                final int ld = getLayoutDirection();
19656                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
19657                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
19658                foreground.setBounds(overlayBounds);
19659            }
19660
19661            foreground.draw(canvas);
19662        }
19663    }
19664
19665    /**
19666     * Sets the padding. The view may add on the space required to display
19667     * the scrollbars, depending on the style and visibility of the scrollbars.
19668     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
19669     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
19670     * from the values set in this call.
19671     *
19672     * @attr ref android.R.styleable#View_padding
19673     * @attr ref android.R.styleable#View_paddingBottom
19674     * @attr ref android.R.styleable#View_paddingLeft
19675     * @attr ref android.R.styleable#View_paddingRight
19676     * @attr ref android.R.styleable#View_paddingTop
19677     * @param left the left padding in pixels
19678     * @param top the top padding in pixels
19679     * @param right the right padding in pixels
19680     * @param bottom the bottom padding in pixels
19681     */
19682    public void setPadding(int left, int top, int right, int bottom) {
19683        resetResolvedPaddingInternal();
19684
19685        mUserPaddingStart = UNDEFINED_PADDING;
19686        mUserPaddingEnd = UNDEFINED_PADDING;
19687
19688        mUserPaddingLeftInitial = left;
19689        mUserPaddingRightInitial = right;
19690
19691        mLeftPaddingDefined = true;
19692        mRightPaddingDefined = true;
19693
19694        internalSetPadding(left, top, right, bottom);
19695    }
19696
19697    /**
19698     * @hide
19699     */
19700    protected void internalSetPadding(int left, int top, int right, int bottom) {
19701        mUserPaddingLeft = left;
19702        mUserPaddingRight = right;
19703        mUserPaddingBottom = bottom;
19704
19705        final int viewFlags = mViewFlags;
19706        boolean changed = false;
19707
19708        // Common case is there are no scroll bars.
19709        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
19710            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
19711                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
19712                        ? 0 : getVerticalScrollbarWidth();
19713                switch (mVerticalScrollbarPosition) {
19714                    case SCROLLBAR_POSITION_DEFAULT:
19715                        if (isLayoutRtl()) {
19716                            left += offset;
19717                        } else {
19718                            right += offset;
19719                        }
19720                        break;
19721                    case SCROLLBAR_POSITION_RIGHT:
19722                        right += offset;
19723                        break;
19724                    case SCROLLBAR_POSITION_LEFT:
19725                        left += offset;
19726                        break;
19727                }
19728            }
19729            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
19730                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
19731                        ? 0 : getHorizontalScrollbarHeight();
19732            }
19733        }
19734
19735        if (mPaddingLeft != left) {
19736            changed = true;
19737            mPaddingLeft = left;
19738        }
19739        if (mPaddingTop != top) {
19740            changed = true;
19741            mPaddingTop = top;
19742        }
19743        if (mPaddingRight != right) {
19744            changed = true;
19745            mPaddingRight = right;
19746        }
19747        if (mPaddingBottom != bottom) {
19748            changed = true;
19749            mPaddingBottom = bottom;
19750        }
19751
19752        if (changed) {
19753            requestLayout();
19754            invalidateOutline();
19755        }
19756    }
19757
19758    /**
19759     * Sets the relative padding. The view may add on the space required to display
19760     * the scrollbars, depending on the style and visibility of the scrollbars.
19761     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
19762     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
19763     * from the values set in this call.
19764     *
19765     * @attr ref android.R.styleable#View_padding
19766     * @attr ref android.R.styleable#View_paddingBottom
19767     * @attr ref android.R.styleable#View_paddingStart
19768     * @attr ref android.R.styleable#View_paddingEnd
19769     * @attr ref android.R.styleable#View_paddingTop
19770     * @param start the start padding in pixels
19771     * @param top the top padding in pixels
19772     * @param end the end padding in pixels
19773     * @param bottom the bottom padding in pixels
19774     */
19775    public void setPaddingRelative(int start, int top, int end, int bottom) {
19776        resetResolvedPaddingInternal();
19777
19778        mUserPaddingStart = start;
19779        mUserPaddingEnd = end;
19780        mLeftPaddingDefined = true;
19781        mRightPaddingDefined = true;
19782
19783        switch(getLayoutDirection()) {
19784            case LAYOUT_DIRECTION_RTL:
19785                mUserPaddingLeftInitial = end;
19786                mUserPaddingRightInitial = start;
19787                internalSetPadding(end, top, start, bottom);
19788                break;
19789            case LAYOUT_DIRECTION_LTR:
19790            default:
19791                mUserPaddingLeftInitial = start;
19792                mUserPaddingRightInitial = end;
19793                internalSetPadding(start, top, end, bottom);
19794        }
19795    }
19796
19797    /**
19798     * Returns the top padding of this view.
19799     *
19800     * @return the top padding in pixels
19801     */
19802    public int getPaddingTop() {
19803        return mPaddingTop;
19804    }
19805
19806    /**
19807     * Returns the bottom padding of this view. If there are inset and enabled
19808     * scrollbars, this value may include the space required to display the
19809     * scrollbars as well.
19810     *
19811     * @return the bottom padding in pixels
19812     */
19813    public int getPaddingBottom() {
19814        return mPaddingBottom;
19815    }
19816
19817    /**
19818     * Returns the left padding of this view. If there are inset and enabled
19819     * scrollbars, this value may include the space required to display the
19820     * scrollbars as well.
19821     *
19822     * @return the left padding in pixels
19823     */
19824    public int getPaddingLeft() {
19825        if (!isPaddingResolved()) {
19826            resolvePadding();
19827        }
19828        return mPaddingLeft;
19829    }
19830
19831    /**
19832     * Returns the start padding of this view depending on its resolved layout direction.
19833     * If there are inset and enabled scrollbars, this value may include the space
19834     * required to display the scrollbars as well.
19835     *
19836     * @return the start padding in pixels
19837     */
19838    public int getPaddingStart() {
19839        if (!isPaddingResolved()) {
19840            resolvePadding();
19841        }
19842        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19843                mPaddingRight : mPaddingLeft;
19844    }
19845
19846    /**
19847     * Returns the right padding of this view. If there are inset and enabled
19848     * scrollbars, this value may include the space required to display the
19849     * scrollbars as well.
19850     *
19851     * @return the right padding in pixels
19852     */
19853    public int getPaddingRight() {
19854        if (!isPaddingResolved()) {
19855            resolvePadding();
19856        }
19857        return mPaddingRight;
19858    }
19859
19860    /**
19861     * Returns the end padding of this view depending on its resolved layout direction.
19862     * If there are inset and enabled scrollbars, this value may include the space
19863     * required to display the scrollbars as well.
19864     *
19865     * @return the end padding in pixels
19866     */
19867    public int getPaddingEnd() {
19868        if (!isPaddingResolved()) {
19869            resolvePadding();
19870        }
19871        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19872                mPaddingLeft : mPaddingRight;
19873    }
19874
19875    /**
19876     * Return if the padding has been set through relative values
19877     * {@link #setPaddingRelative(int, int, int, int)} or through
19878     * @attr ref android.R.styleable#View_paddingStart or
19879     * @attr ref android.R.styleable#View_paddingEnd
19880     *
19881     * @return true if the padding is relative or false if it is not.
19882     */
19883    public boolean isPaddingRelative() {
19884        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
19885    }
19886
19887    Insets computeOpticalInsets() {
19888        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
19889    }
19890
19891    /**
19892     * @hide
19893     */
19894    public void resetPaddingToInitialValues() {
19895        if (isRtlCompatibilityMode()) {
19896            mPaddingLeft = mUserPaddingLeftInitial;
19897            mPaddingRight = mUserPaddingRightInitial;
19898            return;
19899        }
19900        if (isLayoutRtl()) {
19901            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
19902            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
19903        } else {
19904            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
19905            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
19906        }
19907    }
19908
19909    /**
19910     * @hide
19911     */
19912    public Insets getOpticalInsets() {
19913        if (mLayoutInsets == null) {
19914            mLayoutInsets = computeOpticalInsets();
19915        }
19916        return mLayoutInsets;
19917    }
19918
19919    /**
19920     * Set this view's optical insets.
19921     *
19922     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
19923     * property. Views that compute their own optical insets should call it as part of measurement.
19924     * This method does not request layout. If you are setting optical insets outside of
19925     * measure/layout itself you will want to call requestLayout() yourself.
19926     * </p>
19927     * @hide
19928     */
19929    public void setOpticalInsets(Insets insets) {
19930        mLayoutInsets = insets;
19931    }
19932
19933    /**
19934     * Changes the selection state of this view. A view can be selected or not.
19935     * Note that selection is not the same as focus. Views are typically
19936     * selected in the context of an AdapterView like ListView or GridView;
19937     * the selected view is the view that is highlighted.
19938     *
19939     * @param selected true if the view must be selected, false otherwise
19940     */
19941    public void setSelected(boolean selected) {
19942        //noinspection DoubleNegation
19943        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19944            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19945            if (!selected) resetPressedState();
19946            invalidate(true);
19947            refreshDrawableState();
19948            dispatchSetSelected(selected);
19949            if (selected) {
19950                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19951            } else {
19952                notifyViewAccessibilityStateChangedIfNeeded(
19953                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19954            }
19955        }
19956    }
19957
19958    /**
19959     * Dispatch setSelected to all of this View's children.
19960     *
19961     * @see #setSelected(boolean)
19962     *
19963     * @param selected The new selected state
19964     */
19965    protected void dispatchSetSelected(boolean selected) {
19966    }
19967
19968    /**
19969     * Indicates the selection state of this view.
19970     *
19971     * @return true if the view is selected, false otherwise
19972     */
19973    @ViewDebug.ExportedProperty
19974    public boolean isSelected() {
19975        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19976    }
19977
19978    /**
19979     * Changes the activated state of this view. A view can be activated or not.
19980     * Note that activation is not the same as selection.  Selection is
19981     * a transient property, representing the view (hierarchy) the user is
19982     * currently interacting with.  Activation is a longer-term state that the
19983     * user can move views in and out of.  For example, in a list view with
19984     * single or multiple selection enabled, the views in the current selection
19985     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19986     * here.)  The activated state is propagated down to children of the view it
19987     * is set on.
19988     *
19989     * @param activated true if the view must be activated, false otherwise
19990     */
19991    public void setActivated(boolean activated) {
19992        //noinspection DoubleNegation
19993        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19994            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19995            invalidate(true);
19996            refreshDrawableState();
19997            dispatchSetActivated(activated);
19998        }
19999    }
20000
20001    /**
20002     * Dispatch setActivated to all of this View's children.
20003     *
20004     * @see #setActivated(boolean)
20005     *
20006     * @param activated The new activated state
20007     */
20008    protected void dispatchSetActivated(boolean activated) {
20009    }
20010
20011    /**
20012     * Indicates the activation state of this view.
20013     *
20014     * @return true if the view is activated, false otherwise
20015     */
20016    @ViewDebug.ExportedProperty
20017    public boolean isActivated() {
20018        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
20019    }
20020
20021    /**
20022     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
20023     * observer can be used to get notifications when global events, like
20024     * layout, happen.
20025     *
20026     * The returned ViewTreeObserver observer is not guaranteed to remain
20027     * valid for the lifetime of this View. If the caller of this method keeps
20028     * a long-lived reference to ViewTreeObserver, it should always check for
20029     * the return value of {@link ViewTreeObserver#isAlive()}.
20030     *
20031     * @return The ViewTreeObserver for this view's hierarchy.
20032     */
20033    public ViewTreeObserver getViewTreeObserver() {
20034        if (mAttachInfo != null) {
20035            return mAttachInfo.mTreeObserver;
20036        }
20037        if (mFloatingTreeObserver == null) {
20038            mFloatingTreeObserver = new ViewTreeObserver(mContext);
20039        }
20040        return mFloatingTreeObserver;
20041    }
20042
20043    /**
20044     * <p>Finds the topmost view in the current view hierarchy.</p>
20045     *
20046     * @return the topmost view containing this view
20047     */
20048    public View getRootView() {
20049        if (mAttachInfo != null) {
20050            final View v = mAttachInfo.mRootView;
20051            if (v != null) {
20052                return v;
20053            }
20054        }
20055
20056        View parent = this;
20057
20058        while (parent.mParent != null && parent.mParent instanceof View) {
20059            parent = (View) parent.mParent;
20060        }
20061
20062        return parent;
20063    }
20064
20065    /**
20066     * Transforms a motion event from view-local coordinates to on-screen
20067     * coordinates.
20068     *
20069     * @param ev the view-local motion event
20070     * @return false if the transformation could not be applied
20071     * @hide
20072     */
20073    public boolean toGlobalMotionEvent(MotionEvent ev) {
20074        final AttachInfo info = mAttachInfo;
20075        if (info == null) {
20076            return false;
20077        }
20078
20079        final Matrix m = info.mTmpMatrix;
20080        m.set(Matrix.IDENTITY_MATRIX);
20081        transformMatrixToGlobal(m);
20082        ev.transform(m);
20083        return true;
20084    }
20085
20086    /**
20087     * Transforms a motion event from on-screen coordinates to view-local
20088     * coordinates.
20089     *
20090     * @param ev the on-screen motion event
20091     * @return false if the transformation could not be applied
20092     * @hide
20093     */
20094    public boolean toLocalMotionEvent(MotionEvent ev) {
20095        final AttachInfo info = mAttachInfo;
20096        if (info == null) {
20097            return false;
20098        }
20099
20100        final Matrix m = info.mTmpMatrix;
20101        m.set(Matrix.IDENTITY_MATRIX);
20102        transformMatrixToLocal(m);
20103        ev.transform(m);
20104        return true;
20105    }
20106
20107    /**
20108     * Modifies the input matrix such that it maps view-local coordinates to
20109     * on-screen coordinates.
20110     *
20111     * @param m input matrix to modify
20112     * @hide
20113     */
20114    public void transformMatrixToGlobal(Matrix m) {
20115        final ViewParent parent = mParent;
20116        if (parent instanceof View) {
20117            final View vp = (View) parent;
20118            vp.transformMatrixToGlobal(m);
20119            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
20120        } else if (parent instanceof ViewRootImpl) {
20121            final ViewRootImpl vr = (ViewRootImpl) parent;
20122            vr.transformMatrixToGlobal(m);
20123            m.preTranslate(0, -vr.mCurScrollY);
20124        }
20125
20126        m.preTranslate(mLeft, mTop);
20127
20128        if (!hasIdentityMatrix()) {
20129            m.preConcat(getMatrix());
20130        }
20131    }
20132
20133    /**
20134     * Modifies the input matrix such that it maps on-screen coordinates to
20135     * view-local coordinates.
20136     *
20137     * @param m input matrix to modify
20138     * @hide
20139     */
20140    public void transformMatrixToLocal(Matrix m) {
20141        final ViewParent parent = mParent;
20142        if (parent instanceof View) {
20143            final View vp = (View) parent;
20144            vp.transformMatrixToLocal(m);
20145            m.postTranslate(vp.mScrollX, vp.mScrollY);
20146        } else if (parent instanceof ViewRootImpl) {
20147            final ViewRootImpl vr = (ViewRootImpl) parent;
20148            vr.transformMatrixToLocal(m);
20149            m.postTranslate(0, vr.mCurScrollY);
20150        }
20151
20152        m.postTranslate(-mLeft, -mTop);
20153
20154        if (!hasIdentityMatrix()) {
20155            m.postConcat(getInverseMatrix());
20156        }
20157    }
20158
20159    /**
20160     * @hide
20161     */
20162    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
20163            @ViewDebug.IntToString(from = 0, to = "x"),
20164            @ViewDebug.IntToString(from = 1, to = "y")
20165    })
20166    public int[] getLocationOnScreen() {
20167        int[] location = new int[2];
20168        getLocationOnScreen(location);
20169        return location;
20170    }
20171
20172    /**
20173     * <p>Computes the coordinates of this view on the screen. The argument
20174     * must be an array of two integers. After the method returns, the array
20175     * contains the x and y location in that order.</p>
20176     *
20177     * @param outLocation an array of two integers in which to hold the coordinates
20178     */
20179    public void getLocationOnScreen(@Size(2) int[] outLocation) {
20180        getLocationInWindow(outLocation);
20181
20182        final AttachInfo info = mAttachInfo;
20183        if (info != null) {
20184            outLocation[0] += info.mWindowLeft;
20185            outLocation[1] += info.mWindowTop;
20186        }
20187    }
20188
20189    /**
20190     * <p>Computes the coordinates of this view in its window. The argument
20191     * must be an array of two integers. After the method returns, the array
20192     * contains the x and y location in that order.</p>
20193     *
20194     * @param outLocation an array of two integers in which to hold the coordinates
20195     */
20196    public void getLocationInWindow(@Size(2) int[] outLocation) {
20197        if (outLocation == null || outLocation.length < 2) {
20198            throw new IllegalArgumentException("outLocation must be an array of two integers");
20199        }
20200
20201        outLocation[0] = 0;
20202        outLocation[1] = 0;
20203
20204        transformFromViewToWindowSpace(outLocation);
20205    }
20206
20207    /** @hide */
20208    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
20209        if (inOutLocation == null || inOutLocation.length < 2) {
20210            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
20211        }
20212
20213        if (mAttachInfo == null) {
20214            // When the view is not attached to a window, this method does not make sense
20215            inOutLocation[0] = inOutLocation[1] = 0;
20216            return;
20217        }
20218
20219        float position[] = mAttachInfo.mTmpTransformLocation;
20220        position[0] = inOutLocation[0];
20221        position[1] = inOutLocation[1];
20222
20223        if (!hasIdentityMatrix()) {
20224            getMatrix().mapPoints(position);
20225        }
20226
20227        position[0] += mLeft;
20228        position[1] += mTop;
20229
20230        ViewParent viewParent = mParent;
20231        while (viewParent instanceof View) {
20232            final View view = (View) viewParent;
20233
20234            position[0] -= view.mScrollX;
20235            position[1] -= view.mScrollY;
20236
20237            if (!view.hasIdentityMatrix()) {
20238                view.getMatrix().mapPoints(position);
20239            }
20240
20241            position[0] += view.mLeft;
20242            position[1] += view.mTop;
20243
20244            viewParent = view.mParent;
20245         }
20246
20247        if (viewParent instanceof ViewRootImpl) {
20248            // *cough*
20249            final ViewRootImpl vr = (ViewRootImpl) viewParent;
20250            position[1] -= vr.mCurScrollY;
20251        }
20252
20253        inOutLocation[0] = Math.round(position[0]);
20254        inOutLocation[1] = Math.round(position[1]);
20255    }
20256
20257    /**
20258     * @param id the id of the view to be found
20259     * @return the view of the specified id, null if cannot be found
20260     * @hide
20261     */
20262    protected View findViewTraversal(@IdRes int id) {
20263        if (id == mID) {
20264            return this;
20265        }
20266        return null;
20267    }
20268
20269    /**
20270     * @param tag the tag of the view to be found
20271     * @return the view of specified tag, null if cannot be found
20272     * @hide
20273     */
20274    protected View findViewWithTagTraversal(Object tag) {
20275        if (tag != null && tag.equals(mTag)) {
20276            return this;
20277        }
20278        return null;
20279    }
20280
20281    /**
20282     * @param predicate The predicate to evaluate.
20283     * @param childToSkip If not null, ignores this child during the recursive traversal.
20284     * @return The first view that matches the predicate or null.
20285     * @hide
20286     */
20287    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
20288        if (predicate.test(this)) {
20289            return this;
20290        }
20291        return null;
20292    }
20293
20294    /**
20295     * Look for a child view with the given id.  If this view has the given
20296     * id, return this view.
20297     *
20298     * @param id The id to search for.
20299     * @return The view that has the given id in the hierarchy or null
20300     */
20301    @Nullable
20302    public final View findViewById(@IdRes int id) {
20303        if (id < 0) {
20304            return null;
20305        }
20306        return findViewTraversal(id);
20307    }
20308
20309    /**
20310     * Finds a view by its unuque and stable accessibility id.
20311     *
20312     * @param accessibilityId The searched accessibility id.
20313     * @return The found view.
20314     */
20315    final View findViewByAccessibilityId(int accessibilityId) {
20316        if (accessibilityId < 0) {
20317            return null;
20318        }
20319        View view = findViewByAccessibilityIdTraversal(accessibilityId);
20320        if (view != null) {
20321            return view.includeForAccessibility() ? view : null;
20322        }
20323        return null;
20324    }
20325
20326    /**
20327     * Performs the traversal to find a view by its unuque and stable accessibility id.
20328     *
20329     * <strong>Note:</strong>This method does not stop at the root namespace
20330     * boundary since the user can touch the screen at an arbitrary location
20331     * potentially crossing the root namespace bounday which will send an
20332     * accessibility event to accessibility services and they should be able
20333     * to obtain the event source. Also accessibility ids are guaranteed to be
20334     * unique in the window.
20335     *
20336     * @param accessibilityId The accessibility id.
20337     * @return The found view.
20338     *
20339     * @hide
20340     */
20341    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
20342        if (getAccessibilityViewId() == accessibilityId) {
20343            return this;
20344        }
20345        return null;
20346    }
20347
20348    /**
20349     * Look for a child view with the given tag.  If this view has the given
20350     * tag, return this view.
20351     *
20352     * @param tag The tag to search for, using "tag.equals(getTag())".
20353     * @return The View that has the given tag in the hierarchy or null
20354     */
20355    public final View findViewWithTag(Object tag) {
20356        if (tag == null) {
20357            return null;
20358        }
20359        return findViewWithTagTraversal(tag);
20360    }
20361
20362    /**
20363     * Look for a child view that matches the specified predicate.
20364     * If this view matches the predicate, return this view.
20365     *
20366     * @param predicate The predicate to evaluate.
20367     * @return The first view that matches the predicate or null.
20368     * @hide
20369     */
20370    public final View findViewByPredicate(Predicate<View> predicate) {
20371        return findViewByPredicateTraversal(predicate, null);
20372    }
20373
20374    /**
20375     * Look for a child view that matches the specified predicate,
20376     * starting with the specified view and its descendents and then
20377     * recusively searching the ancestors and siblings of that view
20378     * until this view is reached.
20379     *
20380     * This method is useful in cases where the predicate does not match
20381     * a single unique view (perhaps multiple views use the same id)
20382     * and we are trying to find the view that is "closest" in scope to the
20383     * starting view.
20384     *
20385     * @param start The view to start from.
20386     * @param predicate The predicate to evaluate.
20387     * @return The first view that matches the predicate or null.
20388     * @hide
20389     */
20390    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
20391        View childToSkip = null;
20392        for (;;) {
20393            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
20394            if (view != null || start == this) {
20395                return view;
20396            }
20397
20398            ViewParent parent = start.getParent();
20399            if (parent == null || !(parent instanceof View)) {
20400                return null;
20401            }
20402
20403            childToSkip = start;
20404            start = (View) parent;
20405        }
20406    }
20407
20408    /**
20409     * Sets the identifier for this view. The identifier does not have to be
20410     * unique in this view's hierarchy. The identifier should be a positive
20411     * number.
20412     *
20413     * @see #NO_ID
20414     * @see #getId()
20415     * @see #findViewById(int)
20416     *
20417     * @param id a number used to identify the view
20418     *
20419     * @attr ref android.R.styleable#View_id
20420     */
20421    public void setId(@IdRes int id) {
20422        mID = id;
20423        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
20424            mID = generateViewId();
20425        }
20426    }
20427
20428    /**
20429     * {@hide}
20430     *
20431     * @param isRoot true if the view belongs to the root namespace, false
20432     *        otherwise
20433     */
20434    public void setIsRootNamespace(boolean isRoot) {
20435        if (isRoot) {
20436            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
20437        } else {
20438            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
20439        }
20440    }
20441
20442    /**
20443     * {@hide}
20444     *
20445     * @return true if the view belongs to the root namespace, false otherwise
20446     */
20447    public boolean isRootNamespace() {
20448        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
20449    }
20450
20451    /**
20452     * Returns this view's identifier.
20453     *
20454     * @return a positive integer used to identify the view or {@link #NO_ID}
20455     *         if the view has no ID
20456     *
20457     * @see #setId(int)
20458     * @see #findViewById(int)
20459     * @attr ref android.R.styleable#View_id
20460     */
20461    @IdRes
20462    @ViewDebug.CapturedViewProperty
20463    public int getId() {
20464        return mID;
20465    }
20466
20467    /**
20468     * Returns this view's tag.
20469     *
20470     * @return the Object stored in this view as a tag, or {@code null} if not
20471     *         set
20472     *
20473     * @see #setTag(Object)
20474     * @see #getTag(int)
20475     */
20476    @ViewDebug.ExportedProperty
20477    public Object getTag() {
20478        return mTag;
20479    }
20480
20481    /**
20482     * Sets the tag associated with this view. A tag can be used to mark
20483     * a view in its hierarchy and does not have to be unique within the
20484     * hierarchy. Tags can also be used to store data within a view without
20485     * resorting to another data structure.
20486     *
20487     * @param tag an Object to tag the view with
20488     *
20489     * @see #getTag()
20490     * @see #setTag(int, Object)
20491     */
20492    public void setTag(final Object tag) {
20493        mTag = tag;
20494    }
20495
20496    /**
20497     * Returns the tag associated with this view and the specified key.
20498     *
20499     * @param key The key identifying the tag
20500     *
20501     * @return the Object stored in this view as a tag, or {@code null} if not
20502     *         set
20503     *
20504     * @see #setTag(int, Object)
20505     * @see #getTag()
20506     */
20507    public Object getTag(int key) {
20508        if (mKeyedTags != null) return mKeyedTags.get(key);
20509        return null;
20510    }
20511
20512    /**
20513     * Sets a tag associated with this view and a key. A tag can be used
20514     * to mark a view in its hierarchy and does not have to be unique within
20515     * the hierarchy. Tags can also be used to store data within a view
20516     * without resorting to another data structure.
20517     *
20518     * The specified key should be an id declared in the resources of the
20519     * application to ensure it is unique (see the <a
20520     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
20521     * Keys identified as belonging to
20522     * the Android framework or not associated with any package will cause
20523     * an {@link IllegalArgumentException} to be thrown.
20524     *
20525     * @param key The key identifying the tag
20526     * @param tag An Object to tag the view with
20527     *
20528     * @throws IllegalArgumentException If they specified key is not valid
20529     *
20530     * @see #setTag(Object)
20531     * @see #getTag(int)
20532     */
20533    public void setTag(int key, final Object tag) {
20534        // If the package id is 0x00 or 0x01, it's either an undefined package
20535        // or a framework id
20536        if ((key >>> 24) < 2) {
20537            throw new IllegalArgumentException("The key must be an application-specific "
20538                    + "resource id.");
20539        }
20540
20541        setKeyedTag(key, tag);
20542    }
20543
20544    /**
20545     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
20546     * framework id.
20547     *
20548     * @hide
20549     */
20550    public void setTagInternal(int key, Object tag) {
20551        if ((key >>> 24) != 0x1) {
20552            throw new IllegalArgumentException("The key must be a framework-specific "
20553                    + "resource id.");
20554        }
20555
20556        setKeyedTag(key, tag);
20557    }
20558
20559    private void setKeyedTag(int key, Object tag) {
20560        if (mKeyedTags == null) {
20561            mKeyedTags = new SparseArray<Object>(2);
20562        }
20563
20564        mKeyedTags.put(key, tag);
20565    }
20566
20567    /**
20568     * Prints information about this view in the log output, with the tag
20569     * {@link #VIEW_LOG_TAG}.
20570     *
20571     * @hide
20572     */
20573    public void debug() {
20574        debug(0);
20575    }
20576
20577    /**
20578     * Prints information about this view in the log output, with the tag
20579     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
20580     * indentation defined by the <code>depth</code>.
20581     *
20582     * @param depth the indentation level
20583     *
20584     * @hide
20585     */
20586    protected void debug(int depth) {
20587        String output = debugIndent(depth - 1);
20588
20589        output += "+ " + this;
20590        int id = getId();
20591        if (id != -1) {
20592            output += " (id=" + id + ")";
20593        }
20594        Object tag = getTag();
20595        if (tag != null) {
20596            output += " (tag=" + tag + ")";
20597        }
20598        Log.d(VIEW_LOG_TAG, output);
20599
20600        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
20601            output = debugIndent(depth) + " FOCUSED";
20602            Log.d(VIEW_LOG_TAG, output);
20603        }
20604
20605        output = debugIndent(depth);
20606        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
20607                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
20608                + "} ";
20609        Log.d(VIEW_LOG_TAG, output);
20610
20611        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
20612                || mPaddingBottom != 0) {
20613            output = debugIndent(depth);
20614            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
20615                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
20616            Log.d(VIEW_LOG_TAG, output);
20617        }
20618
20619        output = debugIndent(depth);
20620        output += "mMeasureWidth=" + mMeasuredWidth +
20621                " mMeasureHeight=" + mMeasuredHeight;
20622        Log.d(VIEW_LOG_TAG, output);
20623
20624        output = debugIndent(depth);
20625        if (mLayoutParams == null) {
20626            output += "BAD! no layout params";
20627        } else {
20628            output = mLayoutParams.debug(output);
20629        }
20630        Log.d(VIEW_LOG_TAG, output);
20631
20632        output = debugIndent(depth);
20633        output += "flags={";
20634        output += View.printFlags(mViewFlags);
20635        output += "}";
20636        Log.d(VIEW_LOG_TAG, output);
20637
20638        output = debugIndent(depth);
20639        output += "privateFlags={";
20640        output += View.printPrivateFlags(mPrivateFlags);
20641        output += "}";
20642        Log.d(VIEW_LOG_TAG, output);
20643    }
20644
20645    /**
20646     * Creates a string of whitespaces used for indentation.
20647     *
20648     * @param depth the indentation level
20649     * @return a String containing (depth * 2 + 3) * 2 white spaces
20650     *
20651     * @hide
20652     */
20653    protected static String debugIndent(int depth) {
20654        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
20655        for (int i = 0; i < (depth * 2) + 3; i++) {
20656            spaces.append(' ').append(' ');
20657        }
20658        return spaces.toString();
20659    }
20660
20661    /**
20662     * <p>Return the offset of the widget's text baseline from the widget's top
20663     * boundary. If this widget does not support baseline alignment, this
20664     * method returns -1. </p>
20665     *
20666     * @return the offset of the baseline within the widget's bounds or -1
20667     *         if baseline alignment is not supported
20668     */
20669    @ViewDebug.ExportedProperty(category = "layout")
20670    public int getBaseline() {
20671        return -1;
20672    }
20673
20674    /**
20675     * Returns whether the view hierarchy is currently undergoing a layout pass. This
20676     * information is useful to avoid situations such as calling {@link #requestLayout()} during
20677     * a layout pass.
20678     *
20679     * @return whether the view hierarchy is currently undergoing a layout pass
20680     */
20681    public boolean isInLayout() {
20682        ViewRootImpl viewRoot = getViewRootImpl();
20683        return (viewRoot != null && viewRoot.isInLayout());
20684    }
20685
20686    /**
20687     * Call this when something has changed which has invalidated the
20688     * layout of this view. This will schedule a layout pass of the view
20689     * tree. This should not be called while the view hierarchy is currently in a layout
20690     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
20691     * end of the current layout pass (and then layout will run again) or after the current
20692     * frame is drawn and the next layout occurs.
20693     *
20694     * <p>Subclasses which override this method should call the superclass method to
20695     * handle possible request-during-layout errors correctly.</p>
20696     */
20697    @CallSuper
20698    public void requestLayout() {
20699        if (mMeasureCache != null) mMeasureCache.clear();
20700
20701        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
20702            // Only trigger request-during-layout logic if this is the view requesting it,
20703            // not the views in its parent hierarchy
20704            ViewRootImpl viewRoot = getViewRootImpl();
20705            if (viewRoot != null && viewRoot.isInLayout()) {
20706                if (!viewRoot.requestLayoutDuringLayout(this)) {
20707                    return;
20708                }
20709            }
20710            mAttachInfo.mViewRequestingLayout = this;
20711        }
20712
20713        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20714        mPrivateFlags |= PFLAG_INVALIDATED;
20715
20716        if (mParent != null && !mParent.isLayoutRequested()) {
20717            mParent.requestLayout();
20718        }
20719        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
20720            mAttachInfo.mViewRequestingLayout = null;
20721        }
20722    }
20723
20724    /**
20725     * Forces this view to be laid out during the next layout pass.
20726     * This method does not call requestLayout() or forceLayout()
20727     * on the parent.
20728     */
20729    public void forceLayout() {
20730        if (mMeasureCache != null) mMeasureCache.clear();
20731
20732        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20733        mPrivateFlags |= PFLAG_INVALIDATED;
20734    }
20735
20736    /**
20737     * <p>
20738     * This is called to find out how big a view should be. The parent
20739     * supplies constraint information in the width and height parameters.
20740     * </p>
20741     *
20742     * <p>
20743     * The actual measurement work of a view is performed in
20744     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
20745     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
20746     * </p>
20747     *
20748     *
20749     * @param widthMeasureSpec Horizontal space requirements as imposed by the
20750     *        parent
20751     * @param heightMeasureSpec Vertical space requirements as imposed by the
20752     *        parent
20753     *
20754     * @see #onMeasure(int, int)
20755     */
20756    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
20757        boolean optical = isLayoutModeOptical(this);
20758        if (optical != isLayoutModeOptical(mParent)) {
20759            Insets insets = getOpticalInsets();
20760            int oWidth  = insets.left + insets.right;
20761            int oHeight = insets.top  + insets.bottom;
20762            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
20763            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
20764        }
20765
20766        // Suppress sign extension for the low bytes
20767        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
20768        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
20769
20770        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20771
20772        // Optimize layout by avoiding an extra EXACTLY pass when the view is
20773        // already measured as the correct size. In API 23 and below, this
20774        // extra pass is required to make LinearLayout re-distribute weight.
20775        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
20776                || heightMeasureSpec != mOldHeightMeasureSpec;
20777        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
20778                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
20779        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
20780                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
20781        final boolean needsLayout = specChanged
20782                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
20783
20784        if (forceLayout || needsLayout) {
20785            // first clears the measured dimension flag
20786            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
20787
20788            resolveRtlPropertiesIfNeeded();
20789
20790            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
20791            if (cacheIndex < 0 || sIgnoreMeasureCache) {
20792                // measure ourselves, this should set the measured dimension flag back
20793                onMeasure(widthMeasureSpec, heightMeasureSpec);
20794                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20795            } else {
20796                long value = mMeasureCache.valueAt(cacheIndex);
20797                // Casting a long to int drops the high 32 bits, no mask needed
20798                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
20799                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20800            }
20801
20802            // flag not set, setMeasuredDimension() was not invoked, we raise
20803            // an exception to warn the developer
20804            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
20805                throw new IllegalStateException("View with id " + getId() + ": "
20806                        + getClass().getName() + "#onMeasure() did not set the"
20807                        + " measured dimension by calling"
20808                        + " setMeasuredDimension()");
20809            }
20810
20811            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
20812        }
20813
20814        mOldWidthMeasureSpec = widthMeasureSpec;
20815        mOldHeightMeasureSpec = heightMeasureSpec;
20816
20817        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
20818                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
20819    }
20820
20821    /**
20822     * <p>
20823     * Measure the view and its content to determine the measured width and the
20824     * measured height. This method is invoked by {@link #measure(int, int)} and
20825     * should be overridden by subclasses to provide accurate and efficient
20826     * measurement of their contents.
20827     * </p>
20828     *
20829     * <p>
20830     * <strong>CONTRACT:</strong> When overriding this method, you
20831     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
20832     * measured width and height of this view. Failure to do so will trigger an
20833     * <code>IllegalStateException</code>, thrown by
20834     * {@link #measure(int, int)}. Calling the superclass'
20835     * {@link #onMeasure(int, int)} is a valid use.
20836     * </p>
20837     *
20838     * <p>
20839     * The base class implementation of measure defaults to the background size,
20840     * unless a larger size is allowed by the MeasureSpec. Subclasses should
20841     * override {@link #onMeasure(int, int)} to provide better measurements of
20842     * their content.
20843     * </p>
20844     *
20845     * <p>
20846     * If this method is overridden, it is the subclass's responsibility to make
20847     * sure the measured height and width are at least the view's minimum height
20848     * and width ({@link #getSuggestedMinimumHeight()} and
20849     * {@link #getSuggestedMinimumWidth()}).
20850     * </p>
20851     *
20852     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
20853     *                         The requirements are encoded with
20854     *                         {@link android.view.View.MeasureSpec}.
20855     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
20856     *                         The requirements are encoded with
20857     *                         {@link android.view.View.MeasureSpec}.
20858     *
20859     * @see #getMeasuredWidth()
20860     * @see #getMeasuredHeight()
20861     * @see #setMeasuredDimension(int, int)
20862     * @see #getSuggestedMinimumHeight()
20863     * @see #getSuggestedMinimumWidth()
20864     * @see android.view.View.MeasureSpec#getMode(int)
20865     * @see android.view.View.MeasureSpec#getSize(int)
20866     */
20867    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
20868        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
20869                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
20870    }
20871
20872    /**
20873     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
20874     * measured width and measured height. Failing to do so will trigger an
20875     * exception at measurement time.</p>
20876     *
20877     * @param measuredWidth The measured width of this view.  May be a complex
20878     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20879     * {@link #MEASURED_STATE_TOO_SMALL}.
20880     * @param measuredHeight The measured height of this view.  May be a complex
20881     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20882     * {@link #MEASURED_STATE_TOO_SMALL}.
20883     */
20884    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
20885        boolean optical = isLayoutModeOptical(this);
20886        if (optical != isLayoutModeOptical(mParent)) {
20887            Insets insets = getOpticalInsets();
20888            int opticalWidth  = insets.left + insets.right;
20889            int opticalHeight = insets.top  + insets.bottom;
20890
20891            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
20892            measuredHeight += optical ? opticalHeight : -opticalHeight;
20893        }
20894        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
20895    }
20896
20897    /**
20898     * Sets the measured dimension without extra processing for things like optical bounds.
20899     * Useful for reapplying consistent values that have already been cooked with adjustments
20900     * for optical bounds, etc. such as those from the measurement cache.
20901     *
20902     * @param measuredWidth The measured width of this view.  May be a complex
20903     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20904     * {@link #MEASURED_STATE_TOO_SMALL}.
20905     * @param measuredHeight The measured height of this view.  May be a complex
20906     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20907     * {@link #MEASURED_STATE_TOO_SMALL}.
20908     */
20909    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
20910        mMeasuredWidth = measuredWidth;
20911        mMeasuredHeight = measuredHeight;
20912
20913        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
20914    }
20915
20916    /**
20917     * Merge two states as returned by {@link #getMeasuredState()}.
20918     * @param curState The current state as returned from a view or the result
20919     * of combining multiple views.
20920     * @param newState The new view state to combine.
20921     * @return Returns a new integer reflecting the combination of the two
20922     * states.
20923     */
20924    public static int combineMeasuredStates(int curState, int newState) {
20925        return curState | newState;
20926    }
20927
20928    /**
20929     * Version of {@link #resolveSizeAndState(int, int, int)}
20930     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
20931     */
20932    public static int resolveSize(int size, int measureSpec) {
20933        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
20934    }
20935
20936    /**
20937     * Utility to reconcile a desired size and state, with constraints imposed
20938     * by a MeasureSpec. Will take the desired size, unless a different size
20939     * is imposed by the constraints. The returned value is a compound integer,
20940     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20941     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20942     * resulting size is smaller than the size the view wants to be.
20943     *
20944     * @param size How big the view wants to be.
20945     * @param measureSpec Constraints imposed by the parent.
20946     * @param childMeasuredState Size information bit mask for the view's
20947     *                           children.
20948     * @return Size information bit mask as defined by
20949     *         {@link #MEASURED_SIZE_MASK} and
20950     *         {@link #MEASURED_STATE_TOO_SMALL}.
20951     */
20952    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20953        final int specMode = MeasureSpec.getMode(measureSpec);
20954        final int specSize = MeasureSpec.getSize(measureSpec);
20955        final int result;
20956        switch (specMode) {
20957            case MeasureSpec.AT_MOST:
20958                if (specSize < size) {
20959                    result = specSize | MEASURED_STATE_TOO_SMALL;
20960                } else {
20961                    result = size;
20962                }
20963                break;
20964            case MeasureSpec.EXACTLY:
20965                result = specSize;
20966                break;
20967            case MeasureSpec.UNSPECIFIED:
20968            default:
20969                result = size;
20970        }
20971        return result | (childMeasuredState & MEASURED_STATE_MASK);
20972    }
20973
20974    /**
20975     * Utility to return a default size. Uses the supplied size if the
20976     * MeasureSpec imposed no constraints. Will get larger if allowed
20977     * by the MeasureSpec.
20978     *
20979     * @param size Default size for this view
20980     * @param measureSpec Constraints imposed by the parent
20981     * @return The size this view should be.
20982     */
20983    public static int getDefaultSize(int size, int measureSpec) {
20984        int result = size;
20985        int specMode = MeasureSpec.getMode(measureSpec);
20986        int specSize = MeasureSpec.getSize(measureSpec);
20987
20988        switch (specMode) {
20989        case MeasureSpec.UNSPECIFIED:
20990            result = size;
20991            break;
20992        case MeasureSpec.AT_MOST:
20993        case MeasureSpec.EXACTLY:
20994            result = specSize;
20995            break;
20996        }
20997        return result;
20998    }
20999
21000    /**
21001     * Returns the suggested minimum height that the view should use. This
21002     * returns the maximum of the view's minimum height
21003     * and the background's minimum height
21004     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
21005     * <p>
21006     * When being used in {@link #onMeasure(int, int)}, the caller should still
21007     * ensure the returned height is within the requirements of the parent.
21008     *
21009     * @return The suggested minimum height of the view.
21010     */
21011    protected int getSuggestedMinimumHeight() {
21012        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
21013
21014    }
21015
21016    /**
21017     * Returns the suggested minimum width that the view should use. This
21018     * returns the maximum of the view's minimum width
21019     * and the background's minimum width
21020     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
21021     * <p>
21022     * When being used in {@link #onMeasure(int, int)}, the caller should still
21023     * ensure the returned width is within the requirements of the parent.
21024     *
21025     * @return The suggested minimum width of the view.
21026     */
21027    protected int getSuggestedMinimumWidth() {
21028        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
21029    }
21030
21031    /**
21032     * Returns the minimum height of the view.
21033     *
21034     * @return the minimum height the view will try to be, in pixels
21035     *
21036     * @see #setMinimumHeight(int)
21037     *
21038     * @attr ref android.R.styleable#View_minHeight
21039     */
21040    public int getMinimumHeight() {
21041        return mMinHeight;
21042    }
21043
21044    /**
21045     * Sets the minimum height of the view. It is not guaranteed the view will
21046     * be able to achieve this minimum height (for example, if its parent layout
21047     * constrains it with less available height).
21048     *
21049     * @param minHeight The minimum height the view will try to be, in pixels
21050     *
21051     * @see #getMinimumHeight()
21052     *
21053     * @attr ref android.R.styleable#View_minHeight
21054     */
21055    @RemotableViewMethod
21056    public void setMinimumHeight(int minHeight) {
21057        mMinHeight = minHeight;
21058        requestLayout();
21059    }
21060
21061    /**
21062     * Returns the minimum width of the view.
21063     *
21064     * @return the minimum width the view will try to be, in pixels
21065     *
21066     * @see #setMinimumWidth(int)
21067     *
21068     * @attr ref android.R.styleable#View_minWidth
21069     */
21070    public int getMinimumWidth() {
21071        return mMinWidth;
21072    }
21073
21074    /**
21075     * Sets the minimum width of the view. It is not guaranteed the view will
21076     * be able to achieve this minimum width (for example, if its parent layout
21077     * constrains it with less available width).
21078     *
21079     * @param minWidth The minimum width the view will try to be, in pixels
21080     *
21081     * @see #getMinimumWidth()
21082     *
21083     * @attr ref android.R.styleable#View_minWidth
21084     */
21085    public void setMinimumWidth(int minWidth) {
21086        mMinWidth = minWidth;
21087        requestLayout();
21088
21089    }
21090
21091    /**
21092     * Get the animation currently associated with this view.
21093     *
21094     * @return The animation that is currently playing or
21095     *         scheduled to play for this view.
21096     */
21097    public Animation getAnimation() {
21098        return mCurrentAnimation;
21099    }
21100
21101    /**
21102     * Start the specified animation now.
21103     *
21104     * @param animation the animation to start now
21105     */
21106    public void startAnimation(Animation animation) {
21107        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
21108        setAnimation(animation);
21109        invalidateParentCaches();
21110        invalidate(true);
21111    }
21112
21113    /**
21114     * Cancels any animations for this view.
21115     */
21116    public void clearAnimation() {
21117        if (mCurrentAnimation != null) {
21118            mCurrentAnimation.detach();
21119        }
21120        mCurrentAnimation = null;
21121        invalidateParentIfNeeded();
21122    }
21123
21124    /**
21125     * Sets the next animation to play for this view.
21126     * If you want the animation to play immediately, use
21127     * {@link #startAnimation(android.view.animation.Animation)} instead.
21128     * This method provides allows fine-grained
21129     * control over the start time and invalidation, but you
21130     * must make sure that 1) the animation has a start time set, and
21131     * 2) the view's parent (which controls animations on its children)
21132     * will be invalidated when the animation is supposed to
21133     * start.
21134     *
21135     * @param animation The next animation, or null.
21136     */
21137    public void setAnimation(Animation animation) {
21138        mCurrentAnimation = animation;
21139
21140        if (animation != null) {
21141            // If the screen is off assume the animation start time is now instead of
21142            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
21143            // would cause the animation to start when the screen turns back on
21144            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
21145                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
21146                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
21147            }
21148            animation.reset();
21149        }
21150    }
21151
21152    /**
21153     * Invoked by a parent ViewGroup to notify the start of the animation
21154     * currently associated with this view. If you override this method,
21155     * always call super.onAnimationStart();
21156     *
21157     * @see #setAnimation(android.view.animation.Animation)
21158     * @see #getAnimation()
21159     */
21160    @CallSuper
21161    protected void onAnimationStart() {
21162        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
21163    }
21164
21165    /**
21166     * Invoked by a parent ViewGroup to notify the end of the animation
21167     * currently associated with this view. If you override this method,
21168     * always call super.onAnimationEnd();
21169     *
21170     * @see #setAnimation(android.view.animation.Animation)
21171     * @see #getAnimation()
21172     */
21173    @CallSuper
21174    protected void onAnimationEnd() {
21175        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
21176    }
21177
21178    /**
21179     * Invoked if there is a Transform that involves alpha. Subclass that can
21180     * draw themselves with the specified alpha should return true, and then
21181     * respect that alpha when their onDraw() is called. If this returns false
21182     * then the view may be redirected to draw into an offscreen buffer to
21183     * fulfill the request, which will look fine, but may be slower than if the
21184     * subclass handles it internally. The default implementation returns false.
21185     *
21186     * @param alpha The alpha (0..255) to apply to the view's drawing
21187     * @return true if the view can draw with the specified alpha.
21188     */
21189    protected boolean onSetAlpha(int alpha) {
21190        return false;
21191    }
21192
21193    /**
21194     * This is used by the RootView to perform an optimization when
21195     * the view hierarchy contains one or several SurfaceView.
21196     * SurfaceView is always considered transparent, but its children are not,
21197     * therefore all View objects remove themselves from the global transparent
21198     * region (passed as a parameter to this function).
21199     *
21200     * @param region The transparent region for this ViewAncestor (window).
21201     *
21202     * @return Returns true if the effective visibility of the view at this
21203     * point is opaque, regardless of the transparent region; returns false
21204     * if it is possible for underlying windows to be seen behind the view.
21205     *
21206     * {@hide}
21207     */
21208    public boolean gatherTransparentRegion(Region region) {
21209        final AttachInfo attachInfo = mAttachInfo;
21210        if (region != null && attachInfo != null) {
21211            final int pflags = mPrivateFlags;
21212            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
21213                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
21214                // remove it from the transparent region.
21215                final int[] location = attachInfo.mTransparentLocation;
21216                getLocationInWindow(location);
21217                // When a view has Z value, then it will be better to leave some area below the view
21218                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
21219                // the bottom part needs more offset than the left, top and right parts due to the
21220                // spot light effects.
21221                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
21222                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
21223                        location[0] + mRight - mLeft + shadowOffset,
21224                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
21225            } else {
21226                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
21227                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
21228                    // the background drawable's non-transparent parts from this transparent region.
21229                    applyDrawableToTransparentRegion(mBackground, region);
21230                }
21231                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
21232                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
21233                    // Similarly, we remove the foreground drawable's non-transparent parts.
21234                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
21235                }
21236            }
21237        }
21238        return true;
21239    }
21240
21241    /**
21242     * Play a sound effect for this view.
21243     *
21244     * <p>The framework will play sound effects for some built in actions, such as
21245     * clicking, but you may wish to play these effects in your widget,
21246     * for instance, for internal navigation.
21247     *
21248     * <p>The sound effect will only be played if sound effects are enabled by the user, and
21249     * {@link #isSoundEffectsEnabled()} is true.
21250     *
21251     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
21252     */
21253    public void playSoundEffect(int soundConstant) {
21254        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
21255            return;
21256        }
21257        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
21258    }
21259
21260    /**
21261     * BZZZTT!!1!
21262     *
21263     * <p>Provide haptic feedback to the user for this view.
21264     *
21265     * <p>The framework will provide haptic feedback for some built in actions,
21266     * such as long presses, but you may wish to provide feedback for your
21267     * own widget.
21268     *
21269     * <p>The feedback will only be performed if
21270     * {@link #isHapticFeedbackEnabled()} is true.
21271     *
21272     * @param feedbackConstant One of the constants defined in
21273     * {@link HapticFeedbackConstants}
21274     */
21275    public boolean performHapticFeedback(int feedbackConstant) {
21276        return performHapticFeedback(feedbackConstant, 0);
21277    }
21278
21279    /**
21280     * BZZZTT!!1!
21281     *
21282     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
21283     *
21284     * @param feedbackConstant One of the constants defined in
21285     * {@link HapticFeedbackConstants}
21286     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
21287     */
21288    public boolean performHapticFeedback(int feedbackConstant, int flags) {
21289        if (mAttachInfo == null) {
21290            return false;
21291        }
21292        //noinspection SimplifiableIfStatement
21293        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
21294                && !isHapticFeedbackEnabled()) {
21295            return false;
21296        }
21297        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
21298                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
21299    }
21300
21301    /**
21302     * Request that the visibility of the status bar or other screen/window
21303     * decorations be changed.
21304     *
21305     * <p>This method is used to put the over device UI into temporary modes
21306     * where the user's attention is focused more on the application content,
21307     * by dimming or hiding surrounding system affordances.  This is typically
21308     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
21309     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
21310     * to be placed behind the action bar (and with these flags other system
21311     * affordances) so that smooth transitions between hiding and showing them
21312     * can be done.
21313     *
21314     * <p>Two representative examples of the use of system UI visibility is
21315     * implementing a content browsing application (like a magazine reader)
21316     * and a video playing application.
21317     *
21318     * <p>The first code shows a typical implementation of a View in a content
21319     * browsing application.  In this implementation, the application goes
21320     * into a content-oriented mode by hiding the status bar and action bar,
21321     * and putting the navigation elements into lights out mode.  The user can
21322     * then interact with content while in this mode.  Such an application should
21323     * provide an easy way for the user to toggle out of the mode (such as to
21324     * check information in the status bar or access notifications).  In the
21325     * implementation here, this is done simply by tapping on the content.
21326     *
21327     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
21328     *      content}
21329     *
21330     * <p>This second code sample shows a typical implementation of a View
21331     * in a video playing application.  In this situation, while the video is
21332     * playing the application would like to go into a complete full-screen mode,
21333     * to use as much of the display as possible for the video.  When in this state
21334     * the user can not interact with the application; the system intercepts
21335     * touching on the screen to pop the UI out of full screen mode.  See
21336     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
21337     *
21338     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
21339     *      content}
21340     *
21341     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21342     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21343     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21344     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21345     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21346     */
21347    public void setSystemUiVisibility(int visibility) {
21348        if (visibility != mSystemUiVisibility) {
21349            mSystemUiVisibility = visibility;
21350            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21351                mParent.recomputeViewAttributes(this);
21352            }
21353        }
21354    }
21355
21356    /**
21357     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
21358     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21359     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21360     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21361     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21362     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21363     */
21364    public int getSystemUiVisibility() {
21365        return mSystemUiVisibility;
21366    }
21367
21368    /**
21369     * Returns the current system UI visibility that is currently set for
21370     * the entire window.  This is the combination of the
21371     * {@link #setSystemUiVisibility(int)} values supplied by all of the
21372     * views in the window.
21373     */
21374    public int getWindowSystemUiVisibility() {
21375        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
21376    }
21377
21378    /**
21379     * Override to find out when the window's requested system UI visibility
21380     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
21381     * This is different from the callbacks received through
21382     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
21383     * in that this is only telling you about the local request of the window,
21384     * not the actual values applied by the system.
21385     */
21386    public void onWindowSystemUiVisibilityChanged(int visible) {
21387    }
21388
21389    /**
21390     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
21391     * the view hierarchy.
21392     */
21393    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
21394        onWindowSystemUiVisibilityChanged(visible);
21395    }
21396
21397    /**
21398     * Set a listener to receive callbacks when the visibility of the system bar changes.
21399     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
21400     */
21401    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
21402        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
21403        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21404            mParent.recomputeViewAttributes(this);
21405        }
21406    }
21407
21408    /**
21409     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
21410     * the view hierarchy.
21411     */
21412    public void dispatchSystemUiVisibilityChanged(int visibility) {
21413        ListenerInfo li = mListenerInfo;
21414        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
21415            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
21416                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
21417        }
21418    }
21419
21420    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
21421        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
21422        if (val != mSystemUiVisibility) {
21423            setSystemUiVisibility(val);
21424            return true;
21425        }
21426        return false;
21427    }
21428
21429    /** @hide */
21430    public void setDisabledSystemUiVisibility(int flags) {
21431        if (mAttachInfo != null) {
21432            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
21433                mAttachInfo.mDisabledSystemUiVisibility = flags;
21434                if (mParent != null) {
21435                    mParent.recomputeViewAttributes(this);
21436                }
21437            }
21438        }
21439    }
21440
21441    /**
21442     * Creates an image that the system displays during the drag and drop
21443     * operation. This is called a &quot;drag shadow&quot;. The default implementation
21444     * for a DragShadowBuilder based on a View returns an image that has exactly the same
21445     * appearance as the given View. The default also positions the center of the drag shadow
21446     * directly under the touch point. If no View is provided (the constructor with no parameters
21447     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
21448     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
21449     * default is an invisible drag shadow.
21450     * <p>
21451     * You are not required to use the View you provide to the constructor as the basis of the
21452     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
21453     * anything you want as the drag shadow.
21454     * </p>
21455     * <p>
21456     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
21457     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
21458     *  size and position of the drag shadow. It uses this data to construct a
21459     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
21460     *  so that your application can draw the shadow image in the Canvas.
21461     * </p>
21462     *
21463     * <div class="special reference">
21464     * <h3>Developer Guides</h3>
21465     * <p>For a guide to implementing drag and drop features, read the
21466     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
21467     * </div>
21468     */
21469    public static class DragShadowBuilder {
21470        private final WeakReference<View> mView;
21471
21472        /**
21473         * Constructs a shadow image builder based on a View. By default, the resulting drag
21474         * shadow will have the same appearance and dimensions as the View, with the touch point
21475         * over the center of the View.
21476         * @param view A View. Any View in scope can be used.
21477         */
21478        public DragShadowBuilder(View view) {
21479            mView = new WeakReference<View>(view);
21480        }
21481
21482        /**
21483         * Construct a shadow builder object with no associated View.  This
21484         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
21485         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
21486         * to supply the drag shadow's dimensions and appearance without
21487         * reference to any View object. If they are not overridden, then the result is an
21488         * invisible drag shadow.
21489         */
21490        public DragShadowBuilder() {
21491            mView = new WeakReference<View>(null);
21492        }
21493
21494        /**
21495         * Returns the View object that had been passed to the
21496         * {@link #View.DragShadowBuilder(View)}
21497         * constructor.  If that View parameter was {@code null} or if the
21498         * {@link #View.DragShadowBuilder()}
21499         * constructor was used to instantiate the builder object, this method will return
21500         * null.
21501         *
21502         * @return The View object associate with this builder object.
21503         */
21504        @SuppressWarnings({"JavadocReference"})
21505        final public View getView() {
21506            return mView.get();
21507        }
21508
21509        /**
21510         * Provides the metrics for the shadow image. These include the dimensions of
21511         * the shadow image, and the point within that shadow that should
21512         * be centered under the touch location while dragging.
21513         * <p>
21514         * The default implementation sets the dimensions of the shadow to be the
21515         * same as the dimensions of the View itself and centers the shadow under
21516         * the touch point.
21517         * </p>
21518         *
21519         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
21520         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
21521         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
21522         * image.
21523         *
21524         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
21525         * shadow image that should be underneath the touch point during the drag and drop
21526         * operation. Your application must set {@link android.graphics.Point#x} to the
21527         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
21528         */
21529        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
21530            final View view = mView.get();
21531            if (view != null) {
21532                outShadowSize.set(view.getWidth(), view.getHeight());
21533                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
21534            } else {
21535                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
21536            }
21537        }
21538
21539        /**
21540         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
21541         * based on the dimensions it received from the
21542         * {@link #onProvideShadowMetrics(Point, Point)} callback.
21543         *
21544         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
21545         */
21546        public void onDrawShadow(Canvas canvas) {
21547            final View view = mView.get();
21548            if (view != null) {
21549                view.draw(canvas);
21550            } else {
21551                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
21552            }
21553        }
21554    }
21555
21556    /**
21557     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
21558     * startDragAndDrop()} for newer platform versions.
21559     */
21560    @Deprecated
21561    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
21562                                   Object myLocalState, int flags) {
21563        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
21564    }
21565
21566    /**
21567     * Starts a drag and drop operation. When your application calls this method, it passes a
21568     * {@link android.view.View.DragShadowBuilder} object to the system. The
21569     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
21570     * to get metrics for the drag shadow, and then calls the object's
21571     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
21572     * <p>
21573     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
21574     *  drag events to all the View objects in your application that are currently visible. It does
21575     *  this either by calling the View object's drag listener (an implementation of
21576     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
21577     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
21578     *  Both are passed a {@link android.view.DragEvent} object that has a
21579     *  {@link android.view.DragEvent#getAction()} value of
21580     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
21581     * </p>
21582     * <p>
21583     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
21584     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
21585     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
21586     * to the View the user selected for dragging.
21587     * </p>
21588     * @param data A {@link android.content.ClipData} object pointing to the data to be
21589     * transferred by the drag and drop operation.
21590     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21591     * drag shadow.
21592     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
21593     * drop operation. When dispatching drag events to views in the same activity this object
21594     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
21595     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
21596     * will return null).
21597     * <p>
21598     * myLocalState is a lightweight mechanism for the sending information from the dragged View
21599     * to the target Views. For example, it can contain flags that differentiate between a
21600     * a copy operation and a move operation.
21601     * </p>
21602     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
21603     * flags, or any combination of the following:
21604     *     <ul>
21605     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
21606     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
21607     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
21608     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
21609     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
21610     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
21611     *     </ul>
21612     * @return {@code true} if the method completes successfully, or
21613     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
21614     * do a drag, and so no drag operation is in progress.
21615     */
21616    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
21617            Object myLocalState, int flags) {
21618        if (ViewDebug.DEBUG_DRAG) {
21619            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
21620        }
21621        if (mAttachInfo == null) {
21622            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
21623            return false;
21624        }
21625
21626        if (data != null) {
21627            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
21628        }
21629
21630        boolean okay = false;
21631
21632        Point shadowSize = new Point();
21633        Point shadowTouchPoint = new Point();
21634        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
21635
21636        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
21637                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
21638            throw new IllegalStateException("Drag shadow dimensions must not be negative");
21639        }
21640
21641        if (ViewDebug.DEBUG_DRAG) {
21642            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
21643                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
21644        }
21645        if (mAttachInfo.mDragSurface != null) {
21646            mAttachInfo.mDragSurface.release();
21647        }
21648        mAttachInfo.mDragSurface = new Surface();
21649        try {
21650            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
21651                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
21652            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
21653                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
21654            if (mAttachInfo.mDragToken != null) {
21655                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21656                try {
21657                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21658                    shadowBuilder.onDrawShadow(canvas);
21659                } finally {
21660                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21661                }
21662
21663                final ViewRootImpl root = getViewRootImpl();
21664
21665                // Cache the local state object for delivery with DragEvents
21666                root.setLocalDragState(myLocalState);
21667
21668                // repurpose 'shadowSize' for the last touch point
21669                root.getLastTouchPoint(shadowSize);
21670
21671                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
21672                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
21673                        shadowTouchPoint.x, shadowTouchPoint.y, data);
21674                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
21675            }
21676        } catch (Exception e) {
21677            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
21678            mAttachInfo.mDragSurface.destroy();
21679            mAttachInfo.mDragSurface = null;
21680        }
21681
21682        return okay;
21683    }
21684
21685    /**
21686     * Cancels an ongoing drag and drop operation.
21687     * <p>
21688     * A {@link android.view.DragEvent} object with
21689     * {@link android.view.DragEvent#getAction()} value of
21690     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
21691     * {@link android.view.DragEvent#getResult()} value of {@code false}
21692     * will be sent to every
21693     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
21694     * even if they are not currently visible.
21695     * </p>
21696     * <p>
21697     * This method can be called on any View in the same window as the View on which
21698     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
21699     * was called.
21700     * </p>
21701     */
21702    public final void cancelDragAndDrop() {
21703        if (ViewDebug.DEBUG_DRAG) {
21704            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
21705        }
21706        if (mAttachInfo == null) {
21707            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
21708            return;
21709        }
21710        if (mAttachInfo.mDragToken != null) {
21711            try {
21712                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
21713            } catch (Exception e) {
21714                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
21715            }
21716            mAttachInfo.mDragToken = null;
21717        } else {
21718            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
21719        }
21720    }
21721
21722    /**
21723     * Updates the drag shadow for the ongoing drag and drop operation.
21724     *
21725     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21726     * new drag shadow.
21727     */
21728    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
21729        if (ViewDebug.DEBUG_DRAG) {
21730            Log.d(VIEW_LOG_TAG, "updateDragShadow");
21731        }
21732        if (mAttachInfo == null) {
21733            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
21734            return;
21735        }
21736        if (mAttachInfo.mDragToken != null) {
21737            try {
21738                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21739                try {
21740                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21741                    shadowBuilder.onDrawShadow(canvas);
21742                } finally {
21743                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21744                }
21745            } catch (Exception e) {
21746                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
21747            }
21748        } else {
21749            Log.e(VIEW_LOG_TAG, "No active drag");
21750        }
21751    }
21752
21753    /**
21754     * Starts a move from {startX, startY}, the amount of the movement will be the offset
21755     * between {startX, startY} and the new cursor positon.
21756     * @param startX horizontal coordinate where the move started.
21757     * @param startY vertical coordinate where the move started.
21758     * @return whether moving was started successfully.
21759     * @hide
21760     */
21761    public final boolean startMovingTask(float startX, float startY) {
21762        if (ViewDebug.DEBUG_POSITIONING) {
21763            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
21764        }
21765        try {
21766            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
21767        } catch (RemoteException e) {
21768            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
21769        }
21770        return false;
21771    }
21772
21773    /**
21774     * Handles drag events sent by the system following a call to
21775     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
21776     * startDragAndDrop()}.
21777     *<p>
21778     * When the system calls this method, it passes a
21779     * {@link android.view.DragEvent} object. A call to
21780     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
21781     * in DragEvent. The method uses these to determine what is happening in the drag and drop
21782     * operation.
21783     * @param event The {@link android.view.DragEvent} sent by the system.
21784     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
21785     * in DragEvent, indicating the type of drag event represented by this object.
21786     * @return {@code true} if the method was successful, otherwise {@code false}.
21787     * <p>
21788     *  The method should return {@code true} in response to an action type of
21789     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
21790     *  operation.
21791     * </p>
21792     * <p>
21793     *  The method should also return {@code true} in response to an action type of
21794     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
21795     *  {@code false} if it didn't.
21796     * </p>
21797     * <p>
21798     *  For all other events, the return value is ignored.
21799     * </p>
21800     */
21801    public boolean onDragEvent(DragEvent event) {
21802        return false;
21803    }
21804
21805    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
21806    boolean dispatchDragEnterExitInPreN(DragEvent event) {
21807        return callDragEventHandler(event);
21808    }
21809
21810    /**
21811     * Detects if this View is enabled and has a drag event listener.
21812     * If both are true, then it calls the drag event listener with the
21813     * {@link android.view.DragEvent} it received. If the drag event listener returns
21814     * {@code true}, then dispatchDragEvent() returns {@code true}.
21815     * <p>
21816     * For all other cases, the method calls the
21817     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
21818     * method and returns its result.
21819     * </p>
21820     * <p>
21821     * This ensures that a drag event is always consumed, even if the View does not have a drag
21822     * event listener. However, if the View has a listener and the listener returns true, then
21823     * onDragEvent() is not called.
21824     * </p>
21825     */
21826    public boolean dispatchDragEvent(DragEvent event) {
21827        event.mEventHandlerWasCalled = true;
21828        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
21829            event.mAction == DragEvent.ACTION_DROP) {
21830            // About to deliver an event with coordinates to this view. Notify that now this view
21831            // has drag focus. This will send exit/enter events as needed.
21832            getViewRootImpl().setDragFocus(this, event);
21833        }
21834        return callDragEventHandler(event);
21835    }
21836
21837    final boolean callDragEventHandler(DragEvent event) {
21838        final boolean result;
21839
21840        ListenerInfo li = mListenerInfo;
21841        //noinspection SimplifiableIfStatement
21842        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
21843                && li.mOnDragListener.onDrag(this, event)) {
21844            result = true;
21845        } else {
21846            result = onDragEvent(event);
21847        }
21848
21849        switch (event.mAction) {
21850            case DragEvent.ACTION_DRAG_ENTERED: {
21851                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
21852                refreshDrawableState();
21853            } break;
21854            case DragEvent.ACTION_DRAG_EXITED: {
21855                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
21856                refreshDrawableState();
21857            } break;
21858            case DragEvent.ACTION_DRAG_ENDED: {
21859                mPrivateFlags2 &= ~View.DRAG_MASK;
21860                refreshDrawableState();
21861            } break;
21862        }
21863
21864        return result;
21865    }
21866
21867    boolean canAcceptDrag() {
21868        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
21869    }
21870
21871    /**
21872     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
21873     * it is ever exposed at all.
21874     * @hide
21875     */
21876    public void onCloseSystemDialogs(String reason) {
21877    }
21878
21879    /**
21880     * Given a Drawable whose bounds have been set to draw into this view,
21881     * update a Region being computed for
21882     * {@link #gatherTransparentRegion(android.graphics.Region)} so
21883     * that any non-transparent parts of the Drawable are removed from the
21884     * given transparent region.
21885     *
21886     * @param dr The Drawable whose transparency is to be applied to the region.
21887     * @param region A Region holding the current transparency information,
21888     * where any parts of the region that are set are considered to be
21889     * transparent.  On return, this region will be modified to have the
21890     * transparency information reduced by the corresponding parts of the
21891     * Drawable that are not transparent.
21892     * {@hide}
21893     */
21894    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
21895        if (DBG) {
21896            Log.i("View", "Getting transparent region for: " + this);
21897        }
21898        final Region r = dr.getTransparentRegion();
21899        final Rect db = dr.getBounds();
21900        final AttachInfo attachInfo = mAttachInfo;
21901        if (r != null && attachInfo != null) {
21902            final int w = getRight()-getLeft();
21903            final int h = getBottom()-getTop();
21904            if (db.left > 0) {
21905                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
21906                r.op(0, 0, db.left, h, Region.Op.UNION);
21907            }
21908            if (db.right < w) {
21909                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
21910                r.op(db.right, 0, w, h, Region.Op.UNION);
21911            }
21912            if (db.top > 0) {
21913                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
21914                r.op(0, 0, w, db.top, Region.Op.UNION);
21915            }
21916            if (db.bottom < h) {
21917                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
21918                r.op(0, db.bottom, w, h, Region.Op.UNION);
21919            }
21920            final int[] location = attachInfo.mTransparentLocation;
21921            getLocationInWindow(location);
21922            r.translate(location[0], location[1]);
21923            region.op(r, Region.Op.INTERSECT);
21924        } else {
21925            region.op(db, Region.Op.DIFFERENCE);
21926        }
21927    }
21928
21929    private void checkForLongClick(int delayOffset, float x, float y) {
21930        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
21931            mHasPerformedLongPress = false;
21932
21933            if (mPendingCheckForLongPress == null) {
21934                mPendingCheckForLongPress = new CheckForLongPress();
21935            }
21936            mPendingCheckForLongPress.setAnchor(x, y);
21937            mPendingCheckForLongPress.rememberWindowAttachCount();
21938            mPendingCheckForLongPress.rememberPressedState();
21939            postDelayed(mPendingCheckForLongPress,
21940                    ViewConfiguration.getLongPressTimeout() - delayOffset);
21941        }
21942    }
21943
21944    /**
21945     * Inflate a view from an XML resource.  This convenience method wraps the {@link
21946     * LayoutInflater} class, which provides a full range of options for view inflation.
21947     *
21948     * @param context The Context object for your activity or application.
21949     * @param resource The resource ID to inflate
21950     * @param root A view group that will be the parent.  Used to properly inflate the
21951     * layout_* parameters.
21952     * @see LayoutInflater
21953     */
21954    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
21955        LayoutInflater factory = LayoutInflater.from(context);
21956        return factory.inflate(resource, root);
21957    }
21958
21959    /**
21960     * Scroll the view with standard behavior for scrolling beyond the normal
21961     * content boundaries. Views that call this method should override
21962     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
21963     * results of an over-scroll operation.
21964     *
21965     * Views can use this method to handle any touch or fling-based scrolling.
21966     *
21967     * @param deltaX Change in X in pixels
21968     * @param deltaY Change in Y in pixels
21969     * @param scrollX Current X scroll value in pixels before applying deltaX
21970     * @param scrollY Current Y scroll value in pixels before applying deltaY
21971     * @param scrollRangeX Maximum content scroll range along the X axis
21972     * @param scrollRangeY Maximum content scroll range along the Y axis
21973     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21974     *          along the X axis.
21975     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21976     *          along the Y axis.
21977     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21978     * @return true if scrolling was clamped to an over-scroll boundary along either
21979     *          axis, false otherwise.
21980     */
21981    @SuppressWarnings({"UnusedParameters"})
21982    protected boolean overScrollBy(int deltaX, int deltaY,
21983            int scrollX, int scrollY,
21984            int scrollRangeX, int scrollRangeY,
21985            int maxOverScrollX, int maxOverScrollY,
21986            boolean isTouchEvent) {
21987        final int overScrollMode = mOverScrollMode;
21988        final boolean canScrollHorizontal =
21989                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21990        final boolean canScrollVertical =
21991                computeVerticalScrollRange() > computeVerticalScrollExtent();
21992        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21993                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21994        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21995                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21996
21997        int newScrollX = scrollX + deltaX;
21998        if (!overScrollHorizontal) {
21999            maxOverScrollX = 0;
22000        }
22001
22002        int newScrollY = scrollY + deltaY;
22003        if (!overScrollVertical) {
22004            maxOverScrollY = 0;
22005        }
22006
22007        // Clamp values if at the limits and record
22008        final int left = -maxOverScrollX;
22009        final int right = maxOverScrollX + scrollRangeX;
22010        final int top = -maxOverScrollY;
22011        final int bottom = maxOverScrollY + scrollRangeY;
22012
22013        boolean clampedX = false;
22014        if (newScrollX > right) {
22015            newScrollX = right;
22016            clampedX = true;
22017        } else if (newScrollX < left) {
22018            newScrollX = left;
22019            clampedX = true;
22020        }
22021
22022        boolean clampedY = false;
22023        if (newScrollY > bottom) {
22024            newScrollY = bottom;
22025            clampedY = true;
22026        } else if (newScrollY < top) {
22027            newScrollY = top;
22028            clampedY = true;
22029        }
22030
22031        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
22032
22033        return clampedX || clampedY;
22034    }
22035
22036    /**
22037     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
22038     * respond to the results of an over-scroll operation.
22039     *
22040     * @param scrollX New X scroll value in pixels
22041     * @param scrollY New Y scroll value in pixels
22042     * @param clampedX True if scrollX was clamped to an over-scroll boundary
22043     * @param clampedY True if scrollY was clamped to an over-scroll boundary
22044     */
22045    protected void onOverScrolled(int scrollX, int scrollY,
22046            boolean clampedX, boolean clampedY) {
22047        // Intentionally empty.
22048    }
22049
22050    /**
22051     * Returns the over-scroll mode for this view. The result will be
22052     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22053     * (allow over-scrolling only if the view content is larger than the container),
22054     * or {@link #OVER_SCROLL_NEVER}.
22055     *
22056     * @return This view's over-scroll mode.
22057     */
22058    public int getOverScrollMode() {
22059        return mOverScrollMode;
22060    }
22061
22062    /**
22063     * Set the over-scroll mode for this view. Valid over-scroll modes are
22064     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22065     * (allow over-scrolling only if the view content is larger than the container),
22066     * or {@link #OVER_SCROLL_NEVER}.
22067     *
22068     * Setting the over-scroll mode of a view will have an effect only if the
22069     * view is capable of scrolling.
22070     *
22071     * @param overScrollMode The new over-scroll mode for this view.
22072     */
22073    public void setOverScrollMode(int overScrollMode) {
22074        if (overScrollMode != OVER_SCROLL_ALWAYS &&
22075                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
22076                overScrollMode != OVER_SCROLL_NEVER) {
22077            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
22078        }
22079        mOverScrollMode = overScrollMode;
22080    }
22081
22082    /**
22083     * Enable or disable nested scrolling for this view.
22084     *
22085     * <p>If this property is set to true the view will be permitted to initiate nested
22086     * scrolling operations with a compatible parent view in the current hierarchy. If this
22087     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
22088     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
22089     * the nested scroll.</p>
22090     *
22091     * @param enabled true to enable nested scrolling, false to disable
22092     *
22093     * @see #isNestedScrollingEnabled()
22094     */
22095    public void setNestedScrollingEnabled(boolean enabled) {
22096        if (enabled) {
22097            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
22098        } else {
22099            stopNestedScroll();
22100            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
22101        }
22102    }
22103
22104    /**
22105     * Returns true if nested scrolling is enabled for this view.
22106     *
22107     * <p>If nested scrolling is enabled and this View class implementation supports it,
22108     * this view will act as a nested scrolling child view when applicable, forwarding data
22109     * about the scroll operation in progress to a compatible and cooperating nested scrolling
22110     * parent.</p>
22111     *
22112     * @return true if nested scrolling is enabled
22113     *
22114     * @see #setNestedScrollingEnabled(boolean)
22115     */
22116    public boolean isNestedScrollingEnabled() {
22117        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
22118                PFLAG3_NESTED_SCROLLING_ENABLED;
22119    }
22120
22121    /**
22122     * Begin a nestable scroll operation along the given axes.
22123     *
22124     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
22125     *
22126     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
22127     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
22128     * In the case of touch scrolling the nested scroll will be terminated automatically in
22129     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
22130     * In the event of programmatic scrolling the caller must explicitly call
22131     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
22132     *
22133     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
22134     * If it returns false the caller may ignore the rest of this contract until the next scroll.
22135     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
22136     *
22137     * <p>At each incremental step of the scroll the caller should invoke
22138     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
22139     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
22140     * parent at least partially consumed the scroll and the caller should adjust the amount it
22141     * scrolls by.</p>
22142     *
22143     * <p>After applying the remainder of the scroll delta the caller should invoke
22144     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
22145     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
22146     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
22147     * </p>
22148     *
22149     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
22150     *             {@link #SCROLL_AXIS_VERTICAL}.
22151     * @return true if a cooperative parent was found and nested scrolling has been enabled for
22152     *         the current gesture.
22153     *
22154     * @see #stopNestedScroll()
22155     * @see #dispatchNestedPreScroll(int, int, int[], int[])
22156     * @see #dispatchNestedScroll(int, int, int, int, int[])
22157     */
22158    public boolean startNestedScroll(int axes) {
22159        if (hasNestedScrollingParent()) {
22160            // Already in progress
22161            return true;
22162        }
22163        if (isNestedScrollingEnabled()) {
22164            ViewParent p = getParent();
22165            View child = this;
22166            while (p != null) {
22167                try {
22168                    if (p.onStartNestedScroll(child, this, axes)) {
22169                        mNestedScrollingParent = p;
22170                        p.onNestedScrollAccepted(child, this, axes);
22171                        return true;
22172                    }
22173                } catch (AbstractMethodError e) {
22174                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
22175                            "method onStartNestedScroll", e);
22176                    // Allow the search upward to continue
22177                }
22178                if (p instanceof View) {
22179                    child = (View) p;
22180                }
22181                p = p.getParent();
22182            }
22183        }
22184        return false;
22185    }
22186
22187    /**
22188     * Stop a nested scroll in progress.
22189     *
22190     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
22191     *
22192     * @see #startNestedScroll(int)
22193     */
22194    public void stopNestedScroll() {
22195        if (mNestedScrollingParent != null) {
22196            mNestedScrollingParent.onStopNestedScroll(this);
22197            mNestedScrollingParent = null;
22198        }
22199    }
22200
22201    /**
22202     * Returns true if this view has a nested scrolling parent.
22203     *
22204     * <p>The presence of a nested scrolling parent indicates that this view has initiated
22205     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
22206     *
22207     * @return whether this view has a nested scrolling parent
22208     */
22209    public boolean hasNestedScrollingParent() {
22210        return mNestedScrollingParent != null;
22211    }
22212
22213    /**
22214     * Dispatch one step of a nested scroll in progress.
22215     *
22216     * <p>Implementations of views that support nested scrolling should call this to report
22217     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
22218     * is not currently in progress or nested scrolling is not
22219     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
22220     *
22221     * <p>Compatible View implementations should also call
22222     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
22223     * consuming a component of the scroll event themselves.</p>
22224     *
22225     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
22226     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
22227     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
22228     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
22229     * @param offsetInWindow Optional. If not null, on return this will contain the offset
22230     *                       in local view coordinates of this view from before this operation
22231     *                       to after it completes. View implementations may use this to adjust
22232     *                       expected input coordinate tracking.
22233     * @return true if the event was dispatched, false if it could not be dispatched.
22234     * @see #dispatchNestedPreScroll(int, int, int[], int[])
22235     */
22236    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
22237            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
22238        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22239            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
22240                int startX = 0;
22241                int startY = 0;
22242                if (offsetInWindow != null) {
22243                    getLocationInWindow(offsetInWindow);
22244                    startX = offsetInWindow[0];
22245                    startY = offsetInWindow[1];
22246                }
22247
22248                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
22249                        dxUnconsumed, dyUnconsumed);
22250
22251                if (offsetInWindow != null) {
22252                    getLocationInWindow(offsetInWindow);
22253                    offsetInWindow[0] -= startX;
22254                    offsetInWindow[1] -= startY;
22255                }
22256                return true;
22257            } else if (offsetInWindow != null) {
22258                // No motion, no dispatch. Keep offsetInWindow up to date.
22259                offsetInWindow[0] = 0;
22260                offsetInWindow[1] = 0;
22261            }
22262        }
22263        return false;
22264    }
22265
22266    /**
22267     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
22268     *
22269     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
22270     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
22271     * scrolling operation to consume some or all of the scroll operation before the child view
22272     * consumes it.</p>
22273     *
22274     * @param dx Horizontal scroll distance in pixels
22275     * @param dy Vertical scroll distance in pixels
22276     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
22277     *                 and consumed[1] the consumed dy.
22278     * @param offsetInWindow Optional. If not null, on return this will contain the offset
22279     *                       in local view coordinates of this view from before this operation
22280     *                       to after it completes. View implementations may use this to adjust
22281     *                       expected input coordinate tracking.
22282     * @return true if the parent consumed some or all of the scroll delta
22283     * @see #dispatchNestedScroll(int, int, int, int, int[])
22284     */
22285    public boolean dispatchNestedPreScroll(int dx, int dy,
22286            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
22287        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22288            if (dx != 0 || dy != 0) {
22289                int startX = 0;
22290                int startY = 0;
22291                if (offsetInWindow != null) {
22292                    getLocationInWindow(offsetInWindow);
22293                    startX = offsetInWindow[0];
22294                    startY = offsetInWindow[1];
22295                }
22296
22297                if (consumed == null) {
22298                    if (mTempNestedScrollConsumed == null) {
22299                        mTempNestedScrollConsumed = new int[2];
22300                    }
22301                    consumed = mTempNestedScrollConsumed;
22302                }
22303                consumed[0] = 0;
22304                consumed[1] = 0;
22305                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
22306
22307                if (offsetInWindow != null) {
22308                    getLocationInWindow(offsetInWindow);
22309                    offsetInWindow[0] -= startX;
22310                    offsetInWindow[1] -= startY;
22311                }
22312                return consumed[0] != 0 || consumed[1] != 0;
22313            } else if (offsetInWindow != null) {
22314                offsetInWindow[0] = 0;
22315                offsetInWindow[1] = 0;
22316            }
22317        }
22318        return false;
22319    }
22320
22321    /**
22322     * Dispatch a fling to a nested scrolling parent.
22323     *
22324     * <p>This method should be used to indicate that a nested scrolling child has detected
22325     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
22326     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
22327     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
22328     * along a scrollable axis.</p>
22329     *
22330     * <p>If a nested scrolling child view would normally fling but it is at the edge of
22331     * its own content, it can use this method to delegate the fling to its nested scrolling
22332     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
22333     *
22334     * @param velocityX Horizontal fling velocity in pixels per second
22335     * @param velocityY Vertical fling velocity in pixels per second
22336     * @param consumed true if the child consumed the fling, false otherwise
22337     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
22338     */
22339    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
22340        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22341            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
22342        }
22343        return false;
22344    }
22345
22346    /**
22347     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
22348     *
22349     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
22350     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
22351     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
22352     * before the child view consumes it. If this method returns <code>true</code>, a nested
22353     * parent view consumed the fling and this view should not scroll as a result.</p>
22354     *
22355     * <p>For a better user experience, only one view in a nested scrolling chain should consume
22356     * the fling at a time. If a parent view consumed the fling this method will return false.
22357     * Custom view implementations should account for this in two ways:</p>
22358     *
22359     * <ul>
22360     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
22361     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
22362     *     position regardless.</li>
22363     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
22364     *     even to settle back to a valid idle position.</li>
22365     * </ul>
22366     *
22367     * <p>Views should also not offer fling velocities to nested parent views along an axis
22368     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
22369     * should not offer a horizontal fling velocity to its parents since scrolling along that
22370     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
22371     *
22372     * @param velocityX Horizontal fling velocity in pixels per second
22373     * @param velocityY Vertical fling velocity in pixels per second
22374     * @return true if a nested scrolling parent consumed the fling
22375     */
22376    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
22377        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22378            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
22379        }
22380        return false;
22381    }
22382
22383    /**
22384     * Gets a scale factor that determines the distance the view should scroll
22385     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
22386     * @return The vertical scroll scale factor.
22387     * @hide
22388     */
22389    protected float getVerticalScrollFactor() {
22390        if (mVerticalScrollFactor == 0) {
22391            TypedValue outValue = new TypedValue();
22392            if (!mContext.getTheme().resolveAttribute(
22393                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
22394                throw new IllegalStateException(
22395                        "Expected theme to define listPreferredItemHeight.");
22396            }
22397            mVerticalScrollFactor = outValue.getDimension(
22398                    mContext.getResources().getDisplayMetrics());
22399        }
22400        return mVerticalScrollFactor;
22401    }
22402
22403    /**
22404     * Gets a scale factor that determines the distance the view should scroll
22405     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
22406     * @return The horizontal scroll scale factor.
22407     * @hide
22408     */
22409    protected float getHorizontalScrollFactor() {
22410        // TODO: Should use something else.
22411        return getVerticalScrollFactor();
22412    }
22413
22414    /**
22415     * Return the value specifying the text direction or policy that was set with
22416     * {@link #setTextDirection(int)}.
22417     *
22418     * @return the defined text direction. It can be one of:
22419     *
22420     * {@link #TEXT_DIRECTION_INHERIT},
22421     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22422     * {@link #TEXT_DIRECTION_ANY_RTL},
22423     * {@link #TEXT_DIRECTION_LTR},
22424     * {@link #TEXT_DIRECTION_RTL},
22425     * {@link #TEXT_DIRECTION_LOCALE},
22426     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22427     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22428     *
22429     * @attr ref android.R.styleable#View_textDirection
22430     *
22431     * @hide
22432     */
22433    @ViewDebug.ExportedProperty(category = "text", mapping = {
22434            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22435            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22436            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22437            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22438            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22439            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22440            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22441            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22442    })
22443    public int getRawTextDirection() {
22444        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
22445    }
22446
22447    /**
22448     * Set the text direction.
22449     *
22450     * @param textDirection the direction to set. Should be one of:
22451     *
22452     * {@link #TEXT_DIRECTION_INHERIT},
22453     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22454     * {@link #TEXT_DIRECTION_ANY_RTL},
22455     * {@link #TEXT_DIRECTION_LTR},
22456     * {@link #TEXT_DIRECTION_RTL},
22457     * {@link #TEXT_DIRECTION_LOCALE}
22458     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22459     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
22460     *
22461     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
22462     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
22463     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
22464     *
22465     * @attr ref android.R.styleable#View_textDirection
22466     */
22467    public void setTextDirection(int textDirection) {
22468        if (getRawTextDirection() != textDirection) {
22469            // Reset the current text direction and the resolved one
22470            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
22471            resetResolvedTextDirection();
22472            // Set the new text direction
22473            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
22474            // Do resolution
22475            resolveTextDirection();
22476            // Notify change
22477            onRtlPropertiesChanged(getLayoutDirection());
22478            // Refresh
22479            requestLayout();
22480            invalidate(true);
22481        }
22482    }
22483
22484    /**
22485     * Return the resolved text direction.
22486     *
22487     * @return the resolved text direction. Returns one of:
22488     *
22489     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22490     * {@link #TEXT_DIRECTION_ANY_RTL},
22491     * {@link #TEXT_DIRECTION_LTR},
22492     * {@link #TEXT_DIRECTION_RTL},
22493     * {@link #TEXT_DIRECTION_LOCALE},
22494     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22495     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22496     *
22497     * @attr ref android.R.styleable#View_textDirection
22498     */
22499    @ViewDebug.ExportedProperty(category = "text", mapping = {
22500            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22501            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22502            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22503            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22504            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22505            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22506            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22507            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22508    })
22509    public int getTextDirection() {
22510        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
22511    }
22512
22513    /**
22514     * Resolve the text direction.
22515     *
22516     * @return true if resolution has been done, false otherwise.
22517     *
22518     * @hide
22519     */
22520    public boolean resolveTextDirection() {
22521        // Reset any previous text direction resolution
22522        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22523
22524        if (hasRtlSupport()) {
22525            // Set resolved text direction flag depending on text direction flag
22526            final int textDirection = getRawTextDirection();
22527            switch(textDirection) {
22528                case TEXT_DIRECTION_INHERIT:
22529                    if (!canResolveTextDirection()) {
22530                        // We cannot do the resolution if there is no parent, so use the default one
22531                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22532                        // Resolution will need to happen again later
22533                        return false;
22534                    }
22535
22536                    // Parent has not yet resolved, so we still return the default
22537                    try {
22538                        if (!mParent.isTextDirectionResolved()) {
22539                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22540                            // Resolution will need to happen again later
22541                            return false;
22542                        }
22543                    } catch (AbstractMethodError e) {
22544                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22545                                " does not fully implement ViewParent", e);
22546                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
22547                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22548                        return true;
22549                    }
22550
22551                    // Set current resolved direction to the same value as the parent's one
22552                    int parentResolvedDirection;
22553                    try {
22554                        parentResolvedDirection = mParent.getTextDirection();
22555                    } catch (AbstractMethodError e) {
22556                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22557                                " does not fully implement ViewParent", e);
22558                        parentResolvedDirection = TEXT_DIRECTION_LTR;
22559                    }
22560                    switch (parentResolvedDirection) {
22561                        case TEXT_DIRECTION_FIRST_STRONG:
22562                        case TEXT_DIRECTION_ANY_RTL:
22563                        case TEXT_DIRECTION_LTR:
22564                        case TEXT_DIRECTION_RTL:
22565                        case TEXT_DIRECTION_LOCALE:
22566                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
22567                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
22568                            mPrivateFlags2 |=
22569                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22570                            break;
22571                        default:
22572                            // Default resolved direction is "first strong" heuristic
22573                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22574                    }
22575                    break;
22576                case TEXT_DIRECTION_FIRST_STRONG:
22577                case TEXT_DIRECTION_ANY_RTL:
22578                case TEXT_DIRECTION_LTR:
22579                case TEXT_DIRECTION_RTL:
22580                case TEXT_DIRECTION_LOCALE:
22581                case TEXT_DIRECTION_FIRST_STRONG_LTR:
22582                case TEXT_DIRECTION_FIRST_STRONG_RTL:
22583                    // Resolved direction is the same as text direction
22584                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22585                    break;
22586                default:
22587                    // Default resolved direction is "first strong" heuristic
22588                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22589            }
22590        } else {
22591            // Default resolved direction is "first strong" heuristic
22592            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22593        }
22594
22595        // Set to resolved
22596        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
22597        return true;
22598    }
22599
22600    /**
22601     * Check if text direction resolution can be done.
22602     *
22603     * @return true if text direction resolution can be done otherwise return false.
22604     */
22605    public boolean canResolveTextDirection() {
22606        switch (getRawTextDirection()) {
22607            case TEXT_DIRECTION_INHERIT:
22608                if (mParent != null) {
22609                    try {
22610                        return mParent.canResolveTextDirection();
22611                    } catch (AbstractMethodError e) {
22612                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22613                                " does not fully implement ViewParent", e);
22614                    }
22615                }
22616                return false;
22617
22618            default:
22619                return true;
22620        }
22621    }
22622
22623    /**
22624     * Reset resolved text direction. Text direction will be resolved during a call to
22625     * {@link #onMeasure(int, int)}.
22626     *
22627     * @hide
22628     */
22629    public void resetResolvedTextDirection() {
22630        // Reset any previous text direction resolution
22631        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22632        // Set to default value
22633        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22634    }
22635
22636    /**
22637     * @return true if text direction is inherited.
22638     *
22639     * @hide
22640     */
22641    public boolean isTextDirectionInherited() {
22642        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
22643    }
22644
22645    /**
22646     * @return true if text direction is resolved.
22647     */
22648    public boolean isTextDirectionResolved() {
22649        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
22650    }
22651
22652    /**
22653     * Return the value specifying the text alignment or policy that was set with
22654     * {@link #setTextAlignment(int)}.
22655     *
22656     * @return the defined text alignment. It can be one of:
22657     *
22658     * {@link #TEXT_ALIGNMENT_INHERIT},
22659     * {@link #TEXT_ALIGNMENT_GRAVITY},
22660     * {@link #TEXT_ALIGNMENT_CENTER},
22661     * {@link #TEXT_ALIGNMENT_TEXT_START},
22662     * {@link #TEXT_ALIGNMENT_TEXT_END},
22663     * {@link #TEXT_ALIGNMENT_VIEW_START},
22664     * {@link #TEXT_ALIGNMENT_VIEW_END}
22665     *
22666     * @attr ref android.R.styleable#View_textAlignment
22667     *
22668     * @hide
22669     */
22670    @ViewDebug.ExportedProperty(category = "text", mapping = {
22671            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22672            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22673            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22674            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22675            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22676            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22677            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22678    })
22679    @TextAlignment
22680    public int getRawTextAlignment() {
22681        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
22682    }
22683
22684    /**
22685     * Set the text alignment.
22686     *
22687     * @param textAlignment The text alignment to set. Should be one of
22688     *
22689     * {@link #TEXT_ALIGNMENT_INHERIT},
22690     * {@link #TEXT_ALIGNMENT_GRAVITY},
22691     * {@link #TEXT_ALIGNMENT_CENTER},
22692     * {@link #TEXT_ALIGNMENT_TEXT_START},
22693     * {@link #TEXT_ALIGNMENT_TEXT_END},
22694     * {@link #TEXT_ALIGNMENT_VIEW_START},
22695     * {@link #TEXT_ALIGNMENT_VIEW_END}
22696     *
22697     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
22698     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
22699     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
22700     *
22701     * @attr ref android.R.styleable#View_textAlignment
22702     */
22703    public void setTextAlignment(@TextAlignment int textAlignment) {
22704        if (textAlignment != getRawTextAlignment()) {
22705            // Reset the current and resolved text alignment
22706            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
22707            resetResolvedTextAlignment();
22708            // Set the new text alignment
22709            mPrivateFlags2 |=
22710                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
22711            // Do resolution
22712            resolveTextAlignment();
22713            // Notify change
22714            onRtlPropertiesChanged(getLayoutDirection());
22715            // Refresh
22716            requestLayout();
22717            invalidate(true);
22718        }
22719    }
22720
22721    /**
22722     * Return the resolved text alignment.
22723     *
22724     * @return the resolved text alignment. Returns one of:
22725     *
22726     * {@link #TEXT_ALIGNMENT_GRAVITY},
22727     * {@link #TEXT_ALIGNMENT_CENTER},
22728     * {@link #TEXT_ALIGNMENT_TEXT_START},
22729     * {@link #TEXT_ALIGNMENT_TEXT_END},
22730     * {@link #TEXT_ALIGNMENT_VIEW_START},
22731     * {@link #TEXT_ALIGNMENT_VIEW_END}
22732     *
22733     * @attr ref android.R.styleable#View_textAlignment
22734     */
22735    @ViewDebug.ExportedProperty(category = "text", mapping = {
22736            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22737            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22738            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22739            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22740            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22741            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22742            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22743    })
22744    @TextAlignment
22745    public int getTextAlignment() {
22746        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
22747                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
22748    }
22749
22750    /**
22751     * Resolve the text alignment.
22752     *
22753     * @return true if resolution has been done, false otherwise.
22754     *
22755     * @hide
22756     */
22757    public boolean resolveTextAlignment() {
22758        // Reset any previous text alignment resolution
22759        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22760
22761        if (hasRtlSupport()) {
22762            // Set resolved text alignment flag depending on text alignment flag
22763            final int textAlignment = getRawTextAlignment();
22764            switch (textAlignment) {
22765                case TEXT_ALIGNMENT_INHERIT:
22766                    // Check if we can resolve the text alignment
22767                    if (!canResolveTextAlignment()) {
22768                        // We cannot do the resolution if there is no parent so use the default
22769                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22770                        // Resolution will need to happen again later
22771                        return false;
22772                    }
22773
22774                    // Parent has not yet resolved, so we still return the default
22775                    try {
22776                        if (!mParent.isTextAlignmentResolved()) {
22777                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22778                            // Resolution will need to happen again later
22779                            return false;
22780                        }
22781                    } catch (AbstractMethodError e) {
22782                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22783                                " does not fully implement ViewParent", e);
22784                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
22785                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22786                        return true;
22787                    }
22788
22789                    int parentResolvedTextAlignment;
22790                    try {
22791                        parentResolvedTextAlignment = mParent.getTextAlignment();
22792                    } catch (AbstractMethodError e) {
22793                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22794                                " does not fully implement ViewParent", e);
22795                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
22796                    }
22797                    switch (parentResolvedTextAlignment) {
22798                        case TEXT_ALIGNMENT_GRAVITY:
22799                        case TEXT_ALIGNMENT_TEXT_START:
22800                        case TEXT_ALIGNMENT_TEXT_END:
22801                        case TEXT_ALIGNMENT_CENTER:
22802                        case TEXT_ALIGNMENT_VIEW_START:
22803                        case TEXT_ALIGNMENT_VIEW_END:
22804                            // Resolved text alignment is the same as the parent resolved
22805                            // text alignment
22806                            mPrivateFlags2 |=
22807                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22808                            break;
22809                        default:
22810                            // Use default resolved text alignment
22811                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22812                    }
22813                    break;
22814                case TEXT_ALIGNMENT_GRAVITY:
22815                case TEXT_ALIGNMENT_TEXT_START:
22816                case TEXT_ALIGNMENT_TEXT_END:
22817                case TEXT_ALIGNMENT_CENTER:
22818                case TEXT_ALIGNMENT_VIEW_START:
22819                case TEXT_ALIGNMENT_VIEW_END:
22820                    // Resolved text alignment is the same as text alignment
22821                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22822                    break;
22823                default:
22824                    // Use default resolved text alignment
22825                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22826            }
22827        } else {
22828            // Use default resolved text alignment
22829            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22830        }
22831
22832        // Set the resolved
22833        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22834        return true;
22835    }
22836
22837    /**
22838     * Check if text alignment resolution can be done.
22839     *
22840     * @return true if text alignment resolution can be done otherwise return false.
22841     */
22842    public boolean canResolveTextAlignment() {
22843        switch (getRawTextAlignment()) {
22844            case TEXT_DIRECTION_INHERIT:
22845                if (mParent != null) {
22846                    try {
22847                        return mParent.canResolveTextAlignment();
22848                    } catch (AbstractMethodError e) {
22849                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22850                                " does not fully implement ViewParent", e);
22851                    }
22852                }
22853                return false;
22854
22855            default:
22856                return true;
22857        }
22858    }
22859
22860    /**
22861     * Reset resolved text alignment. Text alignment will be resolved during a call to
22862     * {@link #onMeasure(int, int)}.
22863     *
22864     * @hide
22865     */
22866    public void resetResolvedTextAlignment() {
22867        // Reset any previous text alignment resolution
22868        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22869        // Set to default
22870        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22871    }
22872
22873    /**
22874     * @return true if text alignment is inherited.
22875     *
22876     * @hide
22877     */
22878    public boolean isTextAlignmentInherited() {
22879        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
22880    }
22881
22882    /**
22883     * @return true if text alignment is resolved.
22884     */
22885    public boolean isTextAlignmentResolved() {
22886        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22887    }
22888
22889    /**
22890     * Generate a value suitable for use in {@link #setId(int)}.
22891     * This value will not collide with ID values generated at build time by aapt for R.id.
22892     *
22893     * @return a generated ID value
22894     */
22895    public static int generateViewId() {
22896        for (;;) {
22897            final int result = sNextGeneratedId.get();
22898            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
22899            int newValue = result + 1;
22900            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
22901            if (sNextGeneratedId.compareAndSet(result, newValue)) {
22902                return result;
22903            }
22904        }
22905    }
22906
22907    private static boolean isViewIdGenerated(int id) {
22908        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
22909    }
22910
22911    /**
22912     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
22913     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
22914     *                           a normal View or a ViewGroup with
22915     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
22916     * @hide
22917     */
22918    public void captureTransitioningViews(List<View> transitioningViews) {
22919        if (getVisibility() == View.VISIBLE) {
22920            transitioningViews.add(this);
22921        }
22922    }
22923
22924    /**
22925     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
22926     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
22927     * @hide
22928     */
22929    public void findNamedViews(Map<String, View> namedElements) {
22930        if (getVisibility() == VISIBLE || mGhostView != null) {
22931            String transitionName = getTransitionName();
22932            if (transitionName != null) {
22933                namedElements.put(transitionName, this);
22934            }
22935        }
22936    }
22937
22938    /**
22939     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
22940     * The default implementation does not care the location or event types, but some subclasses
22941     * may use it (such as WebViews).
22942     * @param event The MotionEvent from a mouse
22943     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
22944     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
22945     * @see PointerIcon
22946     */
22947    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
22948        final float x = event.getX(pointerIndex);
22949        final float y = event.getY(pointerIndex);
22950        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
22951            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
22952        }
22953        return mPointerIcon;
22954    }
22955
22956    /**
22957     * Set the pointer icon for the current view.
22958     * Passing {@code null} will restore the pointer icon to its default value.
22959     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
22960     */
22961    public void setPointerIcon(PointerIcon pointerIcon) {
22962        mPointerIcon = pointerIcon;
22963        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
22964            return;
22965        }
22966        try {
22967            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
22968        } catch (RemoteException e) {
22969        }
22970    }
22971
22972    /**
22973     * Gets the pointer icon for the current view.
22974     */
22975    public PointerIcon getPointerIcon() {
22976        return mPointerIcon;
22977    }
22978
22979    /**
22980     * Checks pointer capture status.
22981     *
22982     * @return true if the view has pointer capture.
22983     * @see #requestPointerCapture()
22984     * @see #hasPointerCapture()
22985     */
22986    public boolean hasPointerCapture() {
22987        final ViewRootImpl viewRootImpl = getViewRootImpl();
22988        if (viewRootImpl == null) {
22989            return false;
22990        }
22991        return viewRootImpl.hasPointerCapture();
22992    }
22993
22994    /**
22995     * Requests pointer capture mode.
22996     * <p>
22997     * When the window has pointer capture, the mouse pointer icon will disappear and will not
22998     * change its position. Further mouse will be dispatched with the source
22999     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
23000     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
23001     * (touchscreens, or stylus) will not be affected.
23002     * <p>
23003     * If the window already has pointer capture, this call does nothing.
23004     * <p>
23005     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
23006     * automatically when the window loses focus.
23007     *
23008     * @see #releasePointerCapture()
23009     * @see #hasPointerCapture()
23010     */
23011    public void requestPointerCapture() {
23012        final ViewRootImpl viewRootImpl = getViewRootImpl();
23013        if (viewRootImpl != null) {
23014            viewRootImpl.requestPointerCapture(true);
23015        }
23016    }
23017
23018
23019    /**
23020     * Releases the pointer capture.
23021     * <p>
23022     * If the window does not have pointer capture, this call will do nothing.
23023     * @see #requestPointerCapture()
23024     * @see #hasPointerCapture()
23025     */
23026    public void releasePointerCapture() {
23027        final ViewRootImpl viewRootImpl = getViewRootImpl();
23028        if (viewRootImpl != null) {
23029            viewRootImpl.requestPointerCapture(false);
23030        }
23031    }
23032
23033    /**
23034     * Called when the window has just acquired or lost pointer capture.
23035     *
23036     * @param hasCapture True if the view now has pointerCapture, false otherwise.
23037     */
23038    @CallSuper
23039    public void onPointerCaptureChange(boolean hasCapture) {
23040    }
23041
23042    /**
23043     * @see #onPointerCaptureChange
23044     */
23045    public void dispatchPointerCaptureChanged(boolean hasCapture) {
23046        onPointerCaptureChange(hasCapture);
23047    }
23048
23049    /**
23050     * Implement this method to handle captured pointer events
23051     *
23052     * @param event The captured pointer event.
23053     * @return True if the event was handled, false otherwise.
23054     * @see #requestPointerCapture()
23055     */
23056    public boolean onCapturedPointerEvent(MotionEvent event) {
23057        return false;
23058    }
23059
23060    /**
23061     * Interface definition for a callback to be invoked when a captured pointer event
23062     * is being dispatched this view. The callback will be invoked before the event is
23063     * given to the view.
23064     */
23065    public interface OnCapturedPointerListener {
23066        /**
23067         * Called when a captured pointer event is dispatched to a view.
23068         * @param view The view this event has been dispatched to.
23069         * @param event The captured event.
23070         * @return True if the listener has consumed the event, false otherwise.
23071         */
23072        boolean onCapturedPointer(View view, MotionEvent event);
23073    }
23074
23075    /**
23076     * Set a listener to receive callbacks when the pointer capture state of a view changes.
23077     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
23078     */
23079    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
23080        getListenerInfo().mOnCapturedPointerListener = l;
23081    }
23082
23083    // Properties
23084    //
23085    /**
23086     * A Property wrapper around the <code>alpha</code> functionality handled by the
23087     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
23088     */
23089    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
23090        @Override
23091        public void setValue(View object, float value) {
23092            object.setAlpha(value);
23093        }
23094
23095        @Override
23096        public Float get(View object) {
23097            return object.getAlpha();
23098        }
23099    };
23100
23101    /**
23102     * A Property wrapper around the <code>translationX</code> functionality handled by the
23103     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
23104     */
23105    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
23106        @Override
23107        public void setValue(View object, float value) {
23108            object.setTranslationX(value);
23109        }
23110
23111                @Override
23112        public Float get(View object) {
23113            return object.getTranslationX();
23114        }
23115    };
23116
23117    /**
23118     * A Property wrapper around the <code>translationY</code> functionality handled by the
23119     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
23120     */
23121    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
23122        @Override
23123        public void setValue(View object, float value) {
23124            object.setTranslationY(value);
23125        }
23126
23127        @Override
23128        public Float get(View object) {
23129            return object.getTranslationY();
23130        }
23131    };
23132
23133    /**
23134     * A Property wrapper around the <code>translationZ</code> functionality handled by the
23135     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
23136     */
23137    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
23138        @Override
23139        public void setValue(View object, float value) {
23140            object.setTranslationZ(value);
23141        }
23142
23143        @Override
23144        public Float get(View object) {
23145            return object.getTranslationZ();
23146        }
23147    };
23148
23149    /**
23150     * A Property wrapper around the <code>x</code> functionality handled by the
23151     * {@link View#setX(float)} and {@link View#getX()} methods.
23152     */
23153    public static final Property<View, Float> X = new FloatProperty<View>("x") {
23154        @Override
23155        public void setValue(View object, float value) {
23156            object.setX(value);
23157        }
23158
23159        @Override
23160        public Float get(View object) {
23161            return object.getX();
23162        }
23163    };
23164
23165    /**
23166     * A Property wrapper around the <code>y</code> functionality handled by the
23167     * {@link View#setY(float)} and {@link View#getY()} methods.
23168     */
23169    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
23170        @Override
23171        public void setValue(View object, float value) {
23172            object.setY(value);
23173        }
23174
23175        @Override
23176        public Float get(View object) {
23177            return object.getY();
23178        }
23179    };
23180
23181    /**
23182     * A Property wrapper around the <code>z</code> functionality handled by the
23183     * {@link View#setZ(float)} and {@link View#getZ()} methods.
23184     */
23185    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
23186        @Override
23187        public void setValue(View object, float value) {
23188            object.setZ(value);
23189        }
23190
23191        @Override
23192        public Float get(View object) {
23193            return object.getZ();
23194        }
23195    };
23196
23197    /**
23198     * A Property wrapper around the <code>rotation</code> functionality handled by the
23199     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
23200     */
23201    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
23202        @Override
23203        public void setValue(View object, float value) {
23204            object.setRotation(value);
23205        }
23206
23207        @Override
23208        public Float get(View object) {
23209            return object.getRotation();
23210        }
23211    };
23212
23213    /**
23214     * A Property wrapper around the <code>rotationX</code> functionality handled by the
23215     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
23216     */
23217    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
23218        @Override
23219        public void setValue(View object, float value) {
23220            object.setRotationX(value);
23221        }
23222
23223        @Override
23224        public Float get(View object) {
23225            return object.getRotationX();
23226        }
23227    };
23228
23229    /**
23230     * A Property wrapper around the <code>rotationY</code> functionality handled by the
23231     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
23232     */
23233    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
23234        @Override
23235        public void setValue(View object, float value) {
23236            object.setRotationY(value);
23237        }
23238
23239        @Override
23240        public Float get(View object) {
23241            return object.getRotationY();
23242        }
23243    };
23244
23245    /**
23246     * A Property wrapper around the <code>scaleX</code> functionality handled by the
23247     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
23248     */
23249    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
23250        @Override
23251        public void setValue(View object, float value) {
23252            object.setScaleX(value);
23253        }
23254
23255        @Override
23256        public Float get(View object) {
23257            return object.getScaleX();
23258        }
23259    };
23260
23261    /**
23262     * A Property wrapper around the <code>scaleY</code> functionality handled by the
23263     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
23264     */
23265    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
23266        @Override
23267        public void setValue(View object, float value) {
23268            object.setScaleY(value);
23269        }
23270
23271        @Override
23272        public Float get(View object) {
23273            return object.getScaleY();
23274        }
23275    };
23276
23277    /**
23278     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
23279     * Each MeasureSpec represents a requirement for either the width or the height.
23280     * A MeasureSpec is comprised of a size and a mode. There are three possible
23281     * modes:
23282     * <dl>
23283     * <dt>UNSPECIFIED</dt>
23284     * <dd>
23285     * The parent has not imposed any constraint on the child. It can be whatever size
23286     * it wants.
23287     * </dd>
23288     *
23289     * <dt>EXACTLY</dt>
23290     * <dd>
23291     * The parent has determined an exact size for the child. The child is going to be
23292     * given those bounds regardless of how big it wants to be.
23293     * </dd>
23294     *
23295     * <dt>AT_MOST</dt>
23296     * <dd>
23297     * The child can be as large as it wants up to the specified size.
23298     * </dd>
23299     * </dl>
23300     *
23301     * MeasureSpecs are implemented as ints to reduce object allocation. This class
23302     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
23303     */
23304    public static class MeasureSpec {
23305        private static final int MODE_SHIFT = 30;
23306        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
23307
23308        /** @hide */
23309        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
23310        @Retention(RetentionPolicy.SOURCE)
23311        public @interface MeasureSpecMode {}
23312
23313        /**
23314         * Measure specification mode: The parent has not imposed any constraint
23315         * on the child. It can be whatever size it wants.
23316         */
23317        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
23318
23319        /**
23320         * Measure specification mode: The parent has determined an exact size
23321         * for the child. The child is going to be given those bounds regardless
23322         * of how big it wants to be.
23323         */
23324        public static final int EXACTLY     = 1 << MODE_SHIFT;
23325
23326        /**
23327         * Measure specification mode: The child can be as large as it wants up
23328         * to the specified size.
23329         */
23330        public static final int AT_MOST     = 2 << MODE_SHIFT;
23331
23332        /**
23333         * Creates a measure specification based on the supplied size and mode.
23334         *
23335         * The mode must always be one of the following:
23336         * <ul>
23337         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
23338         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
23339         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
23340         * </ul>
23341         *
23342         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
23343         * implementation was such that the order of arguments did not matter
23344         * and overflow in either value could impact the resulting MeasureSpec.
23345         * {@link android.widget.RelativeLayout} was affected by this bug.
23346         * Apps targeting API levels greater than 17 will get the fixed, more strict
23347         * behavior.</p>
23348         *
23349         * @param size the size of the measure specification
23350         * @param mode the mode of the measure specification
23351         * @return the measure specification based on size and mode
23352         */
23353        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
23354                                          @MeasureSpecMode int mode) {
23355            if (sUseBrokenMakeMeasureSpec) {
23356                return size + mode;
23357            } else {
23358                return (size & ~MODE_MASK) | (mode & MODE_MASK);
23359            }
23360        }
23361
23362        /**
23363         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
23364         * will automatically get a size of 0. Older apps expect this.
23365         *
23366         * @hide internal use only for compatibility with system widgets and older apps
23367         */
23368        public static int makeSafeMeasureSpec(int size, int mode) {
23369            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
23370                return 0;
23371            }
23372            return makeMeasureSpec(size, mode);
23373        }
23374
23375        /**
23376         * Extracts the mode from the supplied measure specification.
23377         *
23378         * @param measureSpec the measure specification to extract the mode from
23379         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
23380         *         {@link android.view.View.MeasureSpec#AT_MOST} or
23381         *         {@link android.view.View.MeasureSpec#EXACTLY}
23382         */
23383        @MeasureSpecMode
23384        public static int getMode(int measureSpec) {
23385            //noinspection ResourceType
23386            return (measureSpec & MODE_MASK);
23387        }
23388
23389        /**
23390         * Extracts the size from the supplied measure specification.
23391         *
23392         * @param measureSpec the measure specification to extract the size from
23393         * @return the size in pixels defined in the supplied measure specification
23394         */
23395        public static int getSize(int measureSpec) {
23396            return (measureSpec & ~MODE_MASK);
23397        }
23398
23399        static int adjust(int measureSpec, int delta) {
23400            final int mode = getMode(measureSpec);
23401            int size = getSize(measureSpec);
23402            if (mode == UNSPECIFIED) {
23403                // No need to adjust size for UNSPECIFIED mode.
23404                return makeMeasureSpec(size, UNSPECIFIED);
23405            }
23406            size += delta;
23407            if (size < 0) {
23408                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
23409                        ") spec: " + toString(measureSpec) + " delta: " + delta);
23410                size = 0;
23411            }
23412            return makeMeasureSpec(size, mode);
23413        }
23414
23415        /**
23416         * Returns a String representation of the specified measure
23417         * specification.
23418         *
23419         * @param measureSpec the measure specification to convert to a String
23420         * @return a String with the following format: "MeasureSpec: MODE SIZE"
23421         */
23422        public static String toString(int measureSpec) {
23423            int mode = getMode(measureSpec);
23424            int size = getSize(measureSpec);
23425
23426            StringBuilder sb = new StringBuilder("MeasureSpec: ");
23427
23428            if (mode == UNSPECIFIED)
23429                sb.append("UNSPECIFIED ");
23430            else if (mode == EXACTLY)
23431                sb.append("EXACTLY ");
23432            else if (mode == AT_MOST)
23433                sb.append("AT_MOST ");
23434            else
23435                sb.append(mode).append(" ");
23436
23437            sb.append(size);
23438            return sb.toString();
23439        }
23440    }
23441
23442    private final class CheckForLongPress implements Runnable {
23443        private int mOriginalWindowAttachCount;
23444        private float mX;
23445        private float mY;
23446        private boolean mOriginalPressedState;
23447
23448        @Override
23449        public void run() {
23450            if ((mOriginalPressedState == isPressed()) && (mParent != null)
23451                    && mOriginalWindowAttachCount == mWindowAttachCount) {
23452                if (performLongClick(mX, mY)) {
23453                    mHasPerformedLongPress = true;
23454                }
23455            }
23456        }
23457
23458        public void setAnchor(float x, float y) {
23459            mX = x;
23460            mY = y;
23461        }
23462
23463        public void rememberWindowAttachCount() {
23464            mOriginalWindowAttachCount = mWindowAttachCount;
23465        }
23466
23467        public void rememberPressedState() {
23468            mOriginalPressedState = isPressed();
23469        }
23470    }
23471
23472    private final class CheckForTap implements Runnable {
23473        public float x;
23474        public float y;
23475
23476        @Override
23477        public void run() {
23478            mPrivateFlags &= ~PFLAG_PREPRESSED;
23479            setPressed(true, x, y);
23480            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
23481        }
23482    }
23483
23484    private final class PerformClick implements Runnable {
23485        @Override
23486        public void run() {
23487            performClick();
23488        }
23489    }
23490
23491    /**
23492     * This method returns a ViewPropertyAnimator object, which can be used to animate
23493     * specific properties on this View.
23494     *
23495     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
23496     */
23497    public ViewPropertyAnimator animate() {
23498        if (mAnimator == null) {
23499            mAnimator = new ViewPropertyAnimator(this);
23500        }
23501        return mAnimator;
23502    }
23503
23504    /**
23505     * Sets the name of the View to be used to identify Views in Transitions.
23506     * Names should be unique in the View hierarchy.
23507     *
23508     * @param transitionName The name of the View to uniquely identify it for Transitions.
23509     */
23510    public final void setTransitionName(String transitionName) {
23511        mTransitionName = transitionName;
23512    }
23513
23514    /**
23515     * Returns the name of the View to be used to identify Views in Transitions.
23516     * Names should be unique in the View hierarchy.
23517     *
23518     * <p>This returns null if the View has not been given a name.</p>
23519     *
23520     * @return The name used of the View to be used to identify Views in Transitions or null
23521     * if no name has been given.
23522     */
23523    @ViewDebug.ExportedProperty
23524    public String getTransitionName() {
23525        return mTransitionName;
23526    }
23527
23528    /**
23529     * @hide
23530     */
23531    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
23532        // Do nothing.
23533    }
23534
23535    /**
23536     * Interface definition for a callback to be invoked when a hardware key event is
23537     * dispatched to this view. The callback will be invoked before the key event is
23538     * given to the view. This is only useful for hardware keyboards; a software input
23539     * method has no obligation to trigger this listener.
23540     */
23541    public interface OnKeyListener {
23542        /**
23543         * Called when a hardware key is dispatched to a view. This allows listeners to
23544         * get a chance to respond before the target view.
23545         * <p>Key presses in software keyboards will generally NOT trigger this method,
23546         * although some may elect to do so in some situations. Do not assume a
23547         * software input method has to be key-based; even if it is, it may use key presses
23548         * in a different way than you expect, so there is no way to reliably catch soft
23549         * input key presses.
23550         *
23551         * @param v The view the key has been dispatched to.
23552         * @param keyCode The code for the physical key that was pressed
23553         * @param event The KeyEvent object containing full information about
23554         *        the event.
23555         * @return True if the listener has consumed the event, false otherwise.
23556         */
23557        boolean onKey(View v, int keyCode, KeyEvent event);
23558    }
23559
23560    /**
23561     * Interface definition for a callback to be invoked when a touch event is
23562     * dispatched to this view. The callback will be invoked before the touch
23563     * event is given to the view.
23564     */
23565    public interface OnTouchListener {
23566        /**
23567         * Called when a touch event is dispatched to a view. This allows listeners to
23568         * get a chance to respond before the target view.
23569         *
23570         * @param v The view the touch event has been dispatched to.
23571         * @param event The MotionEvent object containing full information about
23572         *        the event.
23573         * @return True if the listener has consumed the event, false otherwise.
23574         */
23575        boolean onTouch(View v, MotionEvent event);
23576    }
23577
23578    /**
23579     * Interface definition for a callback to be invoked when a hover event is
23580     * dispatched to this view. The callback will be invoked before the hover
23581     * event is given to the view.
23582     */
23583    public interface OnHoverListener {
23584        /**
23585         * Called when a hover event is dispatched to a view. This allows listeners to
23586         * get a chance to respond before the target view.
23587         *
23588         * @param v The view the hover event has been dispatched to.
23589         * @param event The MotionEvent object containing full information about
23590         *        the event.
23591         * @return True if the listener has consumed the event, false otherwise.
23592         */
23593        boolean onHover(View v, MotionEvent event);
23594    }
23595
23596    /**
23597     * Interface definition for a callback to be invoked when a generic motion event is
23598     * dispatched to this view. The callback will be invoked before the generic motion
23599     * event is given to the view.
23600     */
23601    public interface OnGenericMotionListener {
23602        /**
23603         * Called when a generic motion event is dispatched to a view. This allows listeners to
23604         * get a chance to respond before the target view.
23605         *
23606         * @param v The view the generic motion event has been dispatched to.
23607         * @param event The MotionEvent object containing full information about
23608         *        the event.
23609         * @return True if the listener has consumed the event, false otherwise.
23610         */
23611        boolean onGenericMotion(View v, MotionEvent event);
23612    }
23613
23614    /**
23615     * Interface definition for a callback to be invoked when a view has been clicked and held.
23616     */
23617    public interface OnLongClickListener {
23618        /**
23619         * Called when a view has been clicked and held.
23620         *
23621         * @param v The view that was clicked and held.
23622         *
23623         * @return true if the callback consumed the long click, false otherwise.
23624         */
23625        boolean onLongClick(View v);
23626    }
23627
23628    /**
23629     * Interface definition for a callback to be invoked when a drag is being dispatched
23630     * to this view.  The callback will be invoked before the hosting view's own
23631     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
23632     * onDrag(event) behavior, it should return 'false' from this callback.
23633     *
23634     * <div class="special reference">
23635     * <h3>Developer Guides</h3>
23636     * <p>For a guide to implementing drag and drop features, read the
23637     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23638     * </div>
23639     */
23640    public interface OnDragListener {
23641        /**
23642         * Called when a drag event is dispatched to a view. This allows listeners
23643         * to get a chance to override base View behavior.
23644         *
23645         * @param v The View that received the drag event.
23646         * @param event The {@link android.view.DragEvent} object for the drag event.
23647         * @return {@code true} if the drag event was handled successfully, or {@code false}
23648         * if the drag event was not handled. Note that {@code false} will trigger the View
23649         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
23650         */
23651        boolean onDrag(View v, DragEvent event);
23652    }
23653
23654    /**
23655     * Interface definition for a callback to be invoked when the focus state of
23656     * a view changed.
23657     */
23658    public interface OnFocusChangeListener {
23659        /**
23660         * Called when the focus state of a view has changed.
23661         *
23662         * @param v The view whose state has changed.
23663         * @param hasFocus The new focus state of v.
23664         */
23665        void onFocusChange(View v, boolean hasFocus);
23666    }
23667
23668    /**
23669     * Interface definition for a callback to be invoked when a view is clicked.
23670     */
23671    public interface OnClickListener {
23672        /**
23673         * Called when a view has been clicked.
23674         *
23675         * @param v The view that was clicked.
23676         */
23677        void onClick(View v);
23678    }
23679
23680    /**
23681     * Interface definition for a callback to be invoked when a view is context clicked.
23682     */
23683    public interface OnContextClickListener {
23684        /**
23685         * Called when a view is context clicked.
23686         *
23687         * @param v The view that has been context clicked.
23688         * @return true if the callback consumed the context click, false otherwise.
23689         */
23690        boolean onContextClick(View v);
23691    }
23692
23693    /**
23694     * Interface definition for a callback to be invoked when the context menu
23695     * for this view is being built.
23696     */
23697    public interface OnCreateContextMenuListener {
23698        /**
23699         * Called when the context menu for this view is being built. It is not
23700         * safe to hold onto the menu after this method returns.
23701         *
23702         * @param menu The context menu that is being built
23703         * @param v The view for which the context menu is being built
23704         * @param menuInfo Extra information about the item for which the
23705         *            context menu should be shown. This information will vary
23706         *            depending on the class of v.
23707         */
23708        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
23709    }
23710
23711    /**
23712     * Interface definition for a callback to be invoked when the status bar changes
23713     * visibility.  This reports <strong>global</strong> changes to the system UI
23714     * state, not what the application is requesting.
23715     *
23716     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
23717     */
23718    public interface OnSystemUiVisibilityChangeListener {
23719        /**
23720         * Called when the status bar changes visibility because of a call to
23721         * {@link View#setSystemUiVisibility(int)}.
23722         *
23723         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23724         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
23725         * This tells you the <strong>global</strong> state of these UI visibility
23726         * flags, not what your app is currently applying.
23727         */
23728        public void onSystemUiVisibilityChange(int visibility);
23729    }
23730
23731    /**
23732     * Interface definition for a callback to be invoked when this view is attached
23733     * or detached from its window.
23734     */
23735    public interface OnAttachStateChangeListener {
23736        /**
23737         * Called when the view is attached to a window.
23738         * @param v The view that was attached
23739         */
23740        public void onViewAttachedToWindow(View v);
23741        /**
23742         * Called when the view is detached from a window.
23743         * @param v The view that was detached
23744         */
23745        public void onViewDetachedFromWindow(View v);
23746    }
23747
23748    /**
23749     * Listener for applying window insets on a view in a custom way.
23750     *
23751     * <p>Apps may choose to implement this interface if they want to apply custom policy
23752     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
23753     * is set, its
23754     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
23755     * method will be called instead of the View's own
23756     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
23757     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
23758     * the View's normal behavior as part of its own.</p>
23759     */
23760    public interface OnApplyWindowInsetsListener {
23761        /**
23762         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
23763         * on a View, this listener method will be called instead of the view's own
23764         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
23765         *
23766         * @param v The view applying window insets
23767         * @param insets The insets to apply
23768         * @return The insets supplied, minus any insets that were consumed
23769         */
23770        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
23771    }
23772
23773    private final class UnsetPressedState implements Runnable {
23774        @Override
23775        public void run() {
23776            setPressed(false);
23777        }
23778    }
23779
23780    /**
23781     * Base class for derived classes that want to save and restore their own
23782     * state in {@link android.view.View#onSaveInstanceState()}.
23783     */
23784    public static class BaseSavedState extends AbsSavedState {
23785        String mStartActivityRequestWhoSaved;
23786
23787        /**
23788         * Constructor used when reading from a parcel. Reads the state of the superclass.
23789         *
23790         * @param source parcel to read from
23791         */
23792        public BaseSavedState(Parcel source) {
23793            this(source, null);
23794        }
23795
23796        /**
23797         * Constructor used when reading from a parcel using a given class loader.
23798         * Reads the state of the superclass.
23799         *
23800         * @param source parcel to read from
23801         * @param loader ClassLoader to use for reading
23802         */
23803        public BaseSavedState(Parcel source, ClassLoader loader) {
23804            super(source, loader);
23805            mStartActivityRequestWhoSaved = source.readString();
23806        }
23807
23808        /**
23809         * Constructor called by derived classes when creating their SavedState objects
23810         *
23811         * @param superState The state of the superclass of this view
23812         */
23813        public BaseSavedState(Parcelable superState) {
23814            super(superState);
23815        }
23816
23817        @Override
23818        public void writeToParcel(Parcel out, int flags) {
23819            super.writeToParcel(out, flags);
23820            out.writeString(mStartActivityRequestWhoSaved);
23821        }
23822
23823        public static final Parcelable.Creator<BaseSavedState> CREATOR
23824                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
23825            @Override
23826            public BaseSavedState createFromParcel(Parcel in) {
23827                return new BaseSavedState(in);
23828            }
23829
23830            @Override
23831            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
23832                return new BaseSavedState(in, loader);
23833            }
23834
23835            @Override
23836            public BaseSavedState[] newArray(int size) {
23837                return new BaseSavedState[size];
23838            }
23839        };
23840    }
23841
23842    /**
23843     * A set of information given to a view when it is attached to its parent
23844     * window.
23845     */
23846    final static class AttachInfo {
23847        interface Callbacks {
23848            void playSoundEffect(int effectId);
23849            boolean performHapticFeedback(int effectId, boolean always);
23850        }
23851
23852        /**
23853         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
23854         * to a Handler. This class contains the target (View) to invalidate and
23855         * the coordinates of the dirty rectangle.
23856         *
23857         * For performance purposes, this class also implements a pool of up to
23858         * POOL_LIMIT objects that get reused. This reduces memory allocations
23859         * whenever possible.
23860         */
23861        static class InvalidateInfo {
23862            private static final int POOL_LIMIT = 10;
23863
23864            private static final SynchronizedPool<InvalidateInfo> sPool =
23865                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
23866
23867            View target;
23868
23869            int left;
23870            int top;
23871            int right;
23872            int bottom;
23873
23874            public static InvalidateInfo obtain() {
23875                InvalidateInfo instance = sPool.acquire();
23876                return (instance != null) ? instance : new InvalidateInfo();
23877            }
23878
23879            public void recycle() {
23880                target = null;
23881                sPool.release(this);
23882            }
23883        }
23884
23885        final IWindowSession mSession;
23886
23887        final IWindow mWindow;
23888
23889        final IBinder mWindowToken;
23890
23891        Display mDisplay;
23892
23893        final Callbacks mRootCallbacks;
23894
23895        IWindowId mIWindowId;
23896        WindowId mWindowId;
23897
23898        /**
23899         * The top view of the hierarchy.
23900         */
23901        View mRootView;
23902
23903        IBinder mPanelParentWindowToken;
23904
23905        boolean mHardwareAccelerated;
23906        boolean mHardwareAccelerationRequested;
23907        ThreadedRenderer mThreadedRenderer;
23908        List<RenderNode> mPendingAnimatingRenderNodes;
23909
23910        /**
23911         * The state of the display to which the window is attached, as reported
23912         * by {@link Display#getState()}.  Note that the display state constants
23913         * declared by {@link Display} do not exactly line up with the screen state
23914         * constants declared by {@link View} (there are more display states than
23915         * screen states).
23916         */
23917        int mDisplayState = Display.STATE_UNKNOWN;
23918
23919        /**
23920         * Scale factor used by the compatibility mode
23921         */
23922        float mApplicationScale;
23923
23924        /**
23925         * Indicates whether the application is in compatibility mode
23926         */
23927        boolean mScalingRequired;
23928
23929        /**
23930         * Left position of this view's window
23931         */
23932        int mWindowLeft;
23933
23934        /**
23935         * Top position of this view's window
23936         */
23937        int mWindowTop;
23938
23939        /**
23940         * Indicates whether views need to use 32-bit drawing caches
23941         */
23942        boolean mUse32BitDrawingCache;
23943
23944        /**
23945         * For windows that are full-screen but using insets to layout inside
23946         * of the screen areas, these are the current insets to appear inside
23947         * the overscan area of the display.
23948         */
23949        final Rect mOverscanInsets = new Rect();
23950
23951        /**
23952         * For windows that are full-screen but using insets to layout inside
23953         * of the screen decorations, these are the current insets for the
23954         * content of the window.
23955         */
23956        final Rect mContentInsets = new Rect();
23957
23958        /**
23959         * For windows that are full-screen but using insets to layout inside
23960         * of the screen decorations, these are the current insets for the
23961         * actual visible parts of the window.
23962         */
23963        final Rect mVisibleInsets = new Rect();
23964
23965        /**
23966         * For windows that are full-screen but using insets to layout inside
23967         * of the screen decorations, these are the current insets for the
23968         * stable system windows.
23969         */
23970        final Rect mStableInsets = new Rect();
23971
23972        /**
23973         * For windows that include areas that are not covered by real surface these are the outsets
23974         * for real surface.
23975         */
23976        final Rect mOutsets = new Rect();
23977
23978        /**
23979         * In multi-window we force show the navigation bar. Because we don't want that the surface
23980         * size changes in this mode, we instead have a flag whether the navigation bar size should
23981         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
23982         */
23983        boolean mAlwaysConsumeNavBar;
23984
23985        /**
23986         * The internal insets given by this window.  This value is
23987         * supplied by the client (through
23988         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
23989         * be given to the window manager when changed to be used in laying
23990         * out windows behind it.
23991         */
23992        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
23993                = new ViewTreeObserver.InternalInsetsInfo();
23994
23995        /**
23996         * Set to true when mGivenInternalInsets is non-empty.
23997         */
23998        boolean mHasNonEmptyGivenInternalInsets;
23999
24000        /**
24001         * All views in the window's hierarchy that serve as scroll containers,
24002         * used to determine if the window can be resized or must be panned
24003         * to adjust for a soft input area.
24004         */
24005        final ArrayList<View> mScrollContainers = new ArrayList<View>();
24006
24007        final KeyEvent.DispatcherState mKeyDispatchState
24008                = new KeyEvent.DispatcherState();
24009
24010        /**
24011         * Indicates whether the view's window currently has the focus.
24012         */
24013        boolean mHasWindowFocus;
24014
24015        /**
24016         * The current visibility of the window.
24017         */
24018        int mWindowVisibility;
24019
24020        /**
24021         * Indicates the time at which drawing started to occur.
24022         */
24023        long mDrawingTime;
24024
24025        /**
24026         * Indicates whether or not ignoring the DIRTY_MASK flags.
24027         */
24028        boolean mIgnoreDirtyState;
24029
24030        /**
24031         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
24032         * to avoid clearing that flag prematurely.
24033         */
24034        boolean mSetIgnoreDirtyState = false;
24035
24036        /**
24037         * Indicates whether the view's window is currently in touch mode.
24038         */
24039        boolean mInTouchMode;
24040
24041        /**
24042         * Indicates whether the view has requested unbuffered input dispatching for the current
24043         * event stream.
24044         */
24045        boolean mUnbufferedDispatchRequested;
24046
24047        /**
24048         * Indicates that ViewAncestor should trigger a global layout change
24049         * the next time it performs a traversal
24050         */
24051        boolean mRecomputeGlobalAttributes;
24052
24053        /**
24054         * Always report new attributes at next traversal.
24055         */
24056        boolean mForceReportNewAttributes;
24057
24058        /**
24059         * Set during a traveral if any views want to keep the screen on.
24060         */
24061        boolean mKeepScreenOn;
24062
24063        /**
24064         * Set during a traveral if the light center needs to be updated.
24065         */
24066        boolean mNeedsUpdateLightCenter;
24067
24068        /**
24069         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
24070         */
24071        int mSystemUiVisibility;
24072
24073        /**
24074         * Hack to force certain system UI visibility flags to be cleared.
24075         */
24076        int mDisabledSystemUiVisibility;
24077
24078        /**
24079         * Last global system UI visibility reported by the window manager.
24080         */
24081        int mGlobalSystemUiVisibility = -1;
24082
24083        /**
24084         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
24085         * attached.
24086         */
24087        boolean mHasSystemUiListeners;
24088
24089        /**
24090         * Set if the window has requested to extend into the overscan region
24091         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
24092         */
24093        boolean mOverscanRequested;
24094
24095        /**
24096         * Set if the visibility of any views has changed.
24097         */
24098        boolean mViewVisibilityChanged;
24099
24100        /**
24101         * Set to true if a view has been scrolled.
24102         */
24103        boolean mViewScrollChanged;
24104
24105        /**
24106         * Set to true if high contrast mode enabled
24107         */
24108        boolean mHighContrastText;
24109
24110        /**
24111         * Set to true if a pointer event is currently being handled.
24112         */
24113        boolean mHandlingPointerEvent;
24114
24115        /**
24116         * Global to the view hierarchy used as a temporary for dealing with
24117         * x/y points in the transparent region computations.
24118         */
24119        final int[] mTransparentLocation = new int[2];
24120
24121        /**
24122         * Global to the view hierarchy used as a temporary for dealing with
24123         * x/y points in the ViewGroup.invalidateChild implementation.
24124         */
24125        final int[] mInvalidateChildLocation = new int[2];
24126
24127        /**
24128         * Global to the view hierarchy used as a temporary for dealing with
24129         * computing absolute on-screen location.
24130         */
24131        final int[] mTmpLocation = new int[2];
24132
24133        /**
24134         * Global to the view hierarchy used as a temporary for dealing with
24135         * x/y location when view is transformed.
24136         */
24137        final float[] mTmpTransformLocation = new float[2];
24138
24139        /**
24140         * The view tree observer used to dispatch global events like
24141         * layout, pre-draw, touch mode change, etc.
24142         */
24143        final ViewTreeObserver mTreeObserver;
24144
24145        /**
24146         * A Canvas used by the view hierarchy to perform bitmap caching.
24147         */
24148        Canvas mCanvas;
24149
24150        /**
24151         * The view root impl.
24152         */
24153        final ViewRootImpl mViewRootImpl;
24154
24155        /**
24156         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
24157         * handler can be used to pump events in the UI events queue.
24158         */
24159        final Handler mHandler;
24160
24161        /**
24162         * Temporary for use in computing invalidate rectangles while
24163         * calling up the hierarchy.
24164         */
24165        final Rect mTmpInvalRect = new Rect();
24166
24167        /**
24168         * Temporary for use in computing hit areas with transformed views
24169         */
24170        final RectF mTmpTransformRect = new RectF();
24171
24172        /**
24173         * Temporary for use in computing hit areas with transformed views
24174         */
24175        final RectF mTmpTransformRect1 = new RectF();
24176
24177        /**
24178         * Temporary list of rectanges.
24179         */
24180        final List<RectF> mTmpRectList = new ArrayList<>();
24181
24182        /**
24183         * Temporary for use in transforming invalidation rect
24184         */
24185        final Matrix mTmpMatrix = new Matrix();
24186
24187        /**
24188         * Temporary for use in transforming invalidation rect
24189         */
24190        final Transformation mTmpTransformation = new Transformation();
24191
24192        /**
24193         * Temporary for use in querying outlines from OutlineProviders
24194         */
24195        final Outline mTmpOutline = new Outline();
24196
24197        /**
24198         * Temporary list for use in collecting focusable descendents of a view.
24199         */
24200        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
24201
24202        /**
24203         * The id of the window for accessibility purposes.
24204         */
24205        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
24206
24207        /**
24208         * Flags related to accessibility processing.
24209         *
24210         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
24211         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
24212         */
24213        int mAccessibilityFetchFlags;
24214
24215        /**
24216         * The drawable for highlighting accessibility focus.
24217         */
24218        Drawable mAccessibilityFocusDrawable;
24219
24220        /**
24221         * Show where the margins, bounds and layout bounds are for each view.
24222         */
24223        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
24224
24225        /**
24226         * Point used to compute visible regions.
24227         */
24228        final Point mPoint = new Point();
24229
24230        /**
24231         * Used to track which View originated a requestLayout() call, used when
24232         * requestLayout() is called during layout.
24233         */
24234        View mViewRequestingLayout;
24235
24236        /**
24237         * Used to track views that need (at least) a partial relayout at their current size
24238         * during the next traversal.
24239         */
24240        List<View> mPartialLayoutViews = new ArrayList<>();
24241
24242        /**
24243         * Swapped with mPartialLayoutViews during layout to avoid concurrent
24244         * modification. Lazily assigned during ViewRootImpl layout.
24245         */
24246        List<View> mEmptyPartialLayoutViews;
24247
24248        /**
24249         * Used to track the identity of the current drag operation.
24250         */
24251        IBinder mDragToken;
24252
24253        /**
24254         * The drag shadow surface for the current drag operation.
24255         */
24256        public Surface mDragSurface;
24257
24258
24259        /**
24260         * The view that currently has a tooltip displayed.
24261         */
24262        View mTooltipHost;
24263
24264        /**
24265         * Creates a new set of attachment information with the specified
24266         * events handler and thread.
24267         *
24268         * @param handler the events handler the view must use
24269         */
24270        AttachInfo(IWindowSession session, IWindow window, Display display,
24271                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
24272                Context context) {
24273            mSession = session;
24274            mWindow = window;
24275            mWindowToken = window.asBinder();
24276            mDisplay = display;
24277            mViewRootImpl = viewRootImpl;
24278            mHandler = handler;
24279            mRootCallbacks = effectPlayer;
24280            mTreeObserver = new ViewTreeObserver(context);
24281        }
24282    }
24283
24284    /**
24285     * <p>ScrollabilityCache holds various fields used by a View when scrolling
24286     * is supported. This avoids keeping too many unused fields in most
24287     * instances of View.</p>
24288     */
24289    private static class ScrollabilityCache implements Runnable {
24290
24291        /**
24292         * Scrollbars are not visible
24293         */
24294        public static final int OFF = 0;
24295
24296        /**
24297         * Scrollbars are visible
24298         */
24299        public static final int ON = 1;
24300
24301        /**
24302         * Scrollbars are fading away
24303         */
24304        public static final int FADING = 2;
24305
24306        public boolean fadeScrollBars;
24307
24308        public int fadingEdgeLength;
24309        public int scrollBarDefaultDelayBeforeFade;
24310        public int scrollBarFadeDuration;
24311
24312        public int scrollBarSize;
24313        public int scrollBarMinTouchTarget;
24314        public ScrollBarDrawable scrollBar;
24315        public float[] interpolatorValues;
24316        public View host;
24317
24318        public final Paint paint;
24319        public final Matrix matrix;
24320        public Shader shader;
24321
24322        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
24323
24324        private static final float[] OPAQUE = { 255 };
24325        private static final float[] TRANSPARENT = { 0.0f };
24326
24327        /**
24328         * When fading should start. This time moves into the future every time
24329         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
24330         */
24331        public long fadeStartTime;
24332
24333
24334        /**
24335         * The current state of the scrollbars: ON, OFF, or FADING
24336         */
24337        public int state = OFF;
24338
24339        private int mLastColor;
24340
24341        public final Rect mScrollBarBounds = new Rect();
24342        public final Rect mScrollBarTouchBounds = new Rect();
24343
24344        public static final int NOT_DRAGGING = 0;
24345        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
24346        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
24347        public int mScrollBarDraggingState = NOT_DRAGGING;
24348
24349        public float mScrollBarDraggingPos = 0;
24350
24351        public ScrollabilityCache(ViewConfiguration configuration, View host) {
24352            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
24353            scrollBarSize = configuration.getScaledScrollBarSize();
24354            scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget();
24355            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
24356            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
24357
24358            paint = new Paint();
24359            matrix = new Matrix();
24360            // use use a height of 1, and then wack the matrix each time we
24361            // actually use it.
24362            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
24363            paint.setShader(shader);
24364            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
24365
24366            this.host = host;
24367        }
24368
24369        public void setFadeColor(int color) {
24370            if (color != mLastColor) {
24371                mLastColor = color;
24372
24373                if (color != 0) {
24374                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
24375                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
24376                    paint.setShader(shader);
24377                    // Restore the default transfer mode (src_over)
24378                    paint.setXfermode(null);
24379                } else {
24380                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
24381                    paint.setShader(shader);
24382                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
24383                }
24384            }
24385        }
24386
24387        public void run() {
24388            long now = AnimationUtils.currentAnimationTimeMillis();
24389            if (now >= fadeStartTime) {
24390
24391                // the animation fades the scrollbars out by changing
24392                // the opacity (alpha) from fully opaque to fully
24393                // transparent
24394                int nextFrame = (int) now;
24395                int framesCount = 0;
24396
24397                Interpolator interpolator = scrollBarInterpolator;
24398
24399                // Start opaque
24400                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
24401
24402                // End transparent
24403                nextFrame += scrollBarFadeDuration;
24404                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
24405
24406                state = FADING;
24407
24408                // Kick off the fade animation
24409                host.invalidate(true);
24410            }
24411        }
24412    }
24413
24414    /**
24415     * Resuable callback for sending
24416     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
24417     */
24418    private class SendViewScrolledAccessibilityEvent implements Runnable {
24419        public volatile boolean mIsPending;
24420
24421        public void run() {
24422            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
24423            mIsPending = false;
24424        }
24425    }
24426
24427    /**
24428     * <p>
24429     * This class represents a delegate that can be registered in a {@link View}
24430     * to enhance accessibility support via composition rather via inheritance.
24431     * It is specifically targeted to widget developers that extend basic View
24432     * classes i.e. classes in package android.view, that would like their
24433     * applications to be backwards compatible.
24434     * </p>
24435     * <div class="special reference">
24436     * <h3>Developer Guides</h3>
24437     * <p>For more information about making applications accessible, read the
24438     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
24439     * developer guide.</p>
24440     * </div>
24441     * <p>
24442     * A scenario in which a developer would like to use an accessibility delegate
24443     * is overriding a method introduced in a later API version than the minimal API
24444     * version supported by the application. For example, the method
24445     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
24446     * in API version 4 when the accessibility APIs were first introduced. If a
24447     * developer would like his application to run on API version 4 devices (assuming
24448     * all other APIs used by the application are version 4 or lower) and take advantage
24449     * of this method, instead of overriding the method which would break the application's
24450     * backwards compatibility, he can override the corresponding method in this
24451     * delegate and register the delegate in the target View if the API version of
24452     * the system is high enough, i.e. the API version is the same as or higher than the API
24453     * version that introduced
24454     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
24455     * </p>
24456     * <p>
24457     * Here is an example implementation:
24458     * </p>
24459     * <code><pre><p>
24460     * if (Build.VERSION.SDK_INT >= 14) {
24461     *     // If the API version is equal of higher than the version in
24462     *     // which onInitializeAccessibilityNodeInfo was introduced we
24463     *     // register a delegate with a customized implementation.
24464     *     View view = findViewById(R.id.view_id);
24465     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
24466     *         public void onInitializeAccessibilityNodeInfo(View host,
24467     *                 AccessibilityNodeInfo info) {
24468     *             // Let the default implementation populate the info.
24469     *             super.onInitializeAccessibilityNodeInfo(host, info);
24470     *             // Set some other information.
24471     *             info.setEnabled(host.isEnabled());
24472     *         }
24473     *     });
24474     * }
24475     * </code></pre></p>
24476     * <p>
24477     * This delegate contains methods that correspond to the accessibility methods
24478     * in View. If a delegate has been specified the implementation in View hands
24479     * off handling to the corresponding method in this delegate. The default
24480     * implementation the delegate methods behaves exactly as the corresponding
24481     * method in View for the case of no accessibility delegate been set. Hence,
24482     * to customize the behavior of a View method, clients can override only the
24483     * corresponding delegate method without altering the behavior of the rest
24484     * accessibility related methods of the host view.
24485     * </p>
24486     * <p>
24487     * <strong>Note:</strong> On platform versions prior to
24488     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
24489     * views in the {@code android.widget.*} package are called <i>before</i>
24490     * host methods. This prevents certain properties such as class name from
24491     * being modified by overriding
24492     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
24493     * as any changes will be overwritten by the host class.
24494     * <p>
24495     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
24496     * methods are called <i>after</i> host methods, which all properties to be
24497     * modified without being overwritten by the host class.
24498     */
24499    public static class AccessibilityDelegate {
24500
24501        /**
24502         * Sends an accessibility event of the given type. If accessibility is not
24503         * enabled this method has no effect.
24504         * <p>
24505         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
24506         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
24507         * been set.
24508         * </p>
24509         *
24510         * @param host The View hosting the delegate.
24511         * @param eventType The type of the event to send.
24512         *
24513         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
24514         */
24515        public void sendAccessibilityEvent(View host, int eventType) {
24516            host.sendAccessibilityEventInternal(eventType);
24517        }
24518
24519        /**
24520         * Performs the specified accessibility action on the view. For
24521         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
24522         * <p>
24523         * The default implementation behaves as
24524         * {@link View#performAccessibilityAction(int, Bundle)
24525         *  View#performAccessibilityAction(int, Bundle)} for the case of
24526         *  no accessibility delegate been set.
24527         * </p>
24528         *
24529         * @param action The action to perform.
24530         * @return Whether the action was performed.
24531         *
24532         * @see View#performAccessibilityAction(int, Bundle)
24533         *      View#performAccessibilityAction(int, Bundle)
24534         */
24535        public boolean performAccessibilityAction(View host, int action, Bundle args) {
24536            return host.performAccessibilityActionInternal(action, args);
24537        }
24538
24539        /**
24540         * Sends an accessibility event. This method behaves exactly as
24541         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
24542         * empty {@link AccessibilityEvent} and does not perform a check whether
24543         * accessibility is enabled.
24544         * <p>
24545         * The default implementation behaves as
24546         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24547         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
24548         * the case of no accessibility delegate been set.
24549         * </p>
24550         *
24551         * @param host The View hosting the delegate.
24552         * @param event The event to send.
24553         *
24554         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24555         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24556         */
24557        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
24558            host.sendAccessibilityEventUncheckedInternal(event);
24559        }
24560
24561        /**
24562         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
24563         * to its children for adding their text content to the event.
24564         * <p>
24565         * The default implementation behaves as
24566         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24567         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
24568         * the case of no accessibility delegate been set.
24569         * </p>
24570         *
24571         * @param host The View hosting the delegate.
24572         * @param event The event.
24573         * @return True if the event population was completed.
24574         *
24575         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24576         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24577         */
24578        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24579            return host.dispatchPopulateAccessibilityEventInternal(event);
24580        }
24581
24582        /**
24583         * Gives a chance to the host View to populate the accessibility event with its
24584         * text content.
24585         * <p>
24586         * The default implementation behaves as
24587         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
24588         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
24589         * the case of no accessibility delegate been set.
24590         * </p>
24591         *
24592         * @param host The View hosting the delegate.
24593         * @param event The accessibility event which to populate.
24594         *
24595         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
24596         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
24597         */
24598        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24599            host.onPopulateAccessibilityEventInternal(event);
24600        }
24601
24602        /**
24603         * Initializes an {@link AccessibilityEvent} with information about the
24604         * the host View which is the event source.
24605         * <p>
24606         * The default implementation behaves as
24607         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
24608         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
24609         * the case of no accessibility delegate been set.
24610         * </p>
24611         *
24612         * @param host The View hosting the delegate.
24613         * @param event The event to initialize.
24614         *
24615         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
24616         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
24617         */
24618        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
24619            host.onInitializeAccessibilityEventInternal(event);
24620        }
24621
24622        /**
24623         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
24624         * <p>
24625         * The default implementation behaves as
24626         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24627         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
24628         * the case of no accessibility delegate been set.
24629         * </p>
24630         *
24631         * @param host The View hosting the delegate.
24632         * @param info The instance to initialize.
24633         *
24634         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24635         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24636         */
24637        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
24638            host.onInitializeAccessibilityNodeInfoInternal(info);
24639        }
24640
24641        /**
24642         * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
24643         * additional data.
24644         * <p>
24645         * This method only needs to be implemented if the View offers to provide additional data.
24646         * </p>
24647         * <p>
24648         * The default implementation behaves as
24649         * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, int) for
24650         * the case where no accessibility delegate is set.
24651         * </p>
24652         *
24653         * @param host The View hosting the delegate. Never {@code null}.
24654         * @param info The info to which to add the extra data. Never {@code null}.
24655         * @param extraDataKey A key specifying the type of extra data to add to the info. The
24656         *                     extra data should be added to the {@link Bundle} returned by
24657         *                     the info's {@link AccessibilityNodeInfo#getExtras} method.  Never
24658         *                     {@code null}.
24659         * @param arguments A {@link Bundle} holding any arguments relevant for this request.
24660         *                  May be {@code null} if the if the service provided no arguments.
24661         *
24662         * @see AccessibilityNodeInfo#setExtraAvailableData
24663         */
24664        public void addExtraDataToAccessibilityNodeInfo(@NonNull View host,
24665                @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
24666                @Nullable Bundle arguments) {
24667            host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments);
24668        }
24669
24670        /**
24671         * Called when a child of the host View has requested sending an
24672         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
24673         * to augment the event.
24674         * <p>
24675         * The default implementation behaves as
24676         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24677         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
24678         * the case of no accessibility delegate been set.
24679         * </p>
24680         *
24681         * @param host The View hosting the delegate.
24682         * @param child The child which requests sending the event.
24683         * @param event The event to be sent.
24684         * @return True if the event should be sent
24685         *
24686         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24687         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24688         */
24689        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
24690                AccessibilityEvent event) {
24691            return host.onRequestSendAccessibilityEventInternal(child, event);
24692        }
24693
24694        /**
24695         * Gets the provider for managing a virtual view hierarchy rooted at this View
24696         * and reported to {@link android.accessibilityservice.AccessibilityService}s
24697         * that explore the window content.
24698         * <p>
24699         * The default implementation behaves as
24700         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
24701         * the case of no accessibility delegate been set.
24702         * </p>
24703         *
24704         * @return The provider.
24705         *
24706         * @see AccessibilityNodeProvider
24707         */
24708        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
24709            return null;
24710        }
24711
24712        /**
24713         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
24714         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
24715         * This method is responsible for obtaining an accessibility node info from a
24716         * pool of reusable instances and calling
24717         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
24718         * view to initialize the former.
24719         * <p>
24720         * <strong>Note:</strong> The client is responsible for recycling the obtained
24721         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
24722         * creation.
24723         * </p>
24724         * <p>
24725         * The default implementation behaves as
24726         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
24727         * the case of no accessibility delegate been set.
24728         * </p>
24729         * @return A populated {@link AccessibilityNodeInfo}.
24730         *
24731         * @see AccessibilityNodeInfo
24732         *
24733         * @hide
24734         */
24735        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
24736            return host.createAccessibilityNodeInfoInternal();
24737        }
24738    }
24739
24740    private static class MatchIdPredicate implements Predicate<View> {
24741        public int mId;
24742
24743        @Override
24744        public boolean test(View view) {
24745            return (view.mID == mId);
24746        }
24747    }
24748
24749    private static class MatchLabelForPredicate implements Predicate<View> {
24750        private int mLabeledId;
24751
24752        @Override
24753        public boolean test(View view) {
24754            return (view.mLabelForId == mLabeledId);
24755        }
24756    }
24757
24758    private class SendViewStateChangedAccessibilityEvent implements Runnable {
24759        private int mChangeTypes = 0;
24760        private boolean mPosted;
24761        private boolean mPostedWithDelay;
24762        private long mLastEventTimeMillis;
24763
24764        @Override
24765        public void run() {
24766            mPosted = false;
24767            mPostedWithDelay = false;
24768            mLastEventTimeMillis = SystemClock.uptimeMillis();
24769            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
24770                final AccessibilityEvent event = AccessibilityEvent.obtain();
24771                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
24772                event.setContentChangeTypes(mChangeTypes);
24773                sendAccessibilityEventUnchecked(event);
24774            }
24775            mChangeTypes = 0;
24776        }
24777
24778        public void runOrPost(int changeType) {
24779            mChangeTypes |= changeType;
24780
24781            // If this is a live region or the child of a live region, collect
24782            // all events from this frame and send them on the next frame.
24783            if (inLiveRegion()) {
24784                // If we're already posted with a delay, remove that.
24785                if (mPostedWithDelay) {
24786                    removeCallbacks(this);
24787                    mPostedWithDelay = false;
24788                }
24789                // Only post if we're not already posted.
24790                if (!mPosted) {
24791                    post(this);
24792                    mPosted = true;
24793                }
24794                return;
24795            }
24796
24797            if (mPosted) {
24798                return;
24799            }
24800
24801            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
24802            final long minEventIntevalMillis =
24803                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
24804            if (timeSinceLastMillis >= minEventIntevalMillis) {
24805                removeCallbacks(this);
24806                run();
24807            } else {
24808                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
24809                mPostedWithDelay = true;
24810            }
24811        }
24812    }
24813
24814    private boolean inLiveRegion() {
24815        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24816            return true;
24817        }
24818
24819        ViewParent parent = getParent();
24820        while (parent instanceof View) {
24821            if (((View) parent).getAccessibilityLiveRegion()
24822                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24823                return true;
24824            }
24825            parent = parent.getParent();
24826        }
24827
24828        return false;
24829    }
24830
24831    /**
24832     * Dump all private flags in readable format, useful for documentation and
24833     * sanity checking.
24834     */
24835    private static void dumpFlags() {
24836        final HashMap<String, String> found = Maps.newHashMap();
24837        try {
24838            for (Field field : View.class.getDeclaredFields()) {
24839                final int modifiers = field.getModifiers();
24840                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
24841                    if (field.getType().equals(int.class)) {
24842                        final int value = field.getInt(null);
24843                        dumpFlag(found, field.getName(), value);
24844                    } else if (field.getType().equals(int[].class)) {
24845                        final int[] values = (int[]) field.get(null);
24846                        for (int i = 0; i < values.length; i++) {
24847                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
24848                        }
24849                    }
24850                }
24851            }
24852        } catch (IllegalAccessException e) {
24853            throw new RuntimeException(e);
24854        }
24855
24856        final ArrayList<String> keys = Lists.newArrayList();
24857        keys.addAll(found.keySet());
24858        Collections.sort(keys);
24859        for (String key : keys) {
24860            Log.d(VIEW_LOG_TAG, found.get(key));
24861        }
24862    }
24863
24864    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
24865        // Sort flags by prefix, then by bits, always keeping unique keys
24866        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
24867        final int prefix = name.indexOf('_');
24868        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
24869        final String output = bits + " " + name;
24870        found.put(key, output);
24871    }
24872
24873    /** {@hide} */
24874    public void encode(@NonNull ViewHierarchyEncoder stream) {
24875        stream.beginObject(this);
24876        encodeProperties(stream);
24877        stream.endObject();
24878    }
24879
24880    /** {@hide} */
24881    @CallSuper
24882    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
24883        Object resolveId = ViewDebug.resolveId(getContext(), mID);
24884        if (resolveId instanceof String) {
24885            stream.addProperty("id", (String) resolveId);
24886        } else {
24887            stream.addProperty("id", mID);
24888        }
24889
24890        stream.addProperty("misc:transformation.alpha",
24891                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
24892        stream.addProperty("misc:transitionName", getTransitionName());
24893
24894        // layout
24895        stream.addProperty("layout:left", mLeft);
24896        stream.addProperty("layout:right", mRight);
24897        stream.addProperty("layout:top", mTop);
24898        stream.addProperty("layout:bottom", mBottom);
24899        stream.addProperty("layout:width", getWidth());
24900        stream.addProperty("layout:height", getHeight());
24901        stream.addProperty("layout:layoutDirection", getLayoutDirection());
24902        stream.addProperty("layout:layoutRtl", isLayoutRtl());
24903        stream.addProperty("layout:hasTransientState", hasTransientState());
24904        stream.addProperty("layout:baseline", getBaseline());
24905
24906        // layout params
24907        ViewGroup.LayoutParams layoutParams = getLayoutParams();
24908        if (layoutParams != null) {
24909            stream.addPropertyKey("layoutParams");
24910            layoutParams.encode(stream);
24911        }
24912
24913        // scrolling
24914        stream.addProperty("scrolling:scrollX", mScrollX);
24915        stream.addProperty("scrolling:scrollY", mScrollY);
24916
24917        // padding
24918        stream.addProperty("padding:paddingLeft", mPaddingLeft);
24919        stream.addProperty("padding:paddingRight", mPaddingRight);
24920        stream.addProperty("padding:paddingTop", mPaddingTop);
24921        stream.addProperty("padding:paddingBottom", mPaddingBottom);
24922        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
24923        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
24924        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
24925        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
24926        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
24927
24928        // measurement
24929        stream.addProperty("measurement:minHeight", mMinHeight);
24930        stream.addProperty("measurement:minWidth", mMinWidth);
24931        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
24932        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
24933
24934        // drawing
24935        stream.addProperty("drawing:elevation", getElevation());
24936        stream.addProperty("drawing:translationX", getTranslationX());
24937        stream.addProperty("drawing:translationY", getTranslationY());
24938        stream.addProperty("drawing:translationZ", getTranslationZ());
24939        stream.addProperty("drawing:rotation", getRotation());
24940        stream.addProperty("drawing:rotationX", getRotationX());
24941        stream.addProperty("drawing:rotationY", getRotationY());
24942        stream.addProperty("drawing:scaleX", getScaleX());
24943        stream.addProperty("drawing:scaleY", getScaleY());
24944        stream.addProperty("drawing:pivotX", getPivotX());
24945        stream.addProperty("drawing:pivotY", getPivotY());
24946        stream.addProperty("drawing:opaque", isOpaque());
24947        stream.addProperty("drawing:alpha", getAlpha());
24948        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
24949        stream.addProperty("drawing:shadow", hasShadow());
24950        stream.addProperty("drawing:solidColor", getSolidColor());
24951        stream.addProperty("drawing:layerType", mLayerType);
24952        stream.addProperty("drawing:willNotDraw", willNotDraw());
24953        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
24954        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
24955        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
24956        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
24957
24958        // focus
24959        stream.addProperty("focus:hasFocus", hasFocus());
24960        stream.addProperty("focus:isFocused", isFocused());
24961        stream.addProperty("focus:isFocusable", isFocusable());
24962        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
24963
24964        stream.addProperty("misc:clickable", isClickable());
24965        stream.addProperty("misc:pressed", isPressed());
24966        stream.addProperty("misc:selected", isSelected());
24967        stream.addProperty("misc:touchMode", isInTouchMode());
24968        stream.addProperty("misc:hovered", isHovered());
24969        stream.addProperty("misc:activated", isActivated());
24970
24971        stream.addProperty("misc:visibility", getVisibility());
24972        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
24973        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
24974
24975        stream.addProperty("misc:enabled", isEnabled());
24976        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
24977        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
24978
24979        // theme attributes
24980        Resources.Theme theme = getContext().getTheme();
24981        if (theme != null) {
24982            stream.addPropertyKey("theme");
24983            theme.encode(stream);
24984        }
24985
24986        // view attribute information
24987        int n = mAttributes != null ? mAttributes.length : 0;
24988        stream.addProperty("meta:__attrCount__", n/2);
24989        for (int i = 0; i < n; i += 2) {
24990            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
24991        }
24992
24993        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
24994
24995        // text
24996        stream.addProperty("text:textDirection", getTextDirection());
24997        stream.addProperty("text:textAlignment", getTextAlignment());
24998
24999        // accessibility
25000        CharSequence contentDescription = getContentDescription();
25001        stream.addProperty("accessibility:contentDescription",
25002                contentDescription == null ? "" : contentDescription.toString());
25003        stream.addProperty("accessibility:labelFor", getLabelFor());
25004        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
25005    }
25006
25007    /**
25008     * Determine if this view is rendered on a round wearable device and is the main view
25009     * on the screen.
25010     */
25011    boolean shouldDrawRoundScrollbar() {
25012        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
25013            return false;
25014        }
25015
25016        final View rootView = getRootView();
25017        final WindowInsets insets = getRootWindowInsets();
25018
25019        int height = getHeight();
25020        int width = getWidth();
25021        int displayHeight = rootView.getHeight();
25022        int displayWidth = rootView.getWidth();
25023
25024        if (height != displayHeight || width != displayWidth) {
25025            return false;
25026        }
25027
25028        getLocationInWindow(mAttachInfo.mTmpLocation);
25029        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
25030                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
25031    }
25032
25033    /**
25034     * Sets the tooltip text which will be displayed in a small popup next to the view.
25035     * <p>
25036     * The tooltip will be displayed:
25037     * <ul>
25038     * <li>On long click, unless is not handled otherwise (by OnLongClickListener or a context
25039     * menu). </li>
25040     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
25041     * </ul>
25042     * <p>
25043     * <strong>Note:</strong> Do not override this method, as it will have no
25044     * effect on the text displayed in the tooltip.
25045     *
25046     * @param tooltipText the tooltip text, or null if no tooltip is required
25047     * @see #getTooltipText()
25048     * @attr ref android.R.styleable#View_tooltipText
25049     */
25050    public void setTooltipText(@Nullable CharSequence tooltipText) {
25051        if (TextUtils.isEmpty(tooltipText)) {
25052            setFlags(0, TOOLTIP);
25053            hideTooltip();
25054            mTooltipInfo = null;
25055        } else {
25056            setFlags(TOOLTIP, TOOLTIP);
25057            if (mTooltipInfo == null) {
25058                mTooltipInfo = new TooltipInfo();
25059                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
25060                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
25061            }
25062            mTooltipInfo.mTooltipText = tooltipText;
25063            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
25064                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText);
25065            }
25066        }
25067    }
25068
25069    /**
25070     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
25071     */
25072    public void setTooltip(@Nullable CharSequence tooltipText) {
25073        setTooltipText(tooltipText);
25074    }
25075
25076    /**
25077     * Returns the view's tooltip text.
25078     *
25079     * <strong>Note:</strong> Do not override this method, as it will have no
25080     * effect on the text displayed in the tooltip. You must call
25081     * {@link #setTooltipText(CharSequence)} to modify the tooltip text.
25082     *
25083     * @return the tooltip text
25084     * @see #setTooltipText(CharSequence)
25085     * @attr ref android.R.styleable#View_tooltipText
25086     */
25087    @Nullable
25088    public CharSequence getTooltipText() {
25089        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
25090    }
25091
25092    /**
25093     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
25094     */
25095    @Nullable
25096    public CharSequence getTooltip() {
25097        return getTooltipText();
25098    }
25099
25100    private boolean showTooltip(int x, int y, boolean fromLongClick) {
25101        if (mAttachInfo == null || mTooltipInfo == null) {
25102            return false;
25103        }
25104        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
25105            return false;
25106        }
25107        if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) {
25108            return false;
25109        }
25110        hideTooltip();
25111        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
25112        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
25113        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
25114        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText);
25115        mAttachInfo.mTooltipHost = this;
25116        return true;
25117    }
25118
25119    void hideTooltip() {
25120        if (mTooltipInfo == null) {
25121            return;
25122        }
25123        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25124        if (mTooltipInfo.mTooltipPopup == null) {
25125            return;
25126        }
25127        mTooltipInfo.mTooltipPopup.hide();
25128        mTooltipInfo.mTooltipPopup = null;
25129        mTooltipInfo.mTooltipFromLongClick = false;
25130        if (mAttachInfo != null) {
25131            mAttachInfo.mTooltipHost = null;
25132        }
25133    }
25134
25135    private boolean showLongClickTooltip(int x, int y) {
25136        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25137        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25138        return showTooltip(x, y, true);
25139    }
25140
25141    private void showHoverTooltip() {
25142        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
25143    }
25144
25145    boolean dispatchTooltipHoverEvent(MotionEvent event) {
25146        if (mTooltipInfo == null) {
25147            return false;
25148        }
25149        switch(event.getAction()) {
25150            case MotionEvent.ACTION_HOVER_MOVE:
25151                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
25152                    break;
25153                }
25154                if (!mTooltipInfo.mTooltipFromLongClick) {
25155                    if (mTooltipInfo.mTooltipPopup == null) {
25156                        // Schedule showing the tooltip after a timeout.
25157                        mTooltipInfo.mAnchorX = (int) event.getX();
25158                        mTooltipInfo.mAnchorY = (int) event.getY();
25159                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25160                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
25161                                ViewConfiguration.getHoverTooltipShowTimeout());
25162                    }
25163
25164                    // Hide hover-triggered tooltip after a period of inactivity.
25165                    // Match the timeout used by NativeInputManager to hide the mouse pointer
25166                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
25167                    final int timeout;
25168                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
25169                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
25170                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
25171                    } else {
25172                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
25173                    }
25174                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25175                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
25176                }
25177                return true;
25178
25179            case MotionEvent.ACTION_HOVER_EXIT:
25180                if (!mTooltipInfo.mTooltipFromLongClick) {
25181                    hideTooltip();
25182                }
25183                break;
25184        }
25185        return false;
25186    }
25187
25188    void handleTooltipKey(KeyEvent event) {
25189        switch (event.getAction()) {
25190            case KeyEvent.ACTION_DOWN:
25191                if (event.getRepeatCount() == 0) {
25192                    hideTooltip();
25193                }
25194                break;
25195
25196            case KeyEvent.ACTION_UP:
25197                handleTooltipUp();
25198                break;
25199        }
25200    }
25201
25202    private void handleTooltipUp() {
25203        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
25204            return;
25205        }
25206        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25207        postDelayed(mTooltipInfo.mHideTooltipRunnable,
25208                ViewConfiguration.getLongPressTooltipHideTimeout());
25209    }
25210
25211    private int getFocusableAttribute(TypedArray attributes) {
25212        TypedValue val = new TypedValue();
25213        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
25214            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
25215                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
25216            } else {
25217                return val.data;
25218            }
25219        } else {
25220            return FOCUSABLE_AUTO;
25221        }
25222    }
25223
25224    /**
25225     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
25226     * is not showing.
25227     * @hide
25228     */
25229    @TestApi
25230    public View getTooltipView() {
25231        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
25232            return null;
25233        }
25234        return mTooltipInfo.mTooltipPopup.getContentView();
25235    }
25236}
25237