View.java revision 8e1a72964517bfd01d8e650453ef41e22f770f21
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>This method already provides most of what's needed for auto-fill, but should be overridden
6987     * <ol>
6988     * <li>The view contents does not include PII (Personally Identifiable Information), so it
6989     * can call {@link ViewStructure#setSanitized(boolean)} passing {@code true}.
6990     * <li>It must set fields such {@link ViewStructure#setText(CharSequence)},
6991     * {@link ViewStructure#setAutoFillOptions(String[])}, or {@link ViewStructure#setUrl(String)}.
6992     * </ol>
6993     *
6994     * @param structure Fill in with structured view data. The default implementation
6995     * fills in all data that can be inferred from the view itself.
6996     * @param flags optional flags (currently {@code 0}).
6997     */
6998    @CallSuper
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,
9437            @FocusDirection int direction) {
9438        if (isKeyboardNavigationCluster()) {
9439            currentCluster = this;
9440        }
9441        if (isRootNamespace()) {
9442            // Root namespace means we should consider ourselves the top of the
9443            // tree for group searching; otherwise we could be group searching
9444            // into other tabs.  see LocalActivityManager and TabHost for more info.
9445            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
9446                    this, currentCluster, direction);
9447        } else if (mParent != null) {
9448            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
9449        }
9450        return null;
9451    }
9452
9453    /**
9454     * This method is the last chance for the focused view and its ancestors to
9455     * respond to an arrow key. This is called when the focused view did not
9456     * consume the key internally, nor could the view system find a new view in
9457     * the requested direction to give focus to.
9458     *
9459     * @param focused The currently focused view.
9460     * @param direction The direction focus wants to move. One of FOCUS_UP,
9461     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
9462     * @return True if the this view consumed this unhandled move.
9463     */
9464    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
9465        return false;
9466    }
9467
9468    /**
9469     * If a user manually specified the next view id for a particular direction,
9470     * use the root to look up the view.
9471     * @param root The root view of the hierarchy containing this view.
9472     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
9473     * or FOCUS_BACKWARD.
9474     * @return The user specified next view, or null if there is none.
9475     */
9476    View findUserSetNextFocus(View root, @FocusDirection int direction) {
9477        switch (direction) {
9478            case FOCUS_LEFT:
9479                if (mNextFocusLeftId == View.NO_ID) return null;
9480                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
9481            case FOCUS_RIGHT:
9482                if (mNextFocusRightId == View.NO_ID) return null;
9483                return findViewInsideOutShouldExist(root, mNextFocusRightId);
9484            case FOCUS_UP:
9485                if (mNextFocusUpId == View.NO_ID) return null;
9486                return findViewInsideOutShouldExist(root, mNextFocusUpId);
9487            case FOCUS_DOWN:
9488                if (mNextFocusDownId == View.NO_ID) return null;
9489                return findViewInsideOutShouldExist(root, mNextFocusDownId);
9490            case FOCUS_FORWARD:
9491                if (mNextFocusForwardId == View.NO_ID) return null;
9492                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
9493            case FOCUS_BACKWARD: {
9494                if (mID == View.NO_ID) return null;
9495                final int id = mID;
9496                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
9497                    @Override
9498                    public boolean test(View t) {
9499                        return t.mNextFocusForwardId == id;
9500                    }
9501                });
9502            }
9503        }
9504        return null;
9505    }
9506
9507    private View findViewInsideOutShouldExist(View root, int id) {
9508        if (mMatchIdPredicate == null) {
9509            mMatchIdPredicate = new MatchIdPredicate();
9510        }
9511        mMatchIdPredicate.mId = id;
9512        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
9513        if (result == null) {
9514            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
9515        }
9516        return result;
9517    }
9518
9519    /**
9520     * Find and return all focusable views that are descendants of this view,
9521     * possibly including this view if it is focusable itself.
9522     *
9523     * @param direction The direction of the focus
9524     * @return A list of focusable views
9525     */
9526    public ArrayList<View> getFocusables(@FocusDirection int direction) {
9527        ArrayList<View> result = new ArrayList<View>(24);
9528        addFocusables(result, direction);
9529        return result;
9530    }
9531
9532    /**
9533     * Add any focusable views that are descendants of this view (possibly
9534     * including this view if it is focusable itself) to views.  If we are in touch mode,
9535     * only add views that are also focusable in touch mode.
9536     *
9537     * @param views Focusable views found so far
9538     * @param direction The direction of the focus
9539     */
9540    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
9541        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
9542    }
9543
9544    /**
9545     * Adds any focusable views that are descendants of this view (possibly
9546     * including this view if it is focusable itself) to views. This method
9547     * adds all focusable views regardless if we are in touch mode or
9548     * only views focusable in touch mode if we are in touch mode or
9549     * only views that can take accessibility focus if accessibility is enabled
9550     * depending on the focusable mode parameter.
9551     *
9552     * @param views Focusable views found so far or null if all we are interested is
9553     *        the number of focusables.
9554     * @param direction The direction of the focus.
9555     * @param focusableMode The type of focusables to be added.
9556     *
9557     * @see #FOCUSABLES_ALL
9558     * @see #FOCUSABLES_TOUCH_MODE
9559     */
9560    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
9561            @FocusableMode int focusableMode) {
9562        if (views == null) {
9563            return;
9564        }
9565        if (!isFocusable()) {
9566            return;
9567        }
9568        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
9569                && !isFocusableInTouchMode()) {
9570            return;
9571        }
9572        views.add(this);
9573    }
9574
9575    /**
9576     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
9577     * including this view if it is a cluster root itself) to views.
9578     *
9579     * @param views Keyboard navigation cluster roots found so far
9580     * @param direction Direction to look
9581     */
9582    public void addKeyboardNavigationClusters(
9583            @NonNull Collection<View> views,
9584            int direction) {
9585        if (!isKeyboardNavigationCluster()) {
9586            return;
9587        }
9588        if (!hasFocusable()) {
9589            return;
9590        }
9591        views.add(this);
9592    }
9593
9594    /**
9595     * Finds the Views that contain given text. The containment is case insensitive.
9596     * The search is performed by either the text that the View renders or the content
9597     * description that describes the view for accessibility purposes and the view does
9598     * not render or both. Clients can specify how the search is to be performed via
9599     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
9600     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
9601     *
9602     * @param outViews The output list of matching Views.
9603     * @param searched The text to match against.
9604     *
9605     * @see #FIND_VIEWS_WITH_TEXT
9606     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
9607     * @see #setContentDescription(CharSequence)
9608     */
9609    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
9610            @FindViewFlags int flags) {
9611        if (getAccessibilityNodeProvider() != null) {
9612            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
9613                outViews.add(this);
9614            }
9615        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
9616                && (searched != null && searched.length() > 0)
9617                && (mContentDescription != null && mContentDescription.length() > 0)) {
9618            String searchedLowerCase = searched.toString().toLowerCase();
9619            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
9620            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
9621                outViews.add(this);
9622            }
9623        }
9624    }
9625
9626    /**
9627     * Find and return all touchable views that are descendants of this view,
9628     * possibly including this view if it is touchable itself.
9629     *
9630     * @return A list of touchable views
9631     */
9632    public ArrayList<View> getTouchables() {
9633        ArrayList<View> result = new ArrayList<View>();
9634        addTouchables(result);
9635        return result;
9636    }
9637
9638    /**
9639     * Add any touchable views that are descendants of this view (possibly
9640     * including this view if it is touchable itself) to views.
9641     *
9642     * @param views Touchable views found so far
9643     */
9644    public void addTouchables(ArrayList<View> views) {
9645        final int viewFlags = mViewFlags;
9646
9647        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
9648                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
9649                && (viewFlags & ENABLED_MASK) == ENABLED) {
9650            views.add(this);
9651        }
9652    }
9653
9654    /**
9655     * Returns whether this View is accessibility focused.
9656     *
9657     * @return True if this View is accessibility focused.
9658     */
9659    public boolean isAccessibilityFocused() {
9660        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
9661    }
9662
9663    /**
9664     * Call this to try to give accessibility focus to this view.
9665     *
9666     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
9667     * returns false or the view is no visible or the view already has accessibility
9668     * focus.
9669     *
9670     * See also {@link #focusSearch(int)}, which is what you call to say that you
9671     * have focus, and you want your parent to look for the next one.
9672     *
9673     * @return Whether this view actually took accessibility focus.
9674     *
9675     * @hide
9676     */
9677    public boolean requestAccessibilityFocus() {
9678        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
9679        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
9680            return false;
9681        }
9682        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9683            return false;
9684        }
9685        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
9686            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
9687            ViewRootImpl viewRootImpl = getViewRootImpl();
9688            if (viewRootImpl != null) {
9689                viewRootImpl.setAccessibilityFocus(this, null);
9690            }
9691            invalidate();
9692            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
9693            return true;
9694        }
9695        return false;
9696    }
9697
9698    /**
9699     * Call this to try to clear accessibility focus of this view.
9700     *
9701     * See also {@link #focusSearch(int)}, which is what you call to say that you
9702     * have focus, and you want your parent to look for the next one.
9703     *
9704     * @hide
9705     */
9706    public void clearAccessibilityFocus() {
9707        clearAccessibilityFocusNoCallbacks(0);
9708
9709        // Clear the global reference of accessibility focus if this view or
9710        // any of its descendants had accessibility focus. This will NOT send
9711        // an event or update internal state if focus is cleared from a
9712        // descendant view, which may leave views in inconsistent states.
9713        final ViewRootImpl viewRootImpl = getViewRootImpl();
9714        if (viewRootImpl != null) {
9715            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
9716            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9717                viewRootImpl.setAccessibilityFocus(null, null);
9718            }
9719        }
9720    }
9721
9722    private void sendAccessibilityHoverEvent(int eventType) {
9723        // Since we are not delivering to a client accessibility events from not
9724        // important views (unless the clinet request that) we need to fire the
9725        // event from the deepest view exposed to the client. As a consequence if
9726        // the user crosses a not exposed view the client will see enter and exit
9727        // of the exposed predecessor followed by and enter and exit of that same
9728        // predecessor when entering and exiting the not exposed descendant. This
9729        // is fine since the client has a clear idea which view is hovered at the
9730        // price of a couple more events being sent. This is a simple and
9731        // working solution.
9732        View source = this;
9733        while (true) {
9734            if (source.includeForAccessibility()) {
9735                source.sendAccessibilityEvent(eventType);
9736                return;
9737            }
9738            ViewParent parent = source.getParent();
9739            if (parent instanceof View) {
9740                source = (View) parent;
9741            } else {
9742                return;
9743            }
9744        }
9745    }
9746
9747    /**
9748     * Clears accessibility focus without calling any callback methods
9749     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9750     * is used separately from that one for clearing accessibility focus when
9751     * giving this focus to another view.
9752     *
9753     * @param action The action, if any, that led to focus being cleared. Set to
9754     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9755     * the window.
9756     */
9757    void clearAccessibilityFocusNoCallbacks(int action) {
9758        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9759            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9760            invalidate();
9761            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9762                AccessibilityEvent event = AccessibilityEvent.obtain(
9763                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9764                event.setAction(action);
9765                if (mAccessibilityDelegate != null) {
9766                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9767                } else {
9768                    sendAccessibilityEventUnchecked(event);
9769                }
9770            }
9771        }
9772    }
9773
9774    /**
9775     * Call this to try to give focus to a specific view or to one of its
9776     * descendants.
9777     *
9778     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9779     * false), or if it is focusable and it is not focusable in touch mode
9780     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9781     *
9782     * See also {@link #focusSearch(int)}, which is what you call to say that you
9783     * have focus, and you want your parent to look for the next one.
9784     *
9785     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9786     * {@link #FOCUS_DOWN} and <code>null</code>.
9787     *
9788     * @return Whether this view or one of its descendants actually took focus.
9789     */
9790    public final boolean requestFocus() {
9791        return requestFocus(View.FOCUS_DOWN);
9792    }
9793
9794    /**
9795     * This will request focus for whichever View was last focused within this
9796     * cluster before a focus-jump out of it.
9797     *
9798     * @hide
9799     */
9800    @TestApi
9801    public boolean restoreFocusInCluster(@FocusRealDirection int direction) {
9802        // Prioritize focusableByDefault over algorithmic focus selection.
9803        if (restoreDefaultFocus()) {
9804            return true;
9805        }
9806        return requestFocus(direction);
9807    }
9808
9809    /**
9810     * This will request focus for whichever View not in a cluster was last focused before a
9811     * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus
9812     * the "first" focusable view it finds.
9813     *
9814     * @hide
9815     */
9816    @TestApi
9817    public boolean restoreFocusNotInCluster() {
9818        return requestFocus(View.FOCUS_DOWN);
9819    }
9820
9821    /**
9822     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
9823     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
9824     *
9825     * @return Whether this view or one of its descendants actually took focus
9826     */
9827    public boolean restoreDefaultFocus() {
9828        return requestFocus(View.FOCUS_DOWN);
9829    }
9830
9831    /**
9832     * Call this to try to give focus to a specific view or to one of its
9833     * descendants and give it a hint about what direction focus is heading.
9834     *
9835     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9836     * false), or if it is focusable and it is not focusable in touch mode
9837     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9838     *
9839     * See also {@link #focusSearch(int)}, which is what you call to say that you
9840     * have focus, and you want your parent to look for the next one.
9841     *
9842     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9843     * <code>null</code> set for the previously focused rectangle.
9844     *
9845     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9846     * @return Whether this view or one of its descendants actually took focus.
9847     */
9848    public final boolean requestFocus(int direction) {
9849        return requestFocus(direction, null);
9850    }
9851
9852    /**
9853     * Call this to try to give focus to a specific view or to one of its descendants
9854     * and give it hints about the direction and a specific rectangle that the focus
9855     * is coming from.  The rectangle can help give larger views a finer grained hint
9856     * about where focus is coming from, and therefore, where to show selection, or
9857     * forward focus change internally.
9858     *
9859     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9860     * false), or if it is focusable and it is not focusable in touch mode
9861     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9862     *
9863     * A View will not take focus if it is not visible.
9864     *
9865     * A View will not take focus if one of its parents has
9866     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9867     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9868     *
9869     * See also {@link #focusSearch(int)}, which is what you call to say that you
9870     * have focus, and you want your parent to look for the next one.
9871     *
9872     * You may wish to override this method if your custom {@link View} has an internal
9873     * {@link View} that it wishes to forward the request to.
9874     *
9875     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9876     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9877     *        to give a finer grained hint about where focus is coming from.  May be null
9878     *        if there is no hint.
9879     * @return Whether this view or one of its descendants actually took focus.
9880     */
9881    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9882        return requestFocusNoSearch(direction, previouslyFocusedRect);
9883    }
9884
9885    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9886        // need to be focusable
9887        if ((mViewFlags & FOCUSABLE) != FOCUSABLE
9888                || (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9889            return false;
9890        }
9891
9892        // need to be focusable in touch mode if in touch mode
9893        if (isInTouchMode() &&
9894            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9895               return false;
9896        }
9897
9898        // need to not have any parents blocking us
9899        if (hasAncestorThatBlocksDescendantFocus()) {
9900            return false;
9901        }
9902
9903        handleFocusGainInternal(direction, previouslyFocusedRect);
9904        return true;
9905    }
9906
9907    /**
9908     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9909     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9910     * touch mode to request focus when they are touched.
9911     *
9912     * @return Whether this view or one of its descendants actually took focus.
9913     *
9914     * @see #isInTouchMode()
9915     *
9916     */
9917    public final boolean requestFocusFromTouch() {
9918        // Leave touch mode if we need to
9919        if (isInTouchMode()) {
9920            ViewRootImpl viewRoot = getViewRootImpl();
9921            if (viewRoot != null) {
9922                viewRoot.ensureTouchMode(false);
9923            }
9924        }
9925        return requestFocus(View.FOCUS_DOWN);
9926    }
9927
9928    /**
9929     * @return Whether any ancestor of this view blocks descendant focus.
9930     */
9931    private boolean hasAncestorThatBlocksDescendantFocus() {
9932        final boolean focusableInTouchMode = isFocusableInTouchMode();
9933        ViewParent ancestor = mParent;
9934        while (ancestor instanceof ViewGroup) {
9935            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9936            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9937                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9938                return true;
9939            } else {
9940                ancestor = vgAncestor.getParent();
9941            }
9942        }
9943        return false;
9944    }
9945
9946    /**
9947     * Gets the mode for determining whether this View is important for accessibility.
9948     * A view is important for accessibility if it fires accessibility events and if it
9949     * is reported to accessibility services that query the screen.
9950     *
9951     * @return The mode for determining whether a view is important for accessibility, one
9952     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
9953     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
9954     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
9955     *
9956     * @attr ref android.R.styleable#View_importantForAccessibility
9957     *
9958     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9959     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9960     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9961     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9962     */
9963    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9964            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9965            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9966            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9967            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9968                    to = "noHideDescendants")
9969        })
9970    public int getImportantForAccessibility() {
9971        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9972                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9973    }
9974
9975    /**
9976     * Sets the live region mode for this view. This indicates to accessibility
9977     * services whether they should automatically notify the user about changes
9978     * to the view's content description or text, or to the content descriptions
9979     * or text of the view's children (where applicable).
9980     * <p>
9981     * For example, in a login screen with a TextView that displays an "incorrect
9982     * password" notification, that view should be marked as a live region with
9983     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9984     * <p>
9985     * To disable change notifications for this view, use
9986     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9987     * mode for most views.
9988     * <p>
9989     * To indicate that the user should be notified of changes, use
9990     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9991     * <p>
9992     * If the view's changes should interrupt ongoing speech and notify the user
9993     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9994     *
9995     * @param mode The live region mode for this view, one of:
9996     *        <ul>
9997     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9998     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9999     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
10000     *        </ul>
10001     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10002     */
10003    public void setAccessibilityLiveRegion(int mode) {
10004        if (mode != getAccessibilityLiveRegion()) {
10005            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10006            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
10007                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10008            notifyViewAccessibilityStateChangedIfNeeded(
10009                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10010        }
10011    }
10012
10013    /**
10014     * Gets the live region mode for this View.
10015     *
10016     * @return The live region mode for the view.
10017     *
10018     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10019     *
10020     * @see #setAccessibilityLiveRegion(int)
10021     */
10022    public int getAccessibilityLiveRegion() {
10023        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
10024                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
10025    }
10026
10027    /**
10028     * Sets how to determine whether this view is important for accessibility
10029     * which is if it fires accessibility events and if it is reported to
10030     * accessibility services that query the screen.
10031     *
10032     * @param mode How to determine whether this view is important for accessibility.
10033     *
10034     * @attr ref android.R.styleable#View_importantForAccessibility
10035     *
10036     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
10037     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
10038     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
10039     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
10040     */
10041    public void setImportantForAccessibility(int mode) {
10042        final int oldMode = getImportantForAccessibility();
10043        if (mode != oldMode) {
10044            final boolean hideDescendants =
10045                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
10046
10047            // If this node or its descendants are no longer important, try to
10048            // clear accessibility focus.
10049            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
10050                final View focusHost = findAccessibilityFocusHost(hideDescendants);
10051                if (focusHost != null) {
10052                    focusHost.clearAccessibilityFocus();
10053                }
10054            }
10055
10056            // If we're moving between AUTO and another state, we might not need
10057            // to send a subtree changed notification. We'll store the computed
10058            // importance, since we'll need to check it later to make sure.
10059            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
10060                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
10061            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
10062            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10063            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
10064                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10065            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
10066                notifySubtreeAccessibilityStateChangedIfNeeded();
10067            } else {
10068                notifyViewAccessibilityStateChangedIfNeeded(
10069                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10070            }
10071        }
10072    }
10073
10074    /**
10075     * Returns the view within this view's hierarchy that is hosting
10076     * accessibility focus.
10077     *
10078     * @param searchDescendants whether to search for focus in descendant views
10079     * @return the view hosting accessibility focus, or {@code null}
10080     */
10081    private View findAccessibilityFocusHost(boolean searchDescendants) {
10082        if (isAccessibilityFocusedViewOrHost()) {
10083            return this;
10084        }
10085
10086        if (searchDescendants) {
10087            final ViewRootImpl viewRoot = getViewRootImpl();
10088            if (viewRoot != null) {
10089                final View focusHost = viewRoot.getAccessibilityFocusedHost();
10090                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
10091                    return focusHost;
10092                }
10093            }
10094        }
10095
10096        return null;
10097    }
10098
10099    /**
10100     * Computes whether this view should be exposed for accessibility. In
10101     * general, views that are interactive or provide information are exposed
10102     * while views that serve only as containers are hidden.
10103     * <p>
10104     * If an ancestor of this view has importance
10105     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
10106     * returns <code>false</code>.
10107     * <p>
10108     * Otherwise, the value is computed according to the view's
10109     * {@link #getImportantForAccessibility()} value:
10110     * <ol>
10111     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
10112     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
10113     * </code>
10114     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
10115     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
10116     * view satisfies any of the following:
10117     * <ul>
10118     * <li>Is actionable, e.g. {@link #isClickable()},
10119     * {@link #isLongClickable()}, or {@link #isFocusable()}
10120     * <li>Has an {@link AccessibilityDelegate}
10121     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
10122     * {@link OnKeyListener}, etc.
10123     * <li>Is an accessibility live region, e.g.
10124     * {@link #getAccessibilityLiveRegion()} is not
10125     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
10126     * </ul>
10127     * </ol>
10128     *
10129     * @return Whether the view is exposed for accessibility.
10130     * @see #setImportantForAccessibility(int)
10131     * @see #getImportantForAccessibility()
10132     */
10133    public boolean isImportantForAccessibility() {
10134        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
10135                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
10136        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
10137                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10138            return false;
10139        }
10140
10141        // Check parent mode to ensure we're not hidden.
10142        ViewParent parent = mParent;
10143        while (parent instanceof View) {
10144            if (((View) parent).getImportantForAccessibility()
10145                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10146                return false;
10147            }
10148            parent = parent.getParent();
10149        }
10150
10151        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
10152                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
10153                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
10154    }
10155
10156    /**
10157     * Gets the parent for accessibility purposes. Note that the parent for
10158     * accessibility is not necessary the immediate parent. It is the first
10159     * predecessor that is important for accessibility.
10160     *
10161     * @return The parent for accessibility purposes.
10162     */
10163    public ViewParent getParentForAccessibility() {
10164        if (mParent instanceof View) {
10165            View parentView = (View) mParent;
10166            if (parentView.includeForAccessibility()) {
10167                return mParent;
10168            } else {
10169                return mParent.getParentForAccessibility();
10170            }
10171        }
10172        return null;
10173    }
10174
10175    /**
10176     * Adds the children of this View relevant for accessibility to the given list
10177     * as output. Since some Views are not important for accessibility the added
10178     * child views are not necessarily direct children of this view, rather they are
10179     * the first level of descendants important for accessibility.
10180     *
10181     * @param outChildren The output list that will receive children for accessibility.
10182     */
10183    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
10184
10185    }
10186
10187    /**
10188     * Whether to regard this view for accessibility. A view is regarded for
10189     * accessibility if it is important for accessibility or the querying
10190     * accessibility service has explicitly requested that view not
10191     * important for accessibility are regarded.
10192     *
10193     * @return Whether to regard the view for accessibility.
10194     *
10195     * @hide
10196     */
10197    public boolean includeForAccessibility() {
10198        if (mAttachInfo != null) {
10199            return (mAttachInfo.mAccessibilityFetchFlags
10200                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
10201                    || isImportantForAccessibility();
10202        }
10203        return false;
10204    }
10205
10206    /**
10207     * Returns whether the View is considered actionable from
10208     * accessibility perspective. Such view are important for
10209     * accessibility.
10210     *
10211     * @return True if the view is actionable for accessibility.
10212     *
10213     * @hide
10214     */
10215    public boolean isActionableForAccessibility() {
10216        return (isClickable() || isLongClickable() || isFocusable());
10217    }
10218
10219    /**
10220     * Returns whether the View has registered callbacks which makes it
10221     * important for accessibility.
10222     *
10223     * @return True if the view is actionable for accessibility.
10224     */
10225    private boolean hasListenersForAccessibility() {
10226        ListenerInfo info = getListenerInfo();
10227        return mTouchDelegate != null || info.mOnKeyListener != null
10228                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
10229                || info.mOnHoverListener != null || info.mOnDragListener != null;
10230    }
10231
10232    /**
10233     * Notifies that the accessibility state of this view changed. The change
10234     * is local to this view and does not represent structural changes such
10235     * as children and parent. For example, the view became focusable. The
10236     * notification is at at most once every
10237     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10238     * to avoid unnecessary load to the system. Also once a view has a pending
10239     * notification this method is a NOP until the notification has been sent.
10240     *
10241     * @hide
10242     */
10243    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
10244        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10245            return;
10246        }
10247        if (mSendViewStateChangedAccessibilityEvent == null) {
10248            mSendViewStateChangedAccessibilityEvent =
10249                    new SendViewStateChangedAccessibilityEvent();
10250        }
10251        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
10252    }
10253
10254    /**
10255     * Notifies that the accessibility state of this view changed. The change
10256     * is *not* local to this view and does represent structural changes such
10257     * as children and parent. For example, the view size changed. The
10258     * notification is at at most once every
10259     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10260     * to avoid unnecessary load to the system. Also once a view has a pending
10261     * notification this method is a NOP until the notification has been sent.
10262     *
10263     * @hide
10264     */
10265    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
10266        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10267            return;
10268        }
10269        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
10270            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10271            if (mParent != null) {
10272                try {
10273                    mParent.notifySubtreeAccessibilityStateChanged(
10274                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
10275                } catch (AbstractMethodError e) {
10276                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10277                            " does not fully implement ViewParent", e);
10278                }
10279            }
10280        }
10281    }
10282
10283    /**
10284     * Change the visibility of the View without triggering any other changes. This is
10285     * important for transitions, where visibility changes should not adjust focus or
10286     * trigger a new layout. This is only used when the visibility has already been changed
10287     * and we need a transient value during an animation. When the animation completes,
10288     * the original visibility value is always restored.
10289     *
10290     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
10291     * @hide
10292     */
10293    public void setTransitionVisibility(@Visibility int visibility) {
10294        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
10295    }
10296
10297    /**
10298     * Reset the flag indicating the accessibility state of the subtree rooted
10299     * at this view changed.
10300     */
10301    void resetSubtreeAccessibilityStateChanged() {
10302        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10303    }
10304
10305    /**
10306     * Report an accessibility action to this view's parents for delegated processing.
10307     *
10308     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
10309     * call this method to delegate an accessibility action to a supporting parent. If the parent
10310     * returns true from its
10311     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
10312     * method this method will return true to signify that the action was consumed.</p>
10313     *
10314     * <p>This method is useful for implementing nested scrolling child views. If
10315     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
10316     * a custom view implementation may invoke this method to allow a parent to consume the
10317     * scroll first. If this method returns true the custom view should skip its own scrolling
10318     * behavior.</p>
10319     *
10320     * @param action Accessibility action to delegate
10321     * @param arguments Optional action arguments
10322     * @return true if the action was consumed by a parent
10323     */
10324    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
10325        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
10326            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
10327                return true;
10328            }
10329        }
10330        return false;
10331    }
10332
10333    /**
10334     * Performs the specified accessibility action on the view. For
10335     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
10336     * <p>
10337     * If an {@link AccessibilityDelegate} has been specified via calling
10338     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
10339     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
10340     * is responsible for handling this call.
10341     * </p>
10342     *
10343     * <p>The default implementation will delegate
10344     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
10345     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
10346     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
10347     *
10348     * @param action The action to perform.
10349     * @param arguments Optional action arguments.
10350     * @return Whether the action was performed.
10351     */
10352    public boolean performAccessibilityAction(int action, Bundle arguments) {
10353      if (mAccessibilityDelegate != null) {
10354          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
10355      } else {
10356          return performAccessibilityActionInternal(action, arguments);
10357      }
10358    }
10359
10360   /**
10361    * @see #performAccessibilityAction(int, Bundle)
10362    *
10363    * Note: Called from the default {@link AccessibilityDelegate}.
10364    *
10365    * @hide
10366    */
10367    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
10368        if (isNestedScrollingEnabled()
10369                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
10370                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
10371                || action == R.id.accessibilityActionScrollUp
10372                || action == R.id.accessibilityActionScrollLeft
10373                || action == R.id.accessibilityActionScrollDown
10374                || action == R.id.accessibilityActionScrollRight)) {
10375            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
10376                return true;
10377            }
10378        }
10379
10380        switch (action) {
10381            case AccessibilityNodeInfo.ACTION_CLICK: {
10382                if (isClickable()) {
10383                    performClick();
10384                    return true;
10385                }
10386            } break;
10387            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
10388                if (isLongClickable()) {
10389                    performLongClick();
10390                    return true;
10391                }
10392            } break;
10393            case AccessibilityNodeInfo.ACTION_FOCUS: {
10394                if (!hasFocus()) {
10395                    // Get out of touch mode since accessibility
10396                    // wants to move focus around.
10397                    getViewRootImpl().ensureTouchMode(false);
10398                    return requestFocus();
10399                }
10400            } break;
10401            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
10402                if (hasFocus()) {
10403                    clearFocus();
10404                    return !isFocused();
10405                }
10406            } break;
10407            case AccessibilityNodeInfo.ACTION_SELECT: {
10408                if (!isSelected()) {
10409                    setSelected(true);
10410                    return isSelected();
10411                }
10412            } break;
10413            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
10414                if (isSelected()) {
10415                    setSelected(false);
10416                    return !isSelected();
10417                }
10418            } break;
10419            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
10420                if (!isAccessibilityFocused()) {
10421                    return requestAccessibilityFocus();
10422                }
10423            } break;
10424            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
10425                if (isAccessibilityFocused()) {
10426                    clearAccessibilityFocus();
10427                    return true;
10428                }
10429            } break;
10430            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
10431                if (arguments != null) {
10432                    final int granularity = arguments.getInt(
10433                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10434                    final boolean extendSelection = arguments.getBoolean(
10435                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10436                    return traverseAtGranularity(granularity, true, extendSelection);
10437                }
10438            } break;
10439            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
10440                if (arguments != null) {
10441                    final int granularity = arguments.getInt(
10442                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10443                    final boolean extendSelection = arguments.getBoolean(
10444                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10445                    return traverseAtGranularity(granularity, false, extendSelection);
10446                }
10447            } break;
10448            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
10449                CharSequence text = getIterableTextForAccessibility();
10450                if (text == null) {
10451                    return false;
10452                }
10453                final int start = (arguments != null) ? arguments.getInt(
10454                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
10455                final int end = (arguments != null) ? arguments.getInt(
10456                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
10457                // Only cursor position can be specified (selection length == 0)
10458                if ((getAccessibilitySelectionStart() != start
10459                        || getAccessibilitySelectionEnd() != end)
10460                        && (start == end)) {
10461                    setAccessibilitySelection(start, end);
10462                    notifyViewAccessibilityStateChangedIfNeeded(
10463                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10464                    return true;
10465                }
10466            } break;
10467            case R.id.accessibilityActionShowOnScreen: {
10468                if (mAttachInfo != null) {
10469                    final Rect r = mAttachInfo.mTmpInvalRect;
10470                    getDrawingRect(r);
10471                    return requestRectangleOnScreen(r, true);
10472                }
10473            } break;
10474            case R.id.accessibilityActionContextClick: {
10475                if (isContextClickable()) {
10476                    performContextClick();
10477                    return true;
10478                }
10479            } break;
10480        }
10481        return false;
10482    }
10483
10484    private boolean traverseAtGranularity(int granularity, boolean forward,
10485            boolean extendSelection) {
10486        CharSequence text = getIterableTextForAccessibility();
10487        if (text == null || text.length() == 0) {
10488            return false;
10489        }
10490        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
10491        if (iterator == null) {
10492            return false;
10493        }
10494        int current = getAccessibilitySelectionEnd();
10495        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10496            current = forward ? 0 : text.length();
10497        }
10498        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
10499        if (range == null) {
10500            return false;
10501        }
10502        final int segmentStart = range[0];
10503        final int segmentEnd = range[1];
10504        int selectionStart;
10505        int selectionEnd;
10506        if (extendSelection && isAccessibilitySelectionExtendable()) {
10507            selectionStart = getAccessibilitySelectionStart();
10508            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10509                selectionStart = forward ? segmentStart : segmentEnd;
10510            }
10511            selectionEnd = forward ? segmentEnd : segmentStart;
10512        } else {
10513            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
10514        }
10515        setAccessibilitySelection(selectionStart, selectionEnd);
10516        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
10517                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
10518        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
10519        return true;
10520    }
10521
10522    /**
10523     * Gets the text reported for accessibility purposes.
10524     *
10525     * @return The accessibility text.
10526     *
10527     * @hide
10528     */
10529    public CharSequence getIterableTextForAccessibility() {
10530        return getContentDescription();
10531    }
10532
10533    /**
10534     * Gets whether accessibility selection can be extended.
10535     *
10536     * @return If selection is extensible.
10537     *
10538     * @hide
10539     */
10540    public boolean isAccessibilitySelectionExtendable() {
10541        return false;
10542    }
10543
10544    /**
10545     * @hide
10546     */
10547    public int getAccessibilitySelectionStart() {
10548        return mAccessibilityCursorPosition;
10549    }
10550
10551    /**
10552     * @hide
10553     */
10554    public int getAccessibilitySelectionEnd() {
10555        return getAccessibilitySelectionStart();
10556    }
10557
10558    /**
10559     * @hide
10560     */
10561    public void setAccessibilitySelection(int start, int end) {
10562        if (start ==  end && end == mAccessibilityCursorPosition) {
10563            return;
10564        }
10565        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
10566            mAccessibilityCursorPosition = start;
10567        } else {
10568            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
10569        }
10570        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
10571    }
10572
10573    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
10574            int fromIndex, int toIndex) {
10575        if (mParent == null) {
10576            return;
10577        }
10578        AccessibilityEvent event = AccessibilityEvent.obtain(
10579                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
10580        onInitializeAccessibilityEvent(event);
10581        onPopulateAccessibilityEvent(event);
10582        event.setFromIndex(fromIndex);
10583        event.setToIndex(toIndex);
10584        event.setAction(action);
10585        event.setMovementGranularity(granularity);
10586        mParent.requestSendAccessibilityEvent(this, event);
10587    }
10588
10589    /**
10590     * @hide
10591     */
10592    public TextSegmentIterator getIteratorForGranularity(int granularity) {
10593        switch (granularity) {
10594            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
10595                CharSequence text = getIterableTextForAccessibility();
10596                if (text != null && text.length() > 0) {
10597                    CharacterTextSegmentIterator iterator =
10598                        CharacterTextSegmentIterator.getInstance(
10599                                mContext.getResources().getConfiguration().locale);
10600                    iterator.initialize(text.toString());
10601                    return iterator;
10602                }
10603            } break;
10604            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
10605                CharSequence text = getIterableTextForAccessibility();
10606                if (text != null && text.length() > 0) {
10607                    WordTextSegmentIterator iterator =
10608                        WordTextSegmentIterator.getInstance(
10609                                mContext.getResources().getConfiguration().locale);
10610                    iterator.initialize(text.toString());
10611                    return iterator;
10612                }
10613            } break;
10614            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
10615                CharSequence text = getIterableTextForAccessibility();
10616                if (text != null && text.length() > 0) {
10617                    ParagraphTextSegmentIterator iterator =
10618                        ParagraphTextSegmentIterator.getInstance();
10619                    iterator.initialize(text.toString());
10620                    return iterator;
10621                }
10622            } break;
10623        }
10624        return null;
10625    }
10626
10627    /**
10628     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
10629     * and {@link #onFinishTemporaryDetach()}.
10630     *
10631     * <p>This method always returns {@code true} when called directly or indirectly from
10632     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
10633     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
10634     * <ul>
10635     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
10636     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
10637     * </ul>
10638     * </p>
10639     *
10640     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
10641     * and {@link #onFinishTemporaryDetach()}.
10642     */
10643    public final boolean isTemporarilyDetached() {
10644        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
10645    }
10646
10647    /**
10648     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
10649     * a container View.
10650     */
10651    @CallSuper
10652    public void dispatchStartTemporaryDetach() {
10653        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
10654        onStartTemporaryDetach();
10655    }
10656
10657    /**
10658     * This is called when a container is going to temporarily detach a child, with
10659     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
10660     * It will either be followed by {@link #onFinishTemporaryDetach()} or
10661     * {@link #onDetachedFromWindow()} when the container is done.
10662     */
10663    public void onStartTemporaryDetach() {
10664        removeUnsetPressCallback();
10665        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
10666    }
10667
10668    /**
10669     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
10670     * a container View.
10671     */
10672    @CallSuper
10673    public void dispatchFinishTemporaryDetach() {
10674        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
10675        onFinishTemporaryDetach();
10676        if (hasWindowFocus() && hasFocus()) {
10677            InputMethodManager.getInstance().focusIn(this);
10678        }
10679    }
10680
10681    /**
10682     * Called after {@link #onStartTemporaryDetach} when the container is done
10683     * changing the view.
10684     */
10685    public void onFinishTemporaryDetach() {
10686    }
10687
10688    /**
10689     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
10690     * for this view's window.  Returns null if the view is not currently attached
10691     * to the window.  Normally you will not need to use this directly, but
10692     * just use the standard high-level event callbacks like
10693     * {@link #onKeyDown(int, KeyEvent)}.
10694     */
10695    public KeyEvent.DispatcherState getKeyDispatcherState() {
10696        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
10697    }
10698
10699    /**
10700     * Dispatch a key event before it is processed by any input method
10701     * associated with the view hierarchy.  This can be used to intercept
10702     * key events in special situations before the IME consumes them; a
10703     * typical example would be handling the BACK key to update the application's
10704     * UI instead of allowing the IME to see it and close itself.
10705     *
10706     * @param event The key event to be dispatched.
10707     * @return True if the event was handled, false otherwise.
10708     */
10709    public boolean dispatchKeyEventPreIme(KeyEvent event) {
10710        return onKeyPreIme(event.getKeyCode(), event);
10711    }
10712
10713    /**
10714     * Dispatch a key event to the next view on the focus path. This path runs
10715     * from the top of the view tree down to the currently focused view. If this
10716     * view has focus, it will dispatch to itself. Otherwise it will dispatch
10717     * the next node down the focus path. This method also fires any key
10718     * listeners.
10719     *
10720     * @param event The key event to be dispatched.
10721     * @return True if the event was handled, false otherwise.
10722     */
10723    public boolean dispatchKeyEvent(KeyEvent event) {
10724        if (mInputEventConsistencyVerifier != null) {
10725            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
10726        }
10727
10728        // Give any attached key listener a first crack at the event.
10729        //noinspection SimplifiableIfStatement
10730        ListenerInfo li = mListenerInfo;
10731        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10732                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
10733            return true;
10734        }
10735
10736        if (event.dispatch(this, mAttachInfo != null
10737                ? mAttachInfo.mKeyDispatchState : null, this)) {
10738            return true;
10739        }
10740
10741        if (mInputEventConsistencyVerifier != null) {
10742            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10743        }
10744        return false;
10745    }
10746
10747    /**
10748     * Dispatches a key shortcut event.
10749     *
10750     * @param event The key event to be dispatched.
10751     * @return True if the event was handled by the view, false otherwise.
10752     */
10753    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
10754        return onKeyShortcut(event.getKeyCode(), event);
10755    }
10756
10757    /**
10758     * Pass the touch screen motion event down to the target view, or this
10759     * view if it is the target.
10760     *
10761     * @param event The motion event to be dispatched.
10762     * @return True if the event was handled by the view, false otherwise.
10763     */
10764    public boolean dispatchTouchEvent(MotionEvent event) {
10765        // If the event should be handled by accessibility focus first.
10766        if (event.isTargetAccessibilityFocus()) {
10767            // We don't have focus or no virtual descendant has it, do not handle the event.
10768            if (!isAccessibilityFocusedViewOrHost()) {
10769                return false;
10770            }
10771            // We have focus and got the event, then use normal event dispatch.
10772            event.setTargetAccessibilityFocus(false);
10773        }
10774
10775        boolean result = false;
10776
10777        if (mInputEventConsistencyVerifier != null) {
10778            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
10779        }
10780
10781        final int actionMasked = event.getActionMasked();
10782        if (actionMasked == MotionEvent.ACTION_DOWN) {
10783            // Defensive cleanup for new gesture
10784            stopNestedScroll();
10785        }
10786
10787        if (onFilterTouchEventForSecurity(event)) {
10788            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10789                result = true;
10790            }
10791            //noinspection SimplifiableIfStatement
10792            ListenerInfo li = mListenerInfo;
10793            if (li != null && li.mOnTouchListener != null
10794                    && (mViewFlags & ENABLED_MASK) == ENABLED
10795                    && li.mOnTouchListener.onTouch(this, event)) {
10796                result = true;
10797            }
10798
10799            if (!result && onTouchEvent(event)) {
10800                result = true;
10801            }
10802        }
10803
10804        if (!result && mInputEventConsistencyVerifier != null) {
10805            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10806        }
10807
10808        // Clean up after nested scrolls if this is the end of a gesture;
10809        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10810        // of the gesture.
10811        if (actionMasked == MotionEvent.ACTION_UP ||
10812                actionMasked == MotionEvent.ACTION_CANCEL ||
10813                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10814            stopNestedScroll();
10815        }
10816
10817        return result;
10818    }
10819
10820    boolean isAccessibilityFocusedViewOrHost() {
10821        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10822                .getAccessibilityFocusedHost() == this);
10823    }
10824
10825    /**
10826     * Filter the touch event to apply security policies.
10827     *
10828     * @param event The motion event to be filtered.
10829     * @return True if the event should be dispatched, false if the event should be dropped.
10830     *
10831     * @see #getFilterTouchesWhenObscured
10832     */
10833    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10834        //noinspection RedundantIfStatement
10835        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10836                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10837            // Window is obscured, drop this touch.
10838            return false;
10839        }
10840        return true;
10841    }
10842
10843    /**
10844     * Pass a trackball motion event down to the focused view.
10845     *
10846     * @param event The motion event to be dispatched.
10847     * @return True if the event was handled by the view, false otherwise.
10848     */
10849    public boolean dispatchTrackballEvent(MotionEvent event) {
10850        if (mInputEventConsistencyVerifier != null) {
10851            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10852        }
10853
10854        return onTrackballEvent(event);
10855    }
10856
10857    /**
10858     * Pass a captured pointer event down to the focused view.
10859     *
10860     * @param event The motion event to be dispatched.
10861     * @return True if the event was handled by the view, false otherwise.
10862     */
10863    public boolean dispatchCapturedPointerEvent(MotionEvent event) {
10864        if (!hasPointerCapture()) {
10865            return false;
10866        }
10867        //noinspection SimplifiableIfStatement
10868        ListenerInfo li = mListenerInfo;
10869        if (li != null && li.mOnCapturedPointerListener != null
10870                && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
10871            return true;
10872        }
10873        return onCapturedPointerEvent(event);
10874    }
10875
10876    /**
10877     * Dispatch a generic motion event.
10878     * <p>
10879     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10880     * are delivered to the view under the pointer.  All other generic motion events are
10881     * delivered to the focused view.  Hover events are handled specially and are delivered
10882     * to {@link #onHoverEvent(MotionEvent)}.
10883     * </p>
10884     *
10885     * @param event The motion event to be dispatched.
10886     * @return True if the event was handled by the view, false otherwise.
10887     */
10888    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10889        if (mInputEventConsistencyVerifier != null) {
10890            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10891        }
10892
10893        final int source = event.getSource();
10894        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10895            final int action = event.getAction();
10896            if (action == MotionEvent.ACTION_HOVER_ENTER
10897                    || action == MotionEvent.ACTION_HOVER_MOVE
10898                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10899                if (dispatchHoverEvent(event)) {
10900                    return true;
10901                }
10902            } else if (dispatchGenericPointerEvent(event)) {
10903                return true;
10904            }
10905        } else if (dispatchGenericFocusedEvent(event)) {
10906            return true;
10907        }
10908
10909        if (dispatchGenericMotionEventInternal(event)) {
10910            return true;
10911        }
10912
10913        if (mInputEventConsistencyVerifier != null) {
10914            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10915        }
10916        return false;
10917    }
10918
10919    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10920        //noinspection SimplifiableIfStatement
10921        ListenerInfo li = mListenerInfo;
10922        if (li != null && li.mOnGenericMotionListener != null
10923                && (mViewFlags & ENABLED_MASK) == ENABLED
10924                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10925            return true;
10926        }
10927
10928        if (onGenericMotionEvent(event)) {
10929            return true;
10930        }
10931
10932        final int actionButton = event.getActionButton();
10933        switch (event.getActionMasked()) {
10934            case MotionEvent.ACTION_BUTTON_PRESS:
10935                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10936                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10937                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10938                    if (performContextClick(event.getX(), event.getY())) {
10939                        mInContextButtonPress = true;
10940                        setPressed(true, event.getX(), event.getY());
10941                        removeTapCallback();
10942                        removeLongPressCallback();
10943                        return true;
10944                    }
10945                }
10946                break;
10947
10948            case MotionEvent.ACTION_BUTTON_RELEASE:
10949                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10950                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10951                    mInContextButtonPress = false;
10952                    mIgnoreNextUpEvent = true;
10953                }
10954                break;
10955        }
10956
10957        if (mInputEventConsistencyVerifier != null) {
10958            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10959        }
10960        return false;
10961    }
10962
10963    /**
10964     * Dispatch a hover event.
10965     * <p>
10966     * Do not call this method directly.
10967     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10968     * </p>
10969     *
10970     * @param event The motion event to be dispatched.
10971     * @return True if the event was handled by the view, false otherwise.
10972     */
10973    protected boolean dispatchHoverEvent(MotionEvent event) {
10974        ListenerInfo li = mListenerInfo;
10975        //noinspection SimplifiableIfStatement
10976        if (li != null && li.mOnHoverListener != null
10977                && (mViewFlags & ENABLED_MASK) == ENABLED
10978                && li.mOnHoverListener.onHover(this, event)) {
10979            return true;
10980        }
10981
10982        return onHoverEvent(event);
10983    }
10984
10985    /**
10986     * Returns true if the view has a child to which it has recently sent
10987     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10988     * it does not have a hovered child, then it must be the innermost hovered view.
10989     * @hide
10990     */
10991    protected boolean hasHoveredChild() {
10992        return false;
10993    }
10994
10995    /**
10996     * Dispatch a generic motion event to the view under the first pointer.
10997     * <p>
10998     * Do not call this method directly.
10999     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11000     * </p>
11001     *
11002     * @param event The motion event to be dispatched.
11003     * @return True if the event was handled by the view, false otherwise.
11004     */
11005    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
11006        return false;
11007    }
11008
11009    /**
11010     * Dispatch a generic motion event to the currently focused view.
11011     * <p>
11012     * Do not call this method directly.
11013     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11014     * </p>
11015     *
11016     * @param event The motion event to be dispatched.
11017     * @return True if the event was handled by the view, false otherwise.
11018     */
11019    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
11020        return false;
11021    }
11022
11023    /**
11024     * Dispatch a pointer event.
11025     * <p>
11026     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
11027     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
11028     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
11029     * and should not be expected to handle other pointing device features.
11030     * </p>
11031     *
11032     * @param event The motion event to be dispatched.
11033     * @return True if the event was handled by the view, false otherwise.
11034     * @hide
11035     */
11036    public final boolean dispatchPointerEvent(MotionEvent event) {
11037        if (event.isTouchEvent()) {
11038            return dispatchTouchEvent(event);
11039        } else {
11040            return dispatchGenericMotionEvent(event);
11041        }
11042    }
11043
11044    /**
11045     * Called when the window containing this view gains or loses window focus.
11046     * ViewGroups should override to route to their children.
11047     *
11048     * @param hasFocus True if the window containing this view now has focus,
11049     *        false otherwise.
11050     */
11051    public void dispatchWindowFocusChanged(boolean hasFocus) {
11052        onWindowFocusChanged(hasFocus);
11053    }
11054
11055    /**
11056     * Called when the window containing this view gains or loses focus.  Note
11057     * that this is separate from view focus: to receive key events, both
11058     * your view and its window must have focus.  If a window is displayed
11059     * on top of yours that takes input focus, then your own window will lose
11060     * focus but the view focus will remain unchanged.
11061     *
11062     * @param hasWindowFocus True if the window containing this view now has
11063     *        focus, false otherwise.
11064     */
11065    public void onWindowFocusChanged(boolean hasWindowFocus) {
11066        InputMethodManager imm = InputMethodManager.peekInstance();
11067        if (!hasWindowFocus) {
11068            if (isPressed()) {
11069                setPressed(false);
11070            }
11071            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11072            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11073                imm.focusOut(this);
11074            }
11075            removeLongPressCallback();
11076            removeTapCallback();
11077            onFocusLost();
11078        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11079            imm.focusIn(this);
11080        }
11081        refreshDrawableState();
11082    }
11083
11084    /**
11085     * Returns true if this view is in a window that currently has window focus.
11086     * Note that this is not the same as the view itself having focus.
11087     *
11088     * @return True if this view is in a window that currently has window focus.
11089     */
11090    public boolean hasWindowFocus() {
11091        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
11092    }
11093
11094    /**
11095     * Dispatch a view visibility change down the view hierarchy.
11096     * ViewGroups should override to route to their children.
11097     * @param changedView The view whose visibility changed. Could be 'this' or
11098     * an ancestor view.
11099     * @param visibility The new visibility of changedView: {@link #VISIBLE},
11100     * {@link #INVISIBLE} or {@link #GONE}.
11101     */
11102    protected void dispatchVisibilityChanged(@NonNull View changedView,
11103            @Visibility int visibility) {
11104        onVisibilityChanged(changedView, visibility);
11105    }
11106
11107    /**
11108     * Called when the visibility of the view or an ancestor of the view has
11109     * changed.
11110     *
11111     * @param changedView The view whose visibility changed. May be
11112     *                    {@code this} or an ancestor view.
11113     * @param visibility The new visibility, one of {@link #VISIBLE},
11114     *                   {@link #INVISIBLE} or {@link #GONE}.
11115     */
11116    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
11117    }
11118
11119    /**
11120     * Dispatch a hint about whether this view is displayed. For instance, when
11121     * a View moves out of the screen, it might receives a display hint indicating
11122     * the view is not displayed. Applications should not <em>rely</em> on this hint
11123     * as there is no guarantee that they will receive one.
11124     *
11125     * @param hint A hint about whether or not this view is displayed:
11126     * {@link #VISIBLE} or {@link #INVISIBLE}.
11127     */
11128    public void dispatchDisplayHint(@Visibility int hint) {
11129        onDisplayHint(hint);
11130    }
11131
11132    /**
11133     * Gives this view a hint about whether is displayed or not. For instance, when
11134     * a View moves out of the screen, it might receives a display hint indicating
11135     * the view is not displayed. Applications should not <em>rely</em> on this hint
11136     * as there is no guarantee that they will receive one.
11137     *
11138     * @param hint A hint about whether or not this view is displayed:
11139     * {@link #VISIBLE} or {@link #INVISIBLE}.
11140     */
11141    protected void onDisplayHint(@Visibility int hint) {
11142    }
11143
11144    /**
11145     * Dispatch a window visibility change down the view hierarchy.
11146     * ViewGroups should override to route to their children.
11147     *
11148     * @param visibility The new visibility of the window.
11149     *
11150     * @see #onWindowVisibilityChanged(int)
11151     */
11152    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
11153        onWindowVisibilityChanged(visibility);
11154    }
11155
11156    /**
11157     * Called when the window containing has change its visibility
11158     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
11159     * that this tells you whether or not your window is being made visible
11160     * to the window manager; this does <em>not</em> tell you whether or not
11161     * your window is obscured by other windows on the screen, even if it
11162     * is itself visible.
11163     *
11164     * @param visibility The new visibility of the window.
11165     */
11166    protected void onWindowVisibilityChanged(@Visibility int visibility) {
11167        if (visibility == VISIBLE) {
11168            initialAwakenScrollBars();
11169        }
11170    }
11171
11172    /**
11173     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
11174     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
11175     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
11176     *
11177     * @param isVisible true if this view's visibility to the user is uninterrupted by its
11178     *                  ancestors or by window visibility
11179     * @return true if this view is visible to the user, not counting clipping or overlapping
11180     */
11181    boolean dispatchVisibilityAggregated(boolean isVisible) {
11182        final boolean thisVisible = getVisibility() == VISIBLE;
11183        // If we're not visible but something is telling us we are, ignore it.
11184        if (thisVisible || !isVisible) {
11185            onVisibilityAggregated(isVisible);
11186        }
11187        return thisVisible && isVisible;
11188    }
11189
11190    /**
11191     * Called when the user-visibility of this View is potentially affected by a change
11192     * to this view itself, an ancestor view or the window this view is attached to.
11193     *
11194     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
11195     *                  and this view's window is also visible
11196     */
11197    @CallSuper
11198    public void onVisibilityAggregated(boolean isVisible) {
11199        if (isVisible && mAttachInfo != null) {
11200            initialAwakenScrollBars();
11201        }
11202
11203        final Drawable dr = mBackground;
11204        if (dr != null && isVisible != dr.isVisible()) {
11205            dr.setVisible(isVisible, false);
11206        }
11207        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
11208        if (fg != null && isVisible != fg.isVisible()) {
11209            fg.setVisible(isVisible, false);
11210        }
11211    }
11212
11213    /**
11214     * Returns the current visibility of the window this view is attached to
11215     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
11216     *
11217     * @return Returns the current visibility of the view's window.
11218     */
11219    @Visibility
11220    public int getWindowVisibility() {
11221        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
11222    }
11223
11224    /**
11225     * Retrieve the overall visible display size in which the window this view is
11226     * attached to has been positioned in.  This takes into account screen
11227     * decorations above the window, for both cases where the window itself
11228     * is being position inside of them or the window is being placed under
11229     * then and covered insets are used for the window to position its content
11230     * inside.  In effect, this tells you the available area where content can
11231     * be placed and remain visible to users.
11232     *
11233     * <p>This function requires an IPC back to the window manager to retrieve
11234     * the requested information, so should not be used in performance critical
11235     * code like drawing.
11236     *
11237     * @param outRect Filled in with the visible display frame.  If the view
11238     * is not attached to a window, this is simply the raw display size.
11239     */
11240    public void getWindowVisibleDisplayFrame(Rect outRect) {
11241        if (mAttachInfo != null) {
11242            try {
11243                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11244            } catch (RemoteException e) {
11245                return;
11246            }
11247            // XXX This is really broken, and probably all needs to be done
11248            // in the window manager, and we need to know more about whether
11249            // we want the area behind or in front of the IME.
11250            final Rect insets = mAttachInfo.mVisibleInsets;
11251            outRect.left += insets.left;
11252            outRect.top += insets.top;
11253            outRect.right -= insets.right;
11254            outRect.bottom -= insets.bottom;
11255            return;
11256        }
11257        // The view is not attached to a display so we don't have a context.
11258        // Make a best guess about the display size.
11259        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11260        d.getRectSize(outRect);
11261    }
11262
11263    /**
11264     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
11265     * is currently in without any insets.
11266     *
11267     * @hide
11268     */
11269    public void getWindowDisplayFrame(Rect outRect) {
11270        if (mAttachInfo != null) {
11271            try {
11272                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11273            } catch (RemoteException e) {
11274                return;
11275            }
11276            return;
11277        }
11278        // The view is not attached to a display so we don't have a context.
11279        // Make a best guess about the display size.
11280        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11281        d.getRectSize(outRect);
11282    }
11283
11284    /**
11285     * Dispatch a notification about a resource configuration change down
11286     * the view hierarchy.
11287     * ViewGroups should override to route to their children.
11288     *
11289     * @param newConfig The new resource configuration.
11290     *
11291     * @see #onConfigurationChanged(android.content.res.Configuration)
11292     */
11293    public void dispatchConfigurationChanged(Configuration newConfig) {
11294        onConfigurationChanged(newConfig);
11295    }
11296
11297    /**
11298     * Called when the current configuration of the resources being used
11299     * by the application have changed.  You can use this to decide when
11300     * to reload resources that can changed based on orientation and other
11301     * configuration characteristics.  You only need to use this if you are
11302     * not relying on the normal {@link android.app.Activity} mechanism of
11303     * recreating the activity instance upon a configuration change.
11304     *
11305     * @param newConfig The new resource configuration.
11306     */
11307    protected void onConfigurationChanged(Configuration newConfig) {
11308    }
11309
11310    /**
11311     * Private function to aggregate all per-view attributes in to the view
11312     * root.
11313     */
11314    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11315        performCollectViewAttributes(attachInfo, visibility);
11316    }
11317
11318    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11319        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
11320            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
11321                attachInfo.mKeepScreenOn = true;
11322            }
11323            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
11324            ListenerInfo li = mListenerInfo;
11325            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
11326                attachInfo.mHasSystemUiListeners = true;
11327            }
11328        }
11329    }
11330
11331    void needGlobalAttributesUpdate(boolean force) {
11332        final AttachInfo ai = mAttachInfo;
11333        if (ai != null && !ai.mRecomputeGlobalAttributes) {
11334            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
11335                    || ai.mHasSystemUiListeners) {
11336                ai.mRecomputeGlobalAttributes = true;
11337            }
11338        }
11339    }
11340
11341    /**
11342     * Returns whether the device is currently in touch mode.  Touch mode is entered
11343     * once the user begins interacting with the device by touch, and affects various
11344     * things like whether focus is always visible to the user.
11345     *
11346     * @return Whether the device is in touch mode.
11347     */
11348    @ViewDebug.ExportedProperty
11349    public boolean isInTouchMode() {
11350        if (mAttachInfo != null) {
11351            return mAttachInfo.mInTouchMode;
11352        } else {
11353            return ViewRootImpl.isInTouchMode();
11354        }
11355    }
11356
11357    /**
11358     * Returns the context the view is running in, through which it can
11359     * access the current theme, resources, etc.
11360     *
11361     * @return The view's Context.
11362     */
11363    @ViewDebug.CapturedViewProperty
11364    public final Context getContext() {
11365        return mContext;
11366    }
11367
11368    /**
11369     * Handle a key event before it is processed by any input method
11370     * associated with the view hierarchy.  This can be used to intercept
11371     * key events in special situations before the IME consumes them; a
11372     * typical example would be handling the BACK key to update the application's
11373     * UI instead of allowing the IME to see it and close itself.
11374     *
11375     * @param keyCode The value in event.getKeyCode().
11376     * @param event Description of the key event.
11377     * @return If you handled the event, return true. If you want to allow the
11378     *         event to be handled by the next receiver, return false.
11379     */
11380    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
11381        return false;
11382    }
11383
11384    /**
11385     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
11386     * KeyEvent.Callback.onKeyDown()}: perform press of the view
11387     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
11388     * is released, if the view is enabled and clickable.
11389     * <p>
11390     * Key presses in software keyboards will generally NOT trigger this
11391     * listener, although some may elect to do so in some situations. Do not
11392     * rely on this to catch software key presses.
11393     *
11394     * @param keyCode a key code that represents the button pressed, from
11395     *                {@link android.view.KeyEvent}
11396     * @param event the KeyEvent object that defines the button action
11397     */
11398    public boolean onKeyDown(int keyCode, KeyEvent event) {
11399        if (KeyEvent.isConfirmKey(keyCode)) {
11400            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11401                return true;
11402            }
11403
11404            if (event.getRepeatCount() == 0) {
11405                // Long clickable items don't necessarily have to be clickable.
11406                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
11407                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
11408                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
11409                    // For the purposes of menu anchoring and drawable hotspots,
11410                    // key events are considered to be at the center of the view.
11411                    final float x = getWidth() / 2f;
11412                    final float y = getHeight() / 2f;
11413                    if (clickable) {
11414                        setPressed(true, x, y);
11415                    }
11416                    checkForLongClick(0, x, y);
11417                    return true;
11418                }
11419            }
11420        }
11421
11422        return false;
11423    }
11424
11425    /**
11426     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
11427     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
11428     * the event).
11429     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11430     * although some may elect to do so in some situations. Do not rely on this to
11431     * catch software key presses.
11432     */
11433    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
11434        return false;
11435    }
11436
11437    /**
11438     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
11439     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
11440     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
11441     * or {@link KeyEvent#KEYCODE_SPACE} is released.
11442     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11443     * although some may elect to do so in some situations. Do not rely on this to
11444     * catch software key presses.
11445     *
11446     * @param keyCode A key code that represents the button pressed, from
11447     *                {@link android.view.KeyEvent}.
11448     * @param event   The KeyEvent object that defines the button action.
11449     */
11450    public boolean onKeyUp(int keyCode, KeyEvent event) {
11451        if (KeyEvent.isConfirmKey(keyCode)) {
11452            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11453                return true;
11454            }
11455            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
11456                setPressed(false);
11457
11458                if (!mHasPerformedLongPress) {
11459                    // This is a tap, so remove the longpress check
11460                    removeLongPressCallback();
11461                    return performClick();
11462                }
11463            }
11464        }
11465        return false;
11466    }
11467
11468    /**
11469     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
11470     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
11471     * the event).
11472     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11473     * although some may elect to do so in some situations. Do not rely on this to
11474     * catch software key presses.
11475     *
11476     * @param keyCode     A key code that represents the button pressed, from
11477     *                    {@link android.view.KeyEvent}.
11478     * @param repeatCount The number of times the action was made.
11479     * @param event       The KeyEvent object that defines the button action.
11480     */
11481    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
11482        return false;
11483    }
11484
11485    /**
11486     * Called on the focused view when a key shortcut event is not handled.
11487     * Override this method to implement local key shortcuts for the View.
11488     * Key shortcuts can also be implemented by setting the
11489     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
11490     *
11491     * @param keyCode The value in event.getKeyCode().
11492     * @param event Description of the key event.
11493     * @return If you handled the event, return true. If you want to allow the
11494     *         event to be handled by the next receiver, return false.
11495     */
11496    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
11497        return false;
11498    }
11499
11500    /**
11501     * Check whether the called view is a text editor, in which case it
11502     * would make sense to automatically display a soft input window for
11503     * it.  Subclasses should override this if they implement
11504     * {@link #onCreateInputConnection(EditorInfo)} to return true if
11505     * a call on that method would return a non-null InputConnection, and
11506     * they are really a first-class editor that the user would normally
11507     * start typing on when the go into a window containing your view.
11508     *
11509     * <p>The default implementation always returns false.  This does
11510     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
11511     * will not be called or the user can not otherwise perform edits on your
11512     * view; it is just a hint to the system that this is not the primary
11513     * purpose of this view.
11514     *
11515     * @return Returns true if this view is a text editor, else false.
11516     */
11517    public boolean onCheckIsTextEditor() {
11518        return false;
11519    }
11520
11521    /**
11522     * Create a new InputConnection for an InputMethod to interact
11523     * with the view.  The default implementation returns null, since it doesn't
11524     * support input methods.  You can override this to implement such support.
11525     * This is only needed for views that take focus and text input.
11526     *
11527     * <p>When implementing this, you probably also want to implement
11528     * {@link #onCheckIsTextEditor()} to indicate you will return a
11529     * non-null InputConnection.</p>
11530     *
11531     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
11532     * object correctly and in its entirety, so that the connected IME can rely
11533     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
11534     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
11535     * must be filled in with the correct cursor position for IMEs to work correctly
11536     * with your application.</p>
11537     *
11538     * @param outAttrs Fill in with attribute information about the connection.
11539     */
11540    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
11541        return null;
11542    }
11543
11544    /**
11545     * Called by the {@link android.view.inputmethod.InputMethodManager}
11546     * when a view who is not the current
11547     * input connection target is trying to make a call on the manager.  The
11548     * default implementation returns false; you can override this to return
11549     * true for certain views if you are performing InputConnection proxying
11550     * to them.
11551     * @param view The View that is making the InputMethodManager call.
11552     * @return Return true to allow the call, false to reject.
11553     */
11554    public boolean checkInputConnectionProxy(View view) {
11555        return false;
11556    }
11557
11558    /**
11559     * Show the context menu for this view. It is not safe to hold on to the
11560     * menu after returning from this method.
11561     *
11562     * You should normally not overload this method. Overload
11563     * {@link #onCreateContextMenu(ContextMenu)} or define an
11564     * {@link OnCreateContextMenuListener} to add items to the context menu.
11565     *
11566     * @param menu The context menu to populate
11567     */
11568    public void createContextMenu(ContextMenu menu) {
11569        ContextMenuInfo menuInfo = getContextMenuInfo();
11570
11571        // Sets the current menu info so all items added to menu will have
11572        // my extra info set.
11573        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
11574
11575        onCreateContextMenu(menu);
11576        ListenerInfo li = mListenerInfo;
11577        if (li != null && li.mOnCreateContextMenuListener != null) {
11578            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
11579        }
11580
11581        // Clear the extra information so subsequent items that aren't mine don't
11582        // have my extra info.
11583        ((MenuBuilder)menu).setCurrentMenuInfo(null);
11584
11585        if (mParent != null) {
11586            mParent.createContextMenu(menu);
11587        }
11588    }
11589
11590    /**
11591     * Views should implement this if they have extra information to associate
11592     * with the context menu. The return result is supplied as a parameter to
11593     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
11594     * callback.
11595     *
11596     * @return Extra information about the item for which the context menu
11597     *         should be shown. This information will vary across different
11598     *         subclasses of View.
11599     */
11600    protected ContextMenuInfo getContextMenuInfo() {
11601        return null;
11602    }
11603
11604    /**
11605     * Views should implement this if the view itself is going to add items to
11606     * the context menu.
11607     *
11608     * @param menu the context menu to populate
11609     */
11610    protected void onCreateContextMenu(ContextMenu menu) {
11611    }
11612
11613    /**
11614     * Implement this method to handle trackball motion events.  The
11615     * <em>relative</em> movement of the trackball since the last event
11616     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
11617     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
11618     * that a movement of 1 corresponds to the user pressing one DPAD key (so
11619     * they will often be fractional values, representing the more fine-grained
11620     * movement information available from a trackball).
11621     *
11622     * @param event The motion event.
11623     * @return True if the event was handled, false otherwise.
11624     */
11625    public boolean onTrackballEvent(MotionEvent event) {
11626        return false;
11627    }
11628
11629    /**
11630     * Implement this method to handle generic motion events.
11631     * <p>
11632     * Generic motion events describe joystick movements, mouse hovers, track pad
11633     * touches, scroll wheel movements and other input events.  The
11634     * {@link MotionEvent#getSource() source} of the motion event specifies
11635     * the class of input that was received.  Implementations of this method
11636     * must examine the bits in the source before processing the event.
11637     * The following code example shows how this is done.
11638     * </p><p>
11639     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11640     * are delivered to the view under the pointer.  All other generic motion events are
11641     * delivered to the focused view.
11642     * </p>
11643     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
11644     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
11645     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
11646     *             // process the joystick movement...
11647     *             return true;
11648     *         }
11649     *     }
11650     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
11651     *         switch (event.getAction()) {
11652     *             case MotionEvent.ACTION_HOVER_MOVE:
11653     *                 // process the mouse hover movement...
11654     *                 return true;
11655     *             case MotionEvent.ACTION_SCROLL:
11656     *                 // process the scroll wheel movement...
11657     *                 return true;
11658     *         }
11659     *     }
11660     *     return super.onGenericMotionEvent(event);
11661     * }</pre>
11662     *
11663     * @param event The generic motion event being processed.
11664     * @return True if the event was handled, false otherwise.
11665     */
11666    public boolean onGenericMotionEvent(MotionEvent event) {
11667        return false;
11668    }
11669
11670    /**
11671     * Implement this method to handle hover events.
11672     * <p>
11673     * This method is called whenever a pointer is hovering into, over, or out of the
11674     * bounds of a view and the view is not currently being touched.
11675     * Hover events are represented as pointer events with action
11676     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
11677     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
11678     * </p>
11679     * <ul>
11680     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
11681     * when the pointer enters the bounds of the view.</li>
11682     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
11683     * when the pointer has already entered the bounds of the view and has moved.</li>
11684     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
11685     * when the pointer has exited the bounds of the view or when the pointer is
11686     * about to go down due to a button click, tap, or similar user action that
11687     * causes the view to be touched.</li>
11688     * </ul>
11689     * <p>
11690     * The view should implement this method to return true to indicate that it is
11691     * handling the hover event, such as by changing its drawable state.
11692     * </p><p>
11693     * The default implementation calls {@link #setHovered} to update the hovered state
11694     * of the view when a hover enter or hover exit event is received, if the view
11695     * is enabled and is clickable.  The default implementation also sends hover
11696     * accessibility events.
11697     * </p>
11698     *
11699     * @param event The motion event that describes the hover.
11700     * @return True if the view handled the hover event.
11701     *
11702     * @see #isHovered
11703     * @see #setHovered
11704     * @see #onHoverChanged
11705     */
11706    public boolean onHoverEvent(MotionEvent event) {
11707        // The root view may receive hover (or touch) events that are outside the bounds of
11708        // the window.  This code ensures that we only send accessibility events for
11709        // hovers that are actually within the bounds of the root view.
11710        final int action = event.getActionMasked();
11711        if (!mSendingHoverAccessibilityEvents) {
11712            if ((action == MotionEvent.ACTION_HOVER_ENTER
11713                    || action == MotionEvent.ACTION_HOVER_MOVE)
11714                    && !hasHoveredChild()
11715                    && pointInView(event.getX(), event.getY())) {
11716                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
11717                mSendingHoverAccessibilityEvents = true;
11718            }
11719        } else {
11720            if (action == MotionEvent.ACTION_HOVER_EXIT
11721                    || (action == MotionEvent.ACTION_MOVE
11722                            && !pointInView(event.getX(), event.getY()))) {
11723                mSendingHoverAccessibilityEvents = false;
11724                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
11725            }
11726        }
11727
11728        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
11729                && event.isFromSource(InputDevice.SOURCE_MOUSE)
11730                && isOnScrollbar(event.getX(), event.getY())) {
11731            awakenScrollBars();
11732        }
11733        if (isHoverable()) {
11734            switch (action) {
11735                case MotionEvent.ACTION_HOVER_ENTER:
11736                    setHovered(true);
11737                    break;
11738                case MotionEvent.ACTION_HOVER_EXIT:
11739                    setHovered(false);
11740                    break;
11741            }
11742
11743            // Dispatch the event to onGenericMotionEvent before returning true.
11744            // This is to provide compatibility with existing applications that
11745            // handled HOVER_MOVE events in onGenericMotionEvent and that would
11746            // break because of the new default handling for hoverable views
11747            // in onHoverEvent.
11748            // Note that onGenericMotionEvent will be called by default when
11749            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
11750            dispatchGenericMotionEventInternal(event);
11751            // The event was already handled by calling setHovered(), so always
11752            // return true.
11753            return true;
11754        }
11755
11756        return false;
11757    }
11758
11759    /**
11760     * Returns true if the view should handle {@link #onHoverEvent}
11761     * by calling {@link #setHovered} to change its hovered state.
11762     *
11763     * @return True if the view is hoverable.
11764     */
11765    private boolean isHoverable() {
11766        final int viewFlags = mViewFlags;
11767        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11768            return false;
11769        }
11770
11771        return (viewFlags & CLICKABLE) == CLICKABLE
11772                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
11773                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11774    }
11775
11776    /**
11777     * Returns true if the view is currently hovered.
11778     *
11779     * @return True if the view is currently hovered.
11780     *
11781     * @see #setHovered
11782     * @see #onHoverChanged
11783     */
11784    @ViewDebug.ExportedProperty
11785    public boolean isHovered() {
11786        return (mPrivateFlags & PFLAG_HOVERED) != 0;
11787    }
11788
11789    /**
11790     * Sets whether the view is currently hovered.
11791     * <p>
11792     * Calling this method also changes the drawable state of the view.  This
11793     * enables the view to react to hover by using different drawable resources
11794     * to change its appearance.
11795     * </p><p>
11796     * The {@link #onHoverChanged} method is called when the hovered state changes.
11797     * </p>
11798     *
11799     * @param hovered True if the view is hovered.
11800     *
11801     * @see #isHovered
11802     * @see #onHoverChanged
11803     */
11804    public void setHovered(boolean hovered) {
11805        if (hovered) {
11806            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11807                mPrivateFlags |= PFLAG_HOVERED;
11808                refreshDrawableState();
11809                onHoverChanged(true);
11810            }
11811        } else {
11812            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11813                mPrivateFlags &= ~PFLAG_HOVERED;
11814                refreshDrawableState();
11815                onHoverChanged(false);
11816            }
11817        }
11818    }
11819
11820    /**
11821     * Implement this method to handle hover state changes.
11822     * <p>
11823     * This method is called whenever the hover state changes as a result of a
11824     * call to {@link #setHovered}.
11825     * </p>
11826     *
11827     * @param hovered The current hover state, as returned by {@link #isHovered}.
11828     *
11829     * @see #isHovered
11830     * @see #setHovered
11831     */
11832    public void onHoverChanged(boolean hovered) {
11833    }
11834
11835    /**
11836     * Handles scroll bar dragging by mouse input.
11837     *
11838     * @hide
11839     * @param event The motion event.
11840     *
11841     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11842     */
11843    protected boolean handleScrollBarDragging(MotionEvent event) {
11844        if (mScrollCache == null) {
11845            return false;
11846        }
11847        final float x = event.getX();
11848        final float y = event.getY();
11849        final int action = event.getAction();
11850        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11851                && action != MotionEvent.ACTION_DOWN)
11852                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11853                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11854            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11855            return false;
11856        }
11857
11858        switch (action) {
11859            case MotionEvent.ACTION_MOVE:
11860                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11861                    return false;
11862                }
11863                if (mScrollCache.mScrollBarDraggingState
11864                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11865                    final Rect bounds = mScrollCache.mScrollBarBounds;
11866                    getVerticalScrollBarBounds(bounds, null);
11867                    final int range = computeVerticalScrollRange();
11868                    final int offset = computeVerticalScrollOffset();
11869                    final int extent = computeVerticalScrollExtent();
11870
11871                    final int thumbLength = ScrollBarUtils.getThumbLength(
11872                            bounds.height(), bounds.width(), extent, range);
11873                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11874                            bounds.height(), thumbLength, extent, range, offset);
11875
11876                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11877                    final float maxThumbOffset = bounds.height() - thumbLength;
11878                    final float newThumbOffset =
11879                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11880                    final int height = getHeight();
11881                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11882                            && height > 0 && extent > 0) {
11883                        final int newY = Math.round((range - extent)
11884                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11885                        if (newY != getScrollY()) {
11886                            mScrollCache.mScrollBarDraggingPos = y;
11887                            setScrollY(newY);
11888                        }
11889                    }
11890                    return true;
11891                }
11892                if (mScrollCache.mScrollBarDraggingState
11893                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11894                    final Rect bounds = mScrollCache.mScrollBarBounds;
11895                    getHorizontalScrollBarBounds(bounds, null);
11896                    final int range = computeHorizontalScrollRange();
11897                    final int offset = computeHorizontalScrollOffset();
11898                    final int extent = computeHorizontalScrollExtent();
11899
11900                    final int thumbLength = ScrollBarUtils.getThumbLength(
11901                            bounds.width(), bounds.height(), extent, range);
11902                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11903                            bounds.width(), thumbLength, extent, range, offset);
11904
11905                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11906                    final float maxThumbOffset = bounds.width() - thumbLength;
11907                    final float newThumbOffset =
11908                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11909                    final int width = getWidth();
11910                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11911                            && width > 0 && extent > 0) {
11912                        final int newX = Math.round((range - extent)
11913                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11914                        if (newX != getScrollX()) {
11915                            mScrollCache.mScrollBarDraggingPos = x;
11916                            setScrollX(newX);
11917                        }
11918                    }
11919                    return true;
11920                }
11921            case MotionEvent.ACTION_DOWN:
11922                if (mScrollCache.state == ScrollabilityCache.OFF) {
11923                    return false;
11924                }
11925                if (isOnVerticalScrollbarThumb(x, y)) {
11926                    mScrollCache.mScrollBarDraggingState =
11927                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11928                    mScrollCache.mScrollBarDraggingPos = y;
11929                    return true;
11930                }
11931                if (isOnHorizontalScrollbarThumb(x, y)) {
11932                    mScrollCache.mScrollBarDraggingState =
11933                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11934                    mScrollCache.mScrollBarDraggingPos = x;
11935                    return true;
11936                }
11937        }
11938        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11939        return false;
11940    }
11941
11942    /**
11943     * Implement this method to handle touch screen motion events.
11944     * <p>
11945     * If this method is used to detect click actions, it is recommended that
11946     * the actions be performed by implementing and calling
11947     * {@link #performClick()}. This will ensure consistent system behavior,
11948     * including:
11949     * <ul>
11950     * <li>obeying click sound preferences
11951     * <li>dispatching OnClickListener calls
11952     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11953     * accessibility features are enabled
11954     * </ul>
11955     *
11956     * @param event The motion event.
11957     * @return True if the event was handled, false otherwise.
11958     */
11959    public boolean onTouchEvent(MotionEvent event) {
11960        final float x = event.getX();
11961        final float y = event.getY();
11962        final int viewFlags = mViewFlags;
11963        final int action = event.getAction();
11964
11965        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
11966                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11967                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11968
11969        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11970            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11971                setPressed(false);
11972            }
11973            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11974            // A disabled view that is clickable still consumes the touch
11975            // events, it just doesn't respond to them.
11976            return clickable;
11977        }
11978        if (mTouchDelegate != null) {
11979            if (mTouchDelegate.onTouchEvent(event)) {
11980                return true;
11981            }
11982        }
11983
11984        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
11985            switch (action) {
11986                case MotionEvent.ACTION_UP:
11987                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11988                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
11989                        handleTooltipUp();
11990                    }
11991                    if (!clickable) {
11992                        removeTapCallback();
11993                        removeLongPressCallback();
11994                        mInContextButtonPress = false;
11995                        mHasPerformedLongPress = false;
11996                        mIgnoreNextUpEvent = false;
11997                        break;
11998                    }
11999                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
12000                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
12001                        // take focus if we don't have it already and we should in
12002                        // touch mode.
12003                        boolean focusTaken = false;
12004                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
12005                            focusTaken = requestFocus();
12006                        }
12007
12008                        if (prepressed) {
12009                            // The button is being released before we actually
12010                            // showed it as pressed.  Make it show the pressed
12011                            // state now (before scheduling the click) to ensure
12012                            // the user sees it.
12013                            setPressed(true, x, y);
12014                        }
12015
12016                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
12017                            // This is a tap, so remove the longpress check
12018                            removeLongPressCallback();
12019
12020                            // Only perform take click actions if we were in the pressed state
12021                            if (!focusTaken) {
12022                                // Use a Runnable and post this rather than calling
12023                                // performClick directly. This lets other visual state
12024                                // of the view update before click actions start.
12025                                if (mPerformClick == null) {
12026                                    mPerformClick = new PerformClick();
12027                                }
12028                                if (!post(mPerformClick)) {
12029                                    performClick();
12030                                }
12031                            }
12032                        }
12033
12034                        if (mUnsetPressedState == null) {
12035                            mUnsetPressedState = new UnsetPressedState();
12036                        }
12037
12038                        if (prepressed) {
12039                            postDelayed(mUnsetPressedState,
12040                                    ViewConfiguration.getPressedStateDuration());
12041                        } else if (!post(mUnsetPressedState)) {
12042                            // If the post failed, unpress right now
12043                            mUnsetPressedState.run();
12044                        }
12045
12046                        removeTapCallback();
12047                    }
12048                    mIgnoreNextUpEvent = false;
12049                    break;
12050
12051                case MotionEvent.ACTION_DOWN:
12052                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
12053                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
12054                    }
12055                    mHasPerformedLongPress = false;
12056
12057                    if (!clickable) {
12058                        checkForLongClick(0, x, y);
12059                        break;
12060                    }
12061
12062                    if (performButtonActionOnTouchDown(event)) {
12063                        break;
12064                    }
12065
12066                    // Walk up the hierarchy to determine if we're inside a scrolling container.
12067                    boolean isInScrollingContainer = isInScrollingContainer();
12068
12069                    // For views inside a scrolling container, delay the pressed feedback for
12070                    // a short period in case this is a scroll.
12071                    if (isInScrollingContainer) {
12072                        mPrivateFlags |= PFLAG_PREPRESSED;
12073                        if (mPendingCheckForTap == null) {
12074                            mPendingCheckForTap = new CheckForTap();
12075                        }
12076                        mPendingCheckForTap.x = event.getX();
12077                        mPendingCheckForTap.y = event.getY();
12078                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
12079                    } else {
12080                        // Not inside a scrolling container, so show the feedback right away
12081                        setPressed(true, x, y);
12082                        checkForLongClick(0, x, y);
12083                    }
12084                    break;
12085
12086                case MotionEvent.ACTION_CANCEL:
12087                    if (clickable) {
12088                        setPressed(false);
12089                    }
12090                    removeTapCallback();
12091                    removeLongPressCallback();
12092                    mInContextButtonPress = false;
12093                    mHasPerformedLongPress = false;
12094                    mIgnoreNextUpEvent = false;
12095                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12096                    break;
12097
12098                case MotionEvent.ACTION_MOVE:
12099                    if (clickable) {
12100                        drawableHotspotChanged(x, y);
12101                    }
12102
12103                    // Be lenient about moving outside of buttons
12104                    if (!pointInView(x, y, mTouchSlop)) {
12105                        // Outside button
12106                        // Remove any future long press/tap checks
12107                        removeTapCallback();
12108                        removeLongPressCallback();
12109                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
12110                            setPressed(false);
12111                        }
12112                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12113                    }
12114                    break;
12115            }
12116
12117            return true;
12118        }
12119
12120        return false;
12121    }
12122
12123    /**
12124     * @hide
12125     */
12126    public boolean isInScrollingContainer() {
12127        ViewParent p = getParent();
12128        while (p != null && p instanceof ViewGroup) {
12129            if (((ViewGroup) p).shouldDelayChildPressedState()) {
12130                return true;
12131            }
12132            p = p.getParent();
12133        }
12134        return false;
12135    }
12136
12137    /**
12138     * Remove the longpress detection timer.
12139     */
12140    private void removeLongPressCallback() {
12141        if (mPendingCheckForLongPress != null) {
12142            removeCallbacks(mPendingCheckForLongPress);
12143        }
12144    }
12145
12146    /**
12147     * Remove the pending click action
12148     */
12149    private void removePerformClickCallback() {
12150        if (mPerformClick != null) {
12151            removeCallbacks(mPerformClick);
12152        }
12153    }
12154
12155    /**
12156     * Remove the prepress detection timer.
12157     */
12158    private void removeUnsetPressCallback() {
12159        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
12160            setPressed(false);
12161            removeCallbacks(mUnsetPressedState);
12162        }
12163    }
12164
12165    /**
12166     * Remove the tap detection timer.
12167     */
12168    private void removeTapCallback() {
12169        if (mPendingCheckForTap != null) {
12170            mPrivateFlags &= ~PFLAG_PREPRESSED;
12171            removeCallbacks(mPendingCheckForTap);
12172        }
12173    }
12174
12175    /**
12176     * Cancels a pending long press.  Your subclass can use this if you
12177     * want the context menu to come up if the user presses and holds
12178     * at the same place, but you don't want it to come up if they press
12179     * and then move around enough to cause scrolling.
12180     */
12181    public void cancelLongPress() {
12182        removeLongPressCallback();
12183
12184        /*
12185         * The prepressed state handled by the tap callback is a display
12186         * construct, but the tap callback will post a long press callback
12187         * less its own timeout. Remove it here.
12188         */
12189        removeTapCallback();
12190    }
12191
12192    /**
12193     * Remove the pending callback for sending a
12194     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
12195     */
12196    private void removeSendViewScrolledAccessibilityEventCallback() {
12197        if (mSendViewScrolledAccessibilityEvent != null) {
12198            removeCallbacks(mSendViewScrolledAccessibilityEvent);
12199            mSendViewScrolledAccessibilityEvent.mIsPending = false;
12200        }
12201    }
12202
12203    /**
12204     * Sets the TouchDelegate for this View.
12205     */
12206    public void setTouchDelegate(TouchDelegate delegate) {
12207        mTouchDelegate = delegate;
12208    }
12209
12210    /**
12211     * Gets the TouchDelegate for this View.
12212     */
12213    public TouchDelegate getTouchDelegate() {
12214        return mTouchDelegate;
12215    }
12216
12217    /**
12218     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
12219     *
12220     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
12221     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
12222     * available. This method should only be called for touch events.
12223     *
12224     * <p class="note">This api is not intended for most applications. Buffered dispatch
12225     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
12226     * streams will not improve your input latency. Side effects include: increased latency,
12227     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
12228     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
12229     * you.</p>
12230     */
12231    public final void requestUnbufferedDispatch(MotionEvent event) {
12232        final int action = event.getAction();
12233        if (mAttachInfo == null
12234                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
12235                || !event.isTouchEvent()) {
12236            return;
12237        }
12238        mAttachInfo.mUnbufferedDispatchRequested = true;
12239    }
12240
12241    /**
12242     * Set flags controlling behavior of this view.
12243     *
12244     * @param flags Constant indicating the value which should be set
12245     * @param mask Constant indicating the bit range that should be changed
12246     */
12247    void setFlags(int flags, int mask) {
12248        final boolean accessibilityEnabled =
12249                AccessibilityManager.getInstance(mContext).isEnabled();
12250        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
12251
12252        int old = mViewFlags;
12253        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
12254
12255        int changed = mViewFlags ^ old;
12256        if (changed == 0) {
12257            return;
12258        }
12259        int privateFlags = mPrivateFlags;
12260
12261        // If focusable is auto, update the FOCUSABLE bit.
12262        int focusableChangedByAuto = 0;
12263        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
12264                && (changed & (FOCUSABLE_MASK | CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12265            int newFocus = NOT_FOCUSABLE;
12266            if ((mViewFlags & (CLICKABLE | FOCUSABLE_IN_TOUCH_MODE)) != 0) {
12267                newFocus = FOCUSABLE;
12268            } else {
12269                mViewFlags = (mViewFlags & ~FOCUSABLE_IN_TOUCH_MODE);
12270            }
12271            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
12272            focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
12273            changed = (changed & ~FOCUSABLE) | focusableChangedByAuto;
12274        }
12275
12276        /* Check if the FOCUSABLE bit has changed */
12277        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
12278            if (((old & FOCUSABLE) == FOCUSABLE)
12279                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
12280                /* Give up focus if we are no longer focusable */
12281                clearFocus();
12282            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
12283                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
12284                /*
12285                 * Tell the view system that we are now available to take focus
12286                 * if no one else already has it.
12287                 */
12288                if (mParent != null) {
12289                    ViewRootImpl viewRootImpl = getViewRootImpl();
12290                    if (!sAutoFocusableOffUIThreadWontNotifyParents
12291                            || focusableChangedByAuto == 0
12292                            || viewRootImpl == null
12293                            || viewRootImpl.mThread == Thread.currentThread()) {
12294                        mParent.focusableViewAvailable(this);
12295                    }
12296                }
12297            }
12298        }
12299
12300        final int newVisibility = flags & VISIBILITY_MASK;
12301        if (newVisibility == VISIBLE) {
12302            if ((changed & VISIBILITY_MASK) != 0) {
12303                /*
12304                 * If this view is becoming visible, invalidate it in case it changed while
12305                 * it was not visible. Marking it drawn ensures that the invalidation will
12306                 * go through.
12307                 */
12308                mPrivateFlags |= PFLAG_DRAWN;
12309                invalidate(true);
12310
12311                needGlobalAttributesUpdate(true);
12312
12313                // a view becoming visible is worth notifying the parent
12314                // about in case nothing has focus.  even if this specific view
12315                // isn't focusable, it may contain something that is, so let
12316                // the root view try to give this focus if nothing else does.
12317                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
12318                    mParent.focusableViewAvailable(this);
12319                }
12320            }
12321        }
12322
12323        /* Check if the GONE bit has changed */
12324        if ((changed & GONE) != 0) {
12325            needGlobalAttributesUpdate(false);
12326            requestLayout();
12327
12328            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
12329                if (hasFocus()) clearFocus();
12330                clearAccessibilityFocus();
12331                destroyDrawingCache();
12332                if (mParent instanceof View) {
12333                    // GONE views noop invalidation, so invalidate the parent
12334                    ((View) mParent).invalidate(true);
12335                }
12336                // Mark the view drawn to ensure that it gets invalidated properly the next
12337                // time it is visible and gets invalidated
12338                mPrivateFlags |= PFLAG_DRAWN;
12339            }
12340            if (mAttachInfo != null) {
12341                mAttachInfo.mViewVisibilityChanged = true;
12342            }
12343        }
12344
12345        /* Check if the VISIBLE bit has changed */
12346        if ((changed & INVISIBLE) != 0) {
12347            needGlobalAttributesUpdate(false);
12348            /*
12349             * If this view is becoming invisible, set the DRAWN flag so that
12350             * the next invalidate() will not be skipped.
12351             */
12352            mPrivateFlags |= PFLAG_DRAWN;
12353
12354            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
12355                // root view becoming invisible shouldn't clear focus and accessibility focus
12356                if (getRootView() != this) {
12357                    if (hasFocus()) clearFocus();
12358                    clearAccessibilityFocus();
12359                }
12360            }
12361            if (mAttachInfo != null) {
12362                mAttachInfo.mViewVisibilityChanged = true;
12363            }
12364        }
12365
12366        if ((changed & VISIBILITY_MASK) != 0) {
12367            // If the view is invisible, cleanup its display list to free up resources
12368            if (newVisibility != VISIBLE && mAttachInfo != null) {
12369                cleanupDraw();
12370            }
12371
12372            if (mParent instanceof ViewGroup) {
12373                ((ViewGroup) mParent).onChildVisibilityChanged(this,
12374                        (changed & VISIBILITY_MASK), newVisibility);
12375                ((View) mParent).invalidate(true);
12376            } else if (mParent != null) {
12377                mParent.invalidateChild(this, null);
12378            }
12379
12380            if (mAttachInfo != null) {
12381                dispatchVisibilityChanged(this, newVisibility);
12382
12383                // Aggregated visibility changes are dispatched to attached views
12384                // in visible windows where the parent is currently shown/drawn
12385                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
12386                // discounting clipping or overlapping. This makes it a good place
12387                // to change animation states.
12388                if (mParent != null && getWindowVisibility() == VISIBLE &&
12389                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
12390                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
12391                }
12392                notifySubtreeAccessibilityStateChangedIfNeeded();
12393            }
12394        }
12395
12396        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
12397            destroyDrawingCache();
12398        }
12399
12400        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
12401            destroyDrawingCache();
12402            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12403            invalidateParentCaches();
12404        }
12405
12406        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
12407            destroyDrawingCache();
12408            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12409        }
12410
12411        if ((changed & DRAW_MASK) != 0) {
12412            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
12413                if (mBackground != null
12414                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
12415                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12416                } else {
12417                    mPrivateFlags |= PFLAG_SKIP_DRAW;
12418                }
12419            } else {
12420                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12421            }
12422            requestLayout();
12423            invalidate(true);
12424        }
12425
12426        if ((changed & KEEP_SCREEN_ON) != 0) {
12427            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12428                mParent.recomputeViewAttributes(this);
12429            }
12430        }
12431
12432        if (accessibilityEnabled) {
12433            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
12434                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
12435                    || (changed & CONTEXT_CLICKABLE) != 0) {
12436                if (oldIncludeForAccessibility != includeForAccessibility()) {
12437                    notifySubtreeAccessibilityStateChangedIfNeeded();
12438                } else {
12439                    notifyViewAccessibilityStateChangedIfNeeded(
12440                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12441                }
12442            } else if ((changed & ENABLED_MASK) != 0) {
12443                notifyViewAccessibilityStateChangedIfNeeded(
12444                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12445            }
12446        }
12447    }
12448
12449    /**
12450     * Change the view's z order in the tree, so it's on top of other sibling
12451     * views. This ordering change may affect layout, if the parent container
12452     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
12453     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
12454     * method should be followed by calls to {@link #requestLayout()} and
12455     * {@link View#invalidate()} on the view's parent to force the parent to redraw
12456     * with the new child ordering.
12457     *
12458     * @see ViewGroup#bringChildToFront(View)
12459     */
12460    public void bringToFront() {
12461        if (mParent != null) {
12462            mParent.bringChildToFront(this);
12463        }
12464    }
12465
12466    /**
12467     * This is called in response to an internal scroll in this view (i.e., the
12468     * view scrolled its own contents). This is typically as a result of
12469     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
12470     * called.
12471     *
12472     * @param l Current horizontal scroll origin.
12473     * @param t Current vertical scroll origin.
12474     * @param oldl Previous horizontal scroll origin.
12475     * @param oldt Previous vertical scroll origin.
12476     */
12477    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
12478        notifySubtreeAccessibilityStateChangedIfNeeded();
12479
12480        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
12481            postSendViewScrolledAccessibilityEventCallback();
12482        }
12483
12484        mBackgroundSizeChanged = true;
12485        if (mForegroundInfo != null) {
12486            mForegroundInfo.mBoundsChanged = true;
12487        }
12488
12489        final AttachInfo ai = mAttachInfo;
12490        if (ai != null) {
12491            ai.mViewScrollChanged = true;
12492        }
12493
12494        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
12495            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
12496        }
12497    }
12498
12499    /**
12500     * Interface definition for a callback to be invoked when the scroll
12501     * X or Y positions of a view change.
12502     * <p>
12503     * <b>Note:</b> Some views handle scrolling independently from View and may
12504     * have their own separate listeners for scroll-type events. For example,
12505     * {@link android.widget.ListView ListView} allows clients to register an
12506     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
12507     * to listen for changes in list scroll position.
12508     *
12509     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
12510     */
12511    public interface OnScrollChangeListener {
12512        /**
12513         * Called when the scroll position of a view changes.
12514         *
12515         * @param v The view whose scroll position has changed.
12516         * @param scrollX Current horizontal scroll origin.
12517         * @param scrollY Current vertical scroll origin.
12518         * @param oldScrollX Previous horizontal scroll origin.
12519         * @param oldScrollY Previous vertical scroll origin.
12520         */
12521        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
12522    }
12523
12524    /**
12525     * Interface definition for a callback to be invoked when the layout bounds of a view
12526     * changes due to layout processing.
12527     */
12528    public interface OnLayoutChangeListener {
12529        /**
12530         * Called when the layout bounds of a view changes due to layout processing.
12531         *
12532         * @param v The view whose bounds have changed.
12533         * @param left The new value of the view's left property.
12534         * @param top The new value of the view's top property.
12535         * @param right The new value of the view's right property.
12536         * @param bottom The new value of the view's bottom property.
12537         * @param oldLeft The previous value of the view's left property.
12538         * @param oldTop The previous value of the view's top property.
12539         * @param oldRight The previous value of the view's right property.
12540         * @param oldBottom The previous value of the view's bottom property.
12541         */
12542        void onLayoutChange(View v, int left, int top, int right, int bottom,
12543            int oldLeft, int oldTop, int oldRight, int oldBottom);
12544    }
12545
12546    /**
12547     * This is called during layout when the size of this view has changed. If
12548     * you were just added to the view hierarchy, you're called with the old
12549     * values of 0.
12550     *
12551     * @param w Current width of this view.
12552     * @param h Current height of this view.
12553     * @param oldw Old width of this view.
12554     * @param oldh Old height of this view.
12555     */
12556    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
12557    }
12558
12559    /**
12560     * Called by draw to draw the child views. This may be overridden
12561     * by derived classes to gain control just before its children are drawn
12562     * (but after its own view has been drawn).
12563     * @param canvas the canvas on which to draw the view
12564     */
12565    protected void dispatchDraw(Canvas canvas) {
12566
12567    }
12568
12569    /**
12570     * Gets the parent of this view. Note that the parent is a
12571     * ViewParent and not necessarily a View.
12572     *
12573     * @return Parent of this view.
12574     */
12575    public final ViewParent getParent() {
12576        return mParent;
12577    }
12578
12579    /**
12580     * Set the horizontal scrolled position of your view. This will cause a call to
12581     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12582     * invalidated.
12583     * @param value the x position to scroll to
12584     */
12585    public void setScrollX(int value) {
12586        scrollTo(value, mScrollY);
12587    }
12588
12589    /**
12590     * Set the vertical scrolled position of your view. This will cause a call to
12591     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12592     * invalidated.
12593     * @param value the y position to scroll to
12594     */
12595    public void setScrollY(int value) {
12596        scrollTo(mScrollX, value);
12597    }
12598
12599    /**
12600     * Return the scrolled left position of this view. This is the left edge of
12601     * the displayed part of your view. You do not need to draw any pixels
12602     * farther left, since those are outside of the frame of your view on
12603     * screen.
12604     *
12605     * @return The left edge of the displayed part of your view, in pixels.
12606     */
12607    public final int getScrollX() {
12608        return mScrollX;
12609    }
12610
12611    /**
12612     * Return the scrolled top position of this view. This is the top edge of
12613     * the displayed part of your view. You do not need to draw any pixels above
12614     * it, since those are outside of the frame of your view on screen.
12615     *
12616     * @return The top edge of the displayed part of your view, in pixels.
12617     */
12618    public final int getScrollY() {
12619        return mScrollY;
12620    }
12621
12622    /**
12623     * Return the width of the your view.
12624     *
12625     * @return The width of your view, in pixels.
12626     */
12627    @ViewDebug.ExportedProperty(category = "layout")
12628    public final int getWidth() {
12629        return mRight - mLeft;
12630    }
12631
12632    /**
12633     * Return the height of your view.
12634     *
12635     * @return The height of your view, in pixels.
12636     */
12637    @ViewDebug.ExportedProperty(category = "layout")
12638    public final int getHeight() {
12639        return mBottom - mTop;
12640    }
12641
12642    /**
12643     * Return the visible drawing bounds of your view. Fills in the output
12644     * rectangle with the values from getScrollX(), getScrollY(),
12645     * getWidth(), and getHeight(). These bounds do not account for any
12646     * transformation properties currently set on the view, such as
12647     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
12648     *
12649     * @param outRect The (scrolled) drawing bounds of the view.
12650     */
12651    public void getDrawingRect(Rect outRect) {
12652        outRect.left = mScrollX;
12653        outRect.top = mScrollY;
12654        outRect.right = mScrollX + (mRight - mLeft);
12655        outRect.bottom = mScrollY + (mBottom - mTop);
12656    }
12657
12658    /**
12659     * Like {@link #getMeasuredWidthAndState()}, but only returns the
12660     * raw width component (that is the result is masked by
12661     * {@link #MEASURED_SIZE_MASK}).
12662     *
12663     * @return The raw measured width of this view.
12664     */
12665    public final int getMeasuredWidth() {
12666        return mMeasuredWidth & MEASURED_SIZE_MASK;
12667    }
12668
12669    /**
12670     * Return the full width measurement information for this view as computed
12671     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12672     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12673     * This should be used during measurement and layout calculations only. Use
12674     * {@link #getWidth()} to see how wide a view is after layout.
12675     *
12676     * @return The measured width of this view as a bit mask.
12677     */
12678    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12679            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12680                    name = "MEASURED_STATE_TOO_SMALL"),
12681    })
12682    public final int getMeasuredWidthAndState() {
12683        return mMeasuredWidth;
12684    }
12685
12686    /**
12687     * Like {@link #getMeasuredHeightAndState()}, but only returns the
12688     * raw height component (that is the result is masked by
12689     * {@link #MEASURED_SIZE_MASK}).
12690     *
12691     * @return The raw measured height of this view.
12692     */
12693    public final int getMeasuredHeight() {
12694        return mMeasuredHeight & MEASURED_SIZE_MASK;
12695    }
12696
12697    /**
12698     * Return the full height measurement information for this view as computed
12699     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12700     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12701     * This should be used during measurement and layout calculations only. Use
12702     * {@link #getHeight()} to see how wide a view is after layout.
12703     *
12704     * @return The measured height of this view as a bit mask.
12705     */
12706    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12707            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12708                    name = "MEASURED_STATE_TOO_SMALL"),
12709    })
12710    public final int getMeasuredHeightAndState() {
12711        return mMeasuredHeight;
12712    }
12713
12714    /**
12715     * Return only the state bits of {@link #getMeasuredWidthAndState()}
12716     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
12717     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
12718     * and the height component is at the shifted bits
12719     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
12720     */
12721    public final int getMeasuredState() {
12722        return (mMeasuredWidth&MEASURED_STATE_MASK)
12723                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
12724                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
12725    }
12726
12727    /**
12728     * The transform matrix of this view, which is calculated based on the current
12729     * rotation, scale, and pivot properties.
12730     *
12731     * @see #getRotation()
12732     * @see #getScaleX()
12733     * @see #getScaleY()
12734     * @see #getPivotX()
12735     * @see #getPivotY()
12736     * @return The current transform matrix for the view
12737     */
12738    public Matrix getMatrix() {
12739        ensureTransformationInfo();
12740        final Matrix matrix = mTransformationInfo.mMatrix;
12741        mRenderNode.getMatrix(matrix);
12742        return matrix;
12743    }
12744
12745    /**
12746     * Returns true if the transform matrix is the identity matrix.
12747     * Recomputes the matrix if necessary.
12748     *
12749     * @return True if the transform matrix is the identity matrix, false otherwise.
12750     */
12751    final boolean hasIdentityMatrix() {
12752        return mRenderNode.hasIdentityMatrix();
12753    }
12754
12755    void ensureTransformationInfo() {
12756        if (mTransformationInfo == null) {
12757            mTransformationInfo = new TransformationInfo();
12758        }
12759    }
12760
12761    /**
12762     * Utility method to retrieve the inverse of the current mMatrix property.
12763     * We cache the matrix to avoid recalculating it when transform properties
12764     * have not changed.
12765     *
12766     * @return The inverse of the current matrix of this view.
12767     * @hide
12768     */
12769    public final Matrix getInverseMatrix() {
12770        ensureTransformationInfo();
12771        if (mTransformationInfo.mInverseMatrix == null) {
12772            mTransformationInfo.mInverseMatrix = new Matrix();
12773        }
12774        final Matrix matrix = mTransformationInfo.mInverseMatrix;
12775        mRenderNode.getInverseMatrix(matrix);
12776        return matrix;
12777    }
12778
12779    /**
12780     * Gets the distance along the Z axis from the camera to this view.
12781     *
12782     * @see #setCameraDistance(float)
12783     *
12784     * @return The distance along the Z axis.
12785     */
12786    public float getCameraDistance() {
12787        final float dpi = mResources.getDisplayMetrics().densityDpi;
12788        return -(mRenderNode.getCameraDistance() * dpi);
12789    }
12790
12791    /**
12792     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
12793     * views are drawn) from the camera to this view. The camera's distance
12794     * affects 3D transformations, for instance rotations around the X and Y
12795     * axis. If the rotationX or rotationY properties are changed and this view is
12796     * large (more than half the size of the screen), it is recommended to always
12797     * use a camera distance that's greater than the height (X axis rotation) or
12798     * the width (Y axis rotation) of this view.</p>
12799     *
12800     * <p>The distance of the camera from the view plane can have an affect on the
12801     * perspective distortion of the view when it is rotated around the x or y axis.
12802     * For example, a large distance will result in a large viewing angle, and there
12803     * will not be much perspective distortion of the view as it rotates. A short
12804     * distance may cause much more perspective distortion upon rotation, and can
12805     * also result in some drawing artifacts if the rotated view ends up partially
12806     * behind the camera (which is why the recommendation is to use a distance at
12807     * least as far as the size of the view, if the view is to be rotated.)</p>
12808     *
12809     * <p>The distance is expressed in "depth pixels." The default distance depends
12810     * on the screen density. For instance, on a medium density display, the
12811     * default distance is 1280. On a high density display, the default distance
12812     * is 1920.</p>
12813     *
12814     * <p>If you want to specify a distance that leads to visually consistent
12815     * results across various densities, use the following formula:</p>
12816     * <pre>
12817     * float scale = context.getResources().getDisplayMetrics().density;
12818     * view.setCameraDistance(distance * scale);
12819     * </pre>
12820     *
12821     * <p>The density scale factor of a high density display is 1.5,
12822     * and 1920 = 1280 * 1.5.</p>
12823     *
12824     * @param distance The distance in "depth pixels", if negative the opposite
12825     *        value is used
12826     *
12827     * @see #setRotationX(float)
12828     * @see #setRotationY(float)
12829     */
12830    public void setCameraDistance(float distance) {
12831        final float dpi = mResources.getDisplayMetrics().densityDpi;
12832
12833        invalidateViewProperty(true, false);
12834        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
12835        invalidateViewProperty(false, false);
12836
12837        invalidateParentIfNeededAndWasQuickRejected();
12838    }
12839
12840    /**
12841     * The degrees that the view is rotated around the pivot point.
12842     *
12843     * @see #setRotation(float)
12844     * @see #getPivotX()
12845     * @see #getPivotY()
12846     *
12847     * @return The degrees of rotation.
12848     */
12849    @ViewDebug.ExportedProperty(category = "drawing")
12850    public float getRotation() {
12851        return mRenderNode.getRotation();
12852    }
12853
12854    /**
12855     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12856     * result in clockwise rotation.
12857     *
12858     * @param rotation The degrees of rotation.
12859     *
12860     * @see #getRotation()
12861     * @see #getPivotX()
12862     * @see #getPivotY()
12863     * @see #setRotationX(float)
12864     * @see #setRotationY(float)
12865     *
12866     * @attr ref android.R.styleable#View_rotation
12867     */
12868    public void setRotation(float rotation) {
12869        if (rotation != getRotation()) {
12870            // Double-invalidation is necessary to capture view's old and new areas
12871            invalidateViewProperty(true, false);
12872            mRenderNode.setRotation(rotation);
12873            invalidateViewProperty(false, true);
12874
12875            invalidateParentIfNeededAndWasQuickRejected();
12876            notifySubtreeAccessibilityStateChangedIfNeeded();
12877        }
12878    }
12879
12880    /**
12881     * The degrees that the view is rotated around the vertical axis through the pivot point.
12882     *
12883     * @see #getPivotX()
12884     * @see #getPivotY()
12885     * @see #setRotationY(float)
12886     *
12887     * @return The degrees of Y rotation.
12888     */
12889    @ViewDebug.ExportedProperty(category = "drawing")
12890    public float getRotationY() {
12891        return mRenderNode.getRotationY();
12892    }
12893
12894    /**
12895     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12896     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12897     * down the y axis.
12898     *
12899     * When rotating large views, it is recommended to adjust the camera distance
12900     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12901     *
12902     * @param rotationY The degrees of Y rotation.
12903     *
12904     * @see #getRotationY()
12905     * @see #getPivotX()
12906     * @see #getPivotY()
12907     * @see #setRotation(float)
12908     * @see #setRotationX(float)
12909     * @see #setCameraDistance(float)
12910     *
12911     * @attr ref android.R.styleable#View_rotationY
12912     */
12913    public void setRotationY(float rotationY) {
12914        if (rotationY != getRotationY()) {
12915            invalidateViewProperty(true, false);
12916            mRenderNode.setRotationY(rotationY);
12917            invalidateViewProperty(false, true);
12918
12919            invalidateParentIfNeededAndWasQuickRejected();
12920            notifySubtreeAccessibilityStateChangedIfNeeded();
12921        }
12922    }
12923
12924    /**
12925     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12926     *
12927     * @see #getPivotX()
12928     * @see #getPivotY()
12929     * @see #setRotationX(float)
12930     *
12931     * @return The degrees of X rotation.
12932     */
12933    @ViewDebug.ExportedProperty(category = "drawing")
12934    public float getRotationX() {
12935        return mRenderNode.getRotationX();
12936    }
12937
12938    /**
12939     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12940     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12941     * x axis.
12942     *
12943     * When rotating large views, it is recommended to adjust the camera distance
12944     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12945     *
12946     * @param rotationX The degrees of X rotation.
12947     *
12948     * @see #getRotationX()
12949     * @see #getPivotX()
12950     * @see #getPivotY()
12951     * @see #setRotation(float)
12952     * @see #setRotationY(float)
12953     * @see #setCameraDistance(float)
12954     *
12955     * @attr ref android.R.styleable#View_rotationX
12956     */
12957    public void setRotationX(float rotationX) {
12958        if (rotationX != getRotationX()) {
12959            invalidateViewProperty(true, false);
12960            mRenderNode.setRotationX(rotationX);
12961            invalidateViewProperty(false, true);
12962
12963            invalidateParentIfNeededAndWasQuickRejected();
12964            notifySubtreeAccessibilityStateChangedIfNeeded();
12965        }
12966    }
12967
12968    /**
12969     * The amount that the view is scaled in x around the pivot point, as a proportion of
12970     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12971     *
12972     * <p>By default, this is 1.0f.
12973     *
12974     * @see #getPivotX()
12975     * @see #getPivotY()
12976     * @return The scaling factor.
12977     */
12978    @ViewDebug.ExportedProperty(category = "drawing")
12979    public float getScaleX() {
12980        return mRenderNode.getScaleX();
12981    }
12982
12983    /**
12984     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12985     * the view's unscaled width. A value of 1 means that no scaling is applied.
12986     *
12987     * @param scaleX The scaling factor.
12988     * @see #getPivotX()
12989     * @see #getPivotY()
12990     *
12991     * @attr ref android.R.styleable#View_scaleX
12992     */
12993    public void setScaleX(float scaleX) {
12994        if (scaleX != getScaleX()) {
12995            invalidateViewProperty(true, false);
12996            mRenderNode.setScaleX(scaleX);
12997            invalidateViewProperty(false, true);
12998
12999            invalidateParentIfNeededAndWasQuickRejected();
13000            notifySubtreeAccessibilityStateChangedIfNeeded();
13001        }
13002    }
13003
13004    /**
13005     * The amount that the view is scaled in y around the pivot point, as a proportion of
13006     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
13007     *
13008     * <p>By default, this is 1.0f.
13009     *
13010     * @see #getPivotX()
13011     * @see #getPivotY()
13012     * @return The scaling factor.
13013     */
13014    @ViewDebug.ExportedProperty(category = "drawing")
13015    public float getScaleY() {
13016        return mRenderNode.getScaleY();
13017    }
13018
13019    /**
13020     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
13021     * the view's unscaled width. A value of 1 means that no scaling is applied.
13022     *
13023     * @param scaleY The scaling factor.
13024     * @see #getPivotX()
13025     * @see #getPivotY()
13026     *
13027     * @attr ref android.R.styleable#View_scaleY
13028     */
13029    public void setScaleY(float scaleY) {
13030        if (scaleY != getScaleY()) {
13031            invalidateViewProperty(true, false);
13032            mRenderNode.setScaleY(scaleY);
13033            invalidateViewProperty(false, true);
13034
13035            invalidateParentIfNeededAndWasQuickRejected();
13036            notifySubtreeAccessibilityStateChangedIfNeeded();
13037        }
13038    }
13039
13040    /**
13041     * The x location of the point around which the view is {@link #setRotation(float) rotated}
13042     * and {@link #setScaleX(float) scaled}.
13043     *
13044     * @see #getRotation()
13045     * @see #getScaleX()
13046     * @see #getScaleY()
13047     * @see #getPivotY()
13048     * @return The x location of the pivot point.
13049     *
13050     * @attr ref android.R.styleable#View_transformPivotX
13051     */
13052    @ViewDebug.ExportedProperty(category = "drawing")
13053    public float getPivotX() {
13054        return mRenderNode.getPivotX();
13055    }
13056
13057    /**
13058     * Sets the x location of the point around which the view is
13059     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
13060     * By default, the pivot point is centered on the object.
13061     * Setting this property disables this behavior and causes the view to use only the
13062     * explicitly set pivotX and pivotY values.
13063     *
13064     * @param pivotX The x location of the pivot point.
13065     * @see #getRotation()
13066     * @see #getScaleX()
13067     * @see #getScaleY()
13068     * @see #getPivotY()
13069     *
13070     * @attr ref android.R.styleable#View_transformPivotX
13071     */
13072    public void setPivotX(float pivotX) {
13073        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
13074            invalidateViewProperty(true, false);
13075            mRenderNode.setPivotX(pivotX);
13076            invalidateViewProperty(false, true);
13077
13078            invalidateParentIfNeededAndWasQuickRejected();
13079        }
13080    }
13081
13082    /**
13083     * The y location of the point around which the view is {@link #setRotation(float) rotated}
13084     * and {@link #setScaleY(float) scaled}.
13085     *
13086     * @see #getRotation()
13087     * @see #getScaleX()
13088     * @see #getScaleY()
13089     * @see #getPivotY()
13090     * @return The y location of the pivot point.
13091     *
13092     * @attr ref android.R.styleable#View_transformPivotY
13093     */
13094    @ViewDebug.ExportedProperty(category = "drawing")
13095    public float getPivotY() {
13096        return mRenderNode.getPivotY();
13097    }
13098
13099    /**
13100     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
13101     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
13102     * Setting this property disables this behavior and causes the view to use only the
13103     * explicitly set pivotX and pivotY values.
13104     *
13105     * @param pivotY The y location of the pivot point.
13106     * @see #getRotation()
13107     * @see #getScaleX()
13108     * @see #getScaleY()
13109     * @see #getPivotY()
13110     *
13111     * @attr ref android.R.styleable#View_transformPivotY
13112     */
13113    public void setPivotY(float pivotY) {
13114        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
13115            invalidateViewProperty(true, false);
13116            mRenderNode.setPivotY(pivotY);
13117            invalidateViewProperty(false, true);
13118
13119            invalidateParentIfNeededAndWasQuickRejected();
13120        }
13121    }
13122
13123    /**
13124     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
13125     * completely transparent and 1 means the view is completely opaque.
13126     *
13127     * <p>By default this is 1.0f.
13128     * @return The opacity of the view.
13129     */
13130    @ViewDebug.ExportedProperty(category = "drawing")
13131    public float getAlpha() {
13132        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
13133    }
13134
13135    /**
13136     * Sets the behavior for overlapping rendering for this view (see {@link
13137     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
13138     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
13139     * providing the value which is then used internally. That is, when {@link
13140     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
13141     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
13142     * instead.
13143     *
13144     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
13145     * instead of that returned by {@link #hasOverlappingRendering()}.
13146     *
13147     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
13148     */
13149    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
13150        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
13151        if (hasOverlappingRendering) {
13152            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13153        } else {
13154            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13155        }
13156    }
13157
13158    /**
13159     * Returns the value for overlapping rendering that is used internally. This is either
13160     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
13161     * the return value of {@link #hasOverlappingRendering()}, otherwise.
13162     *
13163     * @return The value for overlapping rendering being used internally.
13164     */
13165    public final boolean getHasOverlappingRendering() {
13166        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
13167                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
13168                hasOverlappingRendering();
13169    }
13170
13171    /**
13172     * Returns whether this View has content which overlaps.
13173     *
13174     * <p>This function, intended to be overridden by specific View types, is an optimization when
13175     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
13176     * an offscreen buffer and then composited into place, which can be expensive. If the view has
13177     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
13178     * directly. An example of overlapping rendering is a TextView with a background image, such as
13179     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
13180     * ImageView with only the foreground image. The default implementation returns true; subclasses
13181     * should override if they have cases which can be optimized.</p>
13182     *
13183     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
13184     * necessitates that a View return true if it uses the methods internally without passing the
13185     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
13186     *
13187     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
13188     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
13189     *
13190     * @return true if the content in this view might overlap, false otherwise.
13191     */
13192    @ViewDebug.ExportedProperty(category = "drawing")
13193    public boolean hasOverlappingRendering() {
13194        return true;
13195    }
13196
13197    /**
13198     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
13199     * completely transparent and 1 means the view is completely opaque.
13200     *
13201     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
13202     * can have significant performance implications, especially for large views. It is best to use
13203     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
13204     *
13205     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
13206     * strongly recommended for performance reasons to either override
13207     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
13208     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
13209     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
13210     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
13211     * of rendering cost, even for simple or small views. Starting with
13212     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
13213     * applied to the view at the rendering level.</p>
13214     *
13215     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
13216     * responsible for applying the opacity itself.</p>
13217     *
13218     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
13219     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
13220     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
13221     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
13222     *
13223     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
13224     * value will clip a View to its bounds, unless the View returns <code>false</code> from
13225     * {@link #hasOverlappingRendering}.</p>
13226     *
13227     * @param alpha The opacity of the view.
13228     *
13229     * @see #hasOverlappingRendering()
13230     * @see #setLayerType(int, android.graphics.Paint)
13231     *
13232     * @attr ref android.R.styleable#View_alpha
13233     */
13234    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
13235        ensureTransformationInfo();
13236        if (mTransformationInfo.mAlpha != alpha) {
13237            // Report visibility changes, which can affect children, to accessibility
13238            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
13239                notifySubtreeAccessibilityStateChangedIfNeeded();
13240            }
13241            mTransformationInfo.mAlpha = alpha;
13242            if (onSetAlpha((int) (alpha * 255))) {
13243                mPrivateFlags |= PFLAG_ALPHA_SET;
13244                // subclass is handling alpha - don't optimize rendering cache invalidation
13245                invalidateParentCaches();
13246                invalidate(true);
13247            } else {
13248                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13249                invalidateViewProperty(true, false);
13250                mRenderNode.setAlpha(getFinalAlpha());
13251            }
13252        }
13253    }
13254
13255    /**
13256     * Faster version of setAlpha() which performs the same steps except there are
13257     * no calls to invalidate(). The caller of this function should perform proper invalidation
13258     * on the parent and this object. The return value indicates whether the subclass handles
13259     * alpha (the return value for onSetAlpha()).
13260     *
13261     * @param alpha The new value for the alpha property
13262     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
13263     *         the new value for the alpha property is different from the old value
13264     */
13265    boolean setAlphaNoInvalidation(float alpha) {
13266        ensureTransformationInfo();
13267        if (mTransformationInfo.mAlpha != alpha) {
13268            mTransformationInfo.mAlpha = alpha;
13269            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
13270            if (subclassHandlesAlpha) {
13271                mPrivateFlags |= PFLAG_ALPHA_SET;
13272                return true;
13273            } else {
13274                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13275                mRenderNode.setAlpha(getFinalAlpha());
13276            }
13277        }
13278        return false;
13279    }
13280
13281    /**
13282     * This property is hidden and intended only for use by the Fade transition, which
13283     * animates it to produce a visual translucency that does not side-effect (or get
13284     * affected by) the real alpha property. This value is composited with the other
13285     * alpha value (and the AlphaAnimation value, when that is present) to produce
13286     * a final visual translucency result, which is what is passed into the DisplayList.
13287     *
13288     * @hide
13289     */
13290    public void setTransitionAlpha(float alpha) {
13291        ensureTransformationInfo();
13292        if (mTransformationInfo.mTransitionAlpha != alpha) {
13293            mTransformationInfo.mTransitionAlpha = alpha;
13294            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13295            invalidateViewProperty(true, false);
13296            mRenderNode.setAlpha(getFinalAlpha());
13297        }
13298    }
13299
13300    /**
13301     * Calculates the visual alpha of this view, which is a combination of the actual
13302     * alpha value and the transitionAlpha value (if set).
13303     */
13304    private float getFinalAlpha() {
13305        if (mTransformationInfo != null) {
13306            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
13307        }
13308        return 1;
13309    }
13310
13311    /**
13312     * This property is hidden and intended only for use by the Fade transition, which
13313     * animates it to produce a visual translucency that does not side-effect (or get
13314     * affected by) the real alpha property. This value is composited with the other
13315     * alpha value (and the AlphaAnimation value, when that is present) to produce
13316     * a final visual translucency result, which is what is passed into the DisplayList.
13317     *
13318     * @hide
13319     */
13320    @ViewDebug.ExportedProperty(category = "drawing")
13321    public float getTransitionAlpha() {
13322        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
13323    }
13324
13325    /**
13326     * Top position of this view relative to its parent.
13327     *
13328     * @return The top of this view, in pixels.
13329     */
13330    @ViewDebug.CapturedViewProperty
13331    public final int getTop() {
13332        return mTop;
13333    }
13334
13335    /**
13336     * Sets the top position of this view relative to its parent. This method is meant to be called
13337     * by the layout system and should not generally be called otherwise, because the property
13338     * may be changed at any time by the layout.
13339     *
13340     * @param top The top of this view, in pixels.
13341     */
13342    public final void setTop(int top) {
13343        if (top != mTop) {
13344            final boolean matrixIsIdentity = hasIdentityMatrix();
13345            if (matrixIsIdentity) {
13346                if (mAttachInfo != null) {
13347                    int minTop;
13348                    int yLoc;
13349                    if (top < mTop) {
13350                        minTop = top;
13351                        yLoc = top - mTop;
13352                    } else {
13353                        minTop = mTop;
13354                        yLoc = 0;
13355                    }
13356                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
13357                }
13358            } else {
13359                // Double-invalidation is necessary to capture view's old and new areas
13360                invalidate(true);
13361            }
13362
13363            int width = mRight - mLeft;
13364            int oldHeight = mBottom - mTop;
13365
13366            mTop = top;
13367            mRenderNode.setTop(mTop);
13368
13369            sizeChange(width, mBottom - mTop, width, oldHeight);
13370
13371            if (!matrixIsIdentity) {
13372                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13373                invalidate(true);
13374            }
13375            mBackgroundSizeChanged = true;
13376            if (mForegroundInfo != null) {
13377                mForegroundInfo.mBoundsChanged = true;
13378            }
13379            invalidateParentIfNeeded();
13380            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13381                // View was rejected last time it was drawn by its parent; this may have changed
13382                invalidateParentIfNeeded();
13383            }
13384        }
13385    }
13386
13387    /**
13388     * Bottom position of this view relative to its parent.
13389     *
13390     * @return The bottom of this view, in pixels.
13391     */
13392    @ViewDebug.CapturedViewProperty
13393    public final int getBottom() {
13394        return mBottom;
13395    }
13396
13397    /**
13398     * True if this view has changed since the last time being drawn.
13399     *
13400     * @return The dirty state of this view.
13401     */
13402    public boolean isDirty() {
13403        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
13404    }
13405
13406    /**
13407     * Sets the bottom position of this view relative to its parent. This method is meant to be
13408     * called by the layout system and should not generally be called otherwise, because the
13409     * property may be changed at any time by the layout.
13410     *
13411     * @param bottom The bottom of this view, in pixels.
13412     */
13413    public final void setBottom(int bottom) {
13414        if (bottom != mBottom) {
13415            final boolean matrixIsIdentity = hasIdentityMatrix();
13416            if (matrixIsIdentity) {
13417                if (mAttachInfo != null) {
13418                    int maxBottom;
13419                    if (bottom < mBottom) {
13420                        maxBottom = mBottom;
13421                    } else {
13422                        maxBottom = bottom;
13423                    }
13424                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
13425                }
13426            } else {
13427                // Double-invalidation is necessary to capture view's old and new areas
13428                invalidate(true);
13429            }
13430
13431            int width = mRight - mLeft;
13432            int oldHeight = mBottom - mTop;
13433
13434            mBottom = bottom;
13435            mRenderNode.setBottom(mBottom);
13436
13437            sizeChange(width, mBottom - mTop, width, oldHeight);
13438
13439            if (!matrixIsIdentity) {
13440                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13441                invalidate(true);
13442            }
13443            mBackgroundSizeChanged = true;
13444            if (mForegroundInfo != null) {
13445                mForegroundInfo.mBoundsChanged = true;
13446            }
13447            invalidateParentIfNeeded();
13448            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13449                // View was rejected last time it was drawn by its parent; this may have changed
13450                invalidateParentIfNeeded();
13451            }
13452        }
13453    }
13454
13455    /**
13456     * Left position of this view relative to its parent.
13457     *
13458     * @return The left edge of this view, in pixels.
13459     */
13460    @ViewDebug.CapturedViewProperty
13461    public final int getLeft() {
13462        return mLeft;
13463    }
13464
13465    /**
13466     * Sets the left position of this view relative to its parent. This method is meant to be called
13467     * by the layout system and should not generally be called otherwise, because the property
13468     * may be changed at any time by the layout.
13469     *
13470     * @param left The left of this view, in pixels.
13471     */
13472    public final void setLeft(int left) {
13473        if (left != mLeft) {
13474            final boolean matrixIsIdentity = hasIdentityMatrix();
13475            if (matrixIsIdentity) {
13476                if (mAttachInfo != null) {
13477                    int minLeft;
13478                    int xLoc;
13479                    if (left < mLeft) {
13480                        minLeft = left;
13481                        xLoc = left - mLeft;
13482                    } else {
13483                        minLeft = mLeft;
13484                        xLoc = 0;
13485                    }
13486                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
13487                }
13488            } else {
13489                // Double-invalidation is necessary to capture view's old and new areas
13490                invalidate(true);
13491            }
13492
13493            int oldWidth = mRight - mLeft;
13494            int height = mBottom - mTop;
13495
13496            mLeft = left;
13497            mRenderNode.setLeft(left);
13498
13499            sizeChange(mRight - mLeft, height, oldWidth, height);
13500
13501            if (!matrixIsIdentity) {
13502                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13503                invalidate(true);
13504            }
13505            mBackgroundSizeChanged = true;
13506            if (mForegroundInfo != null) {
13507                mForegroundInfo.mBoundsChanged = true;
13508            }
13509            invalidateParentIfNeeded();
13510            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13511                // View was rejected last time it was drawn by its parent; this may have changed
13512                invalidateParentIfNeeded();
13513            }
13514        }
13515    }
13516
13517    /**
13518     * Right position of this view relative to its parent.
13519     *
13520     * @return The right edge of this view, in pixels.
13521     */
13522    @ViewDebug.CapturedViewProperty
13523    public final int getRight() {
13524        return mRight;
13525    }
13526
13527    /**
13528     * Sets the right position of this view relative to its parent. This method is meant to be called
13529     * by the layout system and should not generally be called otherwise, because the property
13530     * may be changed at any time by the layout.
13531     *
13532     * @param right The right of this view, in pixels.
13533     */
13534    public final void setRight(int right) {
13535        if (right != mRight) {
13536            final boolean matrixIsIdentity = hasIdentityMatrix();
13537            if (matrixIsIdentity) {
13538                if (mAttachInfo != null) {
13539                    int maxRight;
13540                    if (right < mRight) {
13541                        maxRight = mRight;
13542                    } else {
13543                        maxRight = right;
13544                    }
13545                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
13546                }
13547            } else {
13548                // Double-invalidation is necessary to capture view's old and new areas
13549                invalidate(true);
13550            }
13551
13552            int oldWidth = mRight - mLeft;
13553            int height = mBottom - mTop;
13554
13555            mRight = right;
13556            mRenderNode.setRight(mRight);
13557
13558            sizeChange(mRight - mLeft, height, oldWidth, height);
13559
13560            if (!matrixIsIdentity) {
13561                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13562                invalidate(true);
13563            }
13564            mBackgroundSizeChanged = true;
13565            if (mForegroundInfo != null) {
13566                mForegroundInfo.mBoundsChanged = true;
13567            }
13568            invalidateParentIfNeeded();
13569            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13570                // View was rejected last time it was drawn by its parent; this may have changed
13571                invalidateParentIfNeeded();
13572            }
13573        }
13574    }
13575
13576    /**
13577     * The visual x position of this view, in pixels. This is equivalent to the
13578     * {@link #setTranslationX(float) translationX} property plus the current
13579     * {@link #getLeft() left} property.
13580     *
13581     * @return The visual x position of this view, in pixels.
13582     */
13583    @ViewDebug.ExportedProperty(category = "drawing")
13584    public float getX() {
13585        return mLeft + getTranslationX();
13586    }
13587
13588    /**
13589     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
13590     * {@link #setTranslationX(float) translationX} property to be the difference between
13591     * the x value passed in and the current {@link #getLeft() left} property.
13592     *
13593     * @param x The visual x position of this view, in pixels.
13594     */
13595    public void setX(float x) {
13596        setTranslationX(x - mLeft);
13597    }
13598
13599    /**
13600     * The visual y position of this view, in pixels. This is equivalent to the
13601     * {@link #setTranslationY(float) translationY} property plus the current
13602     * {@link #getTop() top} property.
13603     *
13604     * @return The visual y position of this view, in pixels.
13605     */
13606    @ViewDebug.ExportedProperty(category = "drawing")
13607    public float getY() {
13608        return mTop + getTranslationY();
13609    }
13610
13611    /**
13612     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
13613     * {@link #setTranslationY(float) translationY} property to be the difference between
13614     * the y value passed in and the current {@link #getTop() top} property.
13615     *
13616     * @param y The visual y position of this view, in pixels.
13617     */
13618    public void setY(float y) {
13619        setTranslationY(y - mTop);
13620    }
13621
13622    /**
13623     * The visual z position of this view, in pixels. This is equivalent to the
13624     * {@link #setTranslationZ(float) translationZ} property plus the current
13625     * {@link #getElevation() elevation} property.
13626     *
13627     * @return The visual z position of this view, in pixels.
13628     */
13629    @ViewDebug.ExportedProperty(category = "drawing")
13630    public float getZ() {
13631        return getElevation() + getTranslationZ();
13632    }
13633
13634    /**
13635     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
13636     * {@link #setTranslationZ(float) translationZ} property to be the difference between
13637     * the x value passed in and the current {@link #getElevation() elevation} property.
13638     *
13639     * @param z The visual z position of this view, in pixels.
13640     */
13641    public void setZ(float z) {
13642        setTranslationZ(z - getElevation());
13643    }
13644
13645    /**
13646     * The base elevation of this view relative to its parent, in pixels.
13647     *
13648     * @return The base depth position of the view, in pixels.
13649     */
13650    @ViewDebug.ExportedProperty(category = "drawing")
13651    public float getElevation() {
13652        return mRenderNode.getElevation();
13653    }
13654
13655    /**
13656     * Sets the base elevation of this view, in pixels.
13657     *
13658     * @attr ref android.R.styleable#View_elevation
13659     */
13660    public void setElevation(float elevation) {
13661        if (elevation != getElevation()) {
13662            invalidateViewProperty(true, false);
13663            mRenderNode.setElevation(elevation);
13664            invalidateViewProperty(false, true);
13665
13666            invalidateParentIfNeededAndWasQuickRejected();
13667        }
13668    }
13669
13670    /**
13671     * The horizontal location of this view relative to its {@link #getLeft() left} position.
13672     * This position is post-layout, in addition to wherever the object's
13673     * layout placed it.
13674     *
13675     * @return The horizontal position of this view relative to its left position, in pixels.
13676     */
13677    @ViewDebug.ExportedProperty(category = "drawing")
13678    public float getTranslationX() {
13679        return mRenderNode.getTranslationX();
13680    }
13681
13682    /**
13683     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
13684     * This effectively positions the object post-layout, in addition to wherever the object's
13685     * layout placed it.
13686     *
13687     * @param translationX The horizontal position of this view relative to its left position,
13688     * in pixels.
13689     *
13690     * @attr ref android.R.styleable#View_translationX
13691     */
13692    public void setTranslationX(float translationX) {
13693        if (translationX != getTranslationX()) {
13694            invalidateViewProperty(true, false);
13695            mRenderNode.setTranslationX(translationX);
13696            invalidateViewProperty(false, true);
13697
13698            invalidateParentIfNeededAndWasQuickRejected();
13699            notifySubtreeAccessibilityStateChangedIfNeeded();
13700        }
13701    }
13702
13703    /**
13704     * The vertical location of this view relative to its {@link #getTop() top} position.
13705     * This position is post-layout, in addition to wherever the object's
13706     * layout placed it.
13707     *
13708     * @return The vertical position of this view relative to its top position,
13709     * in pixels.
13710     */
13711    @ViewDebug.ExportedProperty(category = "drawing")
13712    public float getTranslationY() {
13713        return mRenderNode.getTranslationY();
13714    }
13715
13716    /**
13717     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
13718     * This effectively positions the object post-layout, in addition to wherever the object's
13719     * layout placed it.
13720     *
13721     * @param translationY The vertical position of this view relative to its top position,
13722     * in pixels.
13723     *
13724     * @attr ref android.R.styleable#View_translationY
13725     */
13726    public void setTranslationY(float translationY) {
13727        if (translationY != getTranslationY()) {
13728            invalidateViewProperty(true, false);
13729            mRenderNode.setTranslationY(translationY);
13730            invalidateViewProperty(false, true);
13731
13732            invalidateParentIfNeededAndWasQuickRejected();
13733            notifySubtreeAccessibilityStateChangedIfNeeded();
13734        }
13735    }
13736
13737    /**
13738     * The depth location of this view relative to its {@link #getElevation() elevation}.
13739     *
13740     * @return The depth of this view relative to its elevation.
13741     */
13742    @ViewDebug.ExportedProperty(category = "drawing")
13743    public float getTranslationZ() {
13744        return mRenderNode.getTranslationZ();
13745    }
13746
13747    /**
13748     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
13749     *
13750     * @attr ref android.R.styleable#View_translationZ
13751     */
13752    public void setTranslationZ(float translationZ) {
13753        if (translationZ != getTranslationZ()) {
13754            invalidateViewProperty(true, false);
13755            mRenderNode.setTranslationZ(translationZ);
13756            invalidateViewProperty(false, true);
13757
13758            invalidateParentIfNeededAndWasQuickRejected();
13759        }
13760    }
13761
13762    /** @hide */
13763    public void setAnimationMatrix(Matrix matrix) {
13764        invalidateViewProperty(true, false);
13765        mRenderNode.setAnimationMatrix(matrix);
13766        invalidateViewProperty(false, true);
13767
13768        invalidateParentIfNeededAndWasQuickRejected();
13769    }
13770
13771    /**
13772     * Returns the current StateListAnimator if exists.
13773     *
13774     * @return StateListAnimator or null if it does not exists
13775     * @see    #setStateListAnimator(android.animation.StateListAnimator)
13776     */
13777    public StateListAnimator getStateListAnimator() {
13778        return mStateListAnimator;
13779    }
13780
13781    /**
13782     * Attaches the provided StateListAnimator to this View.
13783     * <p>
13784     * Any previously attached StateListAnimator will be detached.
13785     *
13786     * @param stateListAnimator The StateListAnimator to update the view
13787     * @see android.animation.StateListAnimator
13788     */
13789    public void setStateListAnimator(StateListAnimator stateListAnimator) {
13790        if (mStateListAnimator == stateListAnimator) {
13791            return;
13792        }
13793        if (mStateListAnimator != null) {
13794            mStateListAnimator.setTarget(null);
13795        }
13796        mStateListAnimator = stateListAnimator;
13797        if (stateListAnimator != null) {
13798            stateListAnimator.setTarget(this);
13799            if (isAttachedToWindow()) {
13800                stateListAnimator.setState(getDrawableState());
13801            }
13802        }
13803    }
13804
13805    /**
13806     * Returns whether the Outline should be used to clip the contents of the View.
13807     * <p>
13808     * Note that this flag will only be respected if the View's Outline returns true from
13809     * {@link Outline#canClip()}.
13810     *
13811     * @see #setOutlineProvider(ViewOutlineProvider)
13812     * @see #setClipToOutline(boolean)
13813     */
13814    public final boolean getClipToOutline() {
13815        return mRenderNode.getClipToOutline();
13816    }
13817
13818    /**
13819     * Sets whether the View's Outline should be used to clip the contents of the View.
13820     * <p>
13821     * Only a single non-rectangular clip can be applied on a View at any time.
13822     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
13823     * circular reveal} animation take priority over Outline clipping, and
13824     * child Outline clipping takes priority over Outline clipping done by a
13825     * parent.
13826     * <p>
13827     * Note that this flag will only be respected if the View's Outline returns true from
13828     * {@link Outline#canClip()}.
13829     *
13830     * @see #setOutlineProvider(ViewOutlineProvider)
13831     * @see #getClipToOutline()
13832     */
13833    public void setClipToOutline(boolean clipToOutline) {
13834        damageInParent();
13835        if (getClipToOutline() != clipToOutline) {
13836            mRenderNode.setClipToOutline(clipToOutline);
13837        }
13838    }
13839
13840    // correspond to the enum values of View_outlineProvider
13841    private static final int PROVIDER_BACKGROUND = 0;
13842    private static final int PROVIDER_NONE = 1;
13843    private static final int PROVIDER_BOUNDS = 2;
13844    private static final int PROVIDER_PADDED_BOUNDS = 3;
13845    private void setOutlineProviderFromAttribute(int providerInt) {
13846        switch (providerInt) {
13847            case PROVIDER_BACKGROUND:
13848                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
13849                break;
13850            case PROVIDER_NONE:
13851                setOutlineProvider(null);
13852                break;
13853            case PROVIDER_BOUNDS:
13854                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13855                break;
13856            case PROVIDER_PADDED_BOUNDS:
13857                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13858                break;
13859        }
13860    }
13861
13862    /**
13863     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13864     * the shape of the shadow it casts, and enables outline clipping.
13865     * <p>
13866     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13867     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13868     * outline provider with this method allows this behavior to be overridden.
13869     * <p>
13870     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13871     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13872     * <p>
13873     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13874     *
13875     * @see #setClipToOutline(boolean)
13876     * @see #getClipToOutline()
13877     * @see #getOutlineProvider()
13878     */
13879    public void setOutlineProvider(ViewOutlineProvider provider) {
13880        mOutlineProvider = provider;
13881        invalidateOutline();
13882    }
13883
13884    /**
13885     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13886     * that defines the shape of the shadow it casts, and enables outline clipping.
13887     *
13888     * @see #setOutlineProvider(ViewOutlineProvider)
13889     */
13890    public ViewOutlineProvider getOutlineProvider() {
13891        return mOutlineProvider;
13892    }
13893
13894    /**
13895     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13896     *
13897     * @see #setOutlineProvider(ViewOutlineProvider)
13898     */
13899    public void invalidateOutline() {
13900        rebuildOutline();
13901
13902        notifySubtreeAccessibilityStateChangedIfNeeded();
13903        invalidateViewProperty(false, false);
13904    }
13905
13906    /**
13907     * Internal version of {@link #invalidateOutline()} which invalidates the
13908     * outline without invalidating the view itself. This is intended to be called from
13909     * within methods in the View class itself which are the result of the view being
13910     * invalidated already. For example, when we are drawing the background of a View,
13911     * we invalidate the outline in case it changed in the meantime, but we do not
13912     * need to invalidate the view because we're already drawing the background as part
13913     * of drawing the view in response to an earlier invalidation of the view.
13914     */
13915    private void rebuildOutline() {
13916        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13917        if (mAttachInfo == null) return;
13918
13919        if (mOutlineProvider == null) {
13920            // no provider, remove outline
13921            mRenderNode.setOutline(null);
13922        } else {
13923            final Outline outline = mAttachInfo.mTmpOutline;
13924            outline.setEmpty();
13925            outline.setAlpha(1.0f);
13926
13927            mOutlineProvider.getOutline(this, outline);
13928            mRenderNode.setOutline(outline);
13929        }
13930    }
13931
13932    /**
13933     * HierarchyViewer only
13934     *
13935     * @hide
13936     */
13937    @ViewDebug.ExportedProperty(category = "drawing")
13938    public boolean hasShadow() {
13939        return mRenderNode.hasShadow();
13940    }
13941
13942
13943    /** @hide */
13944    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13945        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13946        invalidateViewProperty(false, false);
13947    }
13948
13949    /**
13950     * Hit rectangle in parent's coordinates
13951     *
13952     * @param outRect The hit rectangle of the view.
13953     */
13954    public void getHitRect(Rect outRect) {
13955        if (hasIdentityMatrix() || mAttachInfo == null) {
13956            outRect.set(mLeft, mTop, mRight, mBottom);
13957        } else {
13958            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13959            tmpRect.set(0, 0, getWidth(), getHeight());
13960            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13961            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13962                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13963        }
13964    }
13965
13966    /**
13967     * Determines whether the given point, in local coordinates is inside the view.
13968     */
13969    /*package*/ final boolean pointInView(float localX, float localY) {
13970        return pointInView(localX, localY, 0);
13971    }
13972
13973    /**
13974     * Utility method to determine whether the given point, in local coordinates,
13975     * is inside the view, where the area of the view is expanded by the slop factor.
13976     * This method is called while processing touch-move events to determine if the event
13977     * is still within the view.
13978     *
13979     * @hide
13980     */
13981    public boolean pointInView(float localX, float localY, float slop) {
13982        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13983                localY < ((mBottom - mTop) + slop);
13984    }
13985
13986    /**
13987     * When a view has focus and the user navigates away from it, the next view is searched for
13988     * starting from the rectangle filled in by this method.
13989     *
13990     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13991     * of the view.  However, if your view maintains some idea of internal selection,
13992     * such as a cursor, or a selected row or column, you should override this method and
13993     * fill in a more specific rectangle.
13994     *
13995     * @param r The rectangle to fill in, in this view's coordinates.
13996     */
13997    public void getFocusedRect(Rect r) {
13998        getDrawingRect(r);
13999    }
14000
14001    /**
14002     * If some part of this view is not clipped by any of its parents, then
14003     * return that area in r in global (root) coordinates. To convert r to local
14004     * coordinates (without taking possible View rotations into account), offset
14005     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
14006     * If the view is completely clipped or translated out, return false.
14007     *
14008     * @param r If true is returned, r holds the global coordinates of the
14009     *        visible portion of this view.
14010     * @param globalOffset If true is returned, globalOffset holds the dx,dy
14011     *        between this view and its root. globalOffet may be null.
14012     * @return true if r is non-empty (i.e. part of the view is visible at the
14013     *         root level.
14014     */
14015    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
14016        int width = mRight - mLeft;
14017        int height = mBottom - mTop;
14018        if (width > 0 && height > 0) {
14019            r.set(0, 0, width, height);
14020            if (globalOffset != null) {
14021                globalOffset.set(-mScrollX, -mScrollY);
14022            }
14023            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
14024        }
14025        return false;
14026    }
14027
14028    public final boolean getGlobalVisibleRect(Rect r) {
14029        return getGlobalVisibleRect(r, null);
14030    }
14031
14032    public final boolean getLocalVisibleRect(Rect r) {
14033        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
14034        if (getGlobalVisibleRect(r, offset)) {
14035            r.offset(-offset.x, -offset.y); // make r local
14036            return true;
14037        }
14038        return false;
14039    }
14040
14041    /**
14042     * Offset this view's vertical location by the specified number of pixels.
14043     *
14044     * @param offset the number of pixels to offset the view by
14045     */
14046    public void offsetTopAndBottom(int offset) {
14047        if (offset != 0) {
14048            final boolean matrixIsIdentity = hasIdentityMatrix();
14049            if (matrixIsIdentity) {
14050                if (isHardwareAccelerated()) {
14051                    invalidateViewProperty(false, false);
14052                } else {
14053                    final ViewParent p = mParent;
14054                    if (p != null && mAttachInfo != null) {
14055                        final Rect r = mAttachInfo.mTmpInvalRect;
14056                        int minTop;
14057                        int maxBottom;
14058                        int yLoc;
14059                        if (offset < 0) {
14060                            minTop = mTop + offset;
14061                            maxBottom = mBottom;
14062                            yLoc = offset;
14063                        } else {
14064                            minTop = mTop;
14065                            maxBottom = mBottom + offset;
14066                            yLoc = 0;
14067                        }
14068                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
14069                        p.invalidateChild(this, r);
14070                    }
14071                }
14072            } else {
14073                invalidateViewProperty(false, false);
14074            }
14075
14076            mTop += offset;
14077            mBottom += offset;
14078            mRenderNode.offsetTopAndBottom(offset);
14079            if (isHardwareAccelerated()) {
14080                invalidateViewProperty(false, false);
14081                invalidateParentIfNeededAndWasQuickRejected();
14082            } else {
14083                if (!matrixIsIdentity) {
14084                    invalidateViewProperty(false, true);
14085                }
14086                invalidateParentIfNeeded();
14087            }
14088            notifySubtreeAccessibilityStateChangedIfNeeded();
14089        }
14090    }
14091
14092    /**
14093     * Offset this view's horizontal location by the specified amount of pixels.
14094     *
14095     * @param offset the number of pixels to offset the view by
14096     */
14097    public void offsetLeftAndRight(int offset) {
14098        if (offset != 0) {
14099            final boolean matrixIsIdentity = hasIdentityMatrix();
14100            if (matrixIsIdentity) {
14101                if (isHardwareAccelerated()) {
14102                    invalidateViewProperty(false, false);
14103                } else {
14104                    final ViewParent p = mParent;
14105                    if (p != null && mAttachInfo != null) {
14106                        final Rect r = mAttachInfo.mTmpInvalRect;
14107                        int minLeft;
14108                        int maxRight;
14109                        if (offset < 0) {
14110                            minLeft = mLeft + offset;
14111                            maxRight = mRight;
14112                        } else {
14113                            minLeft = mLeft;
14114                            maxRight = mRight + offset;
14115                        }
14116                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
14117                        p.invalidateChild(this, r);
14118                    }
14119                }
14120            } else {
14121                invalidateViewProperty(false, false);
14122            }
14123
14124            mLeft += offset;
14125            mRight += offset;
14126            mRenderNode.offsetLeftAndRight(offset);
14127            if (isHardwareAccelerated()) {
14128                invalidateViewProperty(false, false);
14129                invalidateParentIfNeededAndWasQuickRejected();
14130            } else {
14131                if (!matrixIsIdentity) {
14132                    invalidateViewProperty(false, true);
14133                }
14134                invalidateParentIfNeeded();
14135            }
14136            notifySubtreeAccessibilityStateChangedIfNeeded();
14137        }
14138    }
14139
14140    /**
14141     * Get the LayoutParams associated with this view. All views should have
14142     * layout parameters. These supply parameters to the <i>parent</i> of this
14143     * view specifying how it should be arranged. There are many subclasses of
14144     * ViewGroup.LayoutParams, and these correspond to the different subclasses
14145     * of ViewGroup that are responsible for arranging their children.
14146     *
14147     * This method may return null if this View is not attached to a parent
14148     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
14149     * was not invoked successfully. When a View is attached to a parent
14150     * ViewGroup, this method must not return null.
14151     *
14152     * @return The LayoutParams associated with this view, or null if no
14153     *         parameters have been set yet
14154     */
14155    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
14156    public ViewGroup.LayoutParams getLayoutParams() {
14157        return mLayoutParams;
14158    }
14159
14160    /**
14161     * Set the layout parameters associated with this view. These supply
14162     * parameters to the <i>parent</i> of this view specifying how it should be
14163     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
14164     * correspond to the different subclasses of ViewGroup that are responsible
14165     * for arranging their children.
14166     *
14167     * @param params The layout parameters for this view, cannot be null
14168     */
14169    public void setLayoutParams(ViewGroup.LayoutParams params) {
14170        if (params == null) {
14171            throw new NullPointerException("Layout parameters cannot be null");
14172        }
14173        mLayoutParams = params;
14174        resolveLayoutParams();
14175        if (mParent instanceof ViewGroup) {
14176            ((ViewGroup) mParent).onSetLayoutParams(this, params);
14177        }
14178        requestLayout();
14179    }
14180
14181    /**
14182     * Resolve the layout parameters depending on the resolved layout direction
14183     *
14184     * @hide
14185     */
14186    public void resolveLayoutParams() {
14187        if (mLayoutParams != null) {
14188            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
14189        }
14190    }
14191
14192    /**
14193     * Set the scrolled position of your view. This will cause a call to
14194     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14195     * invalidated.
14196     * @param x the x position to scroll to
14197     * @param y the y position to scroll to
14198     */
14199    public void scrollTo(int x, int y) {
14200        if (mScrollX != x || mScrollY != y) {
14201            int oldX = mScrollX;
14202            int oldY = mScrollY;
14203            mScrollX = x;
14204            mScrollY = y;
14205            invalidateParentCaches();
14206            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
14207            if (!awakenScrollBars()) {
14208                postInvalidateOnAnimation();
14209            }
14210        }
14211    }
14212
14213    /**
14214     * Move the scrolled position of your view. This will cause a call to
14215     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14216     * invalidated.
14217     * @param x the amount of pixels to scroll by horizontally
14218     * @param y the amount of pixels to scroll by vertically
14219     */
14220    public void scrollBy(int x, int y) {
14221        scrollTo(mScrollX + x, mScrollY + y);
14222    }
14223
14224    /**
14225     * <p>Trigger the scrollbars to draw. When invoked this method starts an
14226     * animation to fade the scrollbars out after a default delay. If a subclass
14227     * provides animated scrolling, the start delay should equal the duration
14228     * of the scrolling animation.</p>
14229     *
14230     * <p>The animation starts only if at least one of the scrollbars is
14231     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
14232     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14233     * this method returns true, and false otherwise. If the animation is
14234     * started, this method calls {@link #invalidate()}; in that case the
14235     * caller should not call {@link #invalidate()}.</p>
14236     *
14237     * <p>This method should be invoked every time a subclass directly updates
14238     * the scroll parameters.</p>
14239     *
14240     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
14241     * and {@link #scrollTo(int, int)}.</p>
14242     *
14243     * @return true if the animation is played, false otherwise
14244     *
14245     * @see #awakenScrollBars(int)
14246     * @see #scrollBy(int, int)
14247     * @see #scrollTo(int, int)
14248     * @see #isHorizontalScrollBarEnabled()
14249     * @see #isVerticalScrollBarEnabled()
14250     * @see #setHorizontalScrollBarEnabled(boolean)
14251     * @see #setVerticalScrollBarEnabled(boolean)
14252     */
14253    protected boolean awakenScrollBars() {
14254        return mScrollCache != null &&
14255                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
14256    }
14257
14258    /**
14259     * Trigger the scrollbars to draw.
14260     * This method differs from awakenScrollBars() only in its default duration.
14261     * initialAwakenScrollBars() will show the scroll bars for longer than
14262     * usual to give the user more of a chance to notice them.
14263     *
14264     * @return true if the animation is played, false otherwise.
14265     */
14266    private boolean initialAwakenScrollBars() {
14267        return mScrollCache != null &&
14268                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
14269    }
14270
14271    /**
14272     * <p>
14273     * Trigger the scrollbars to draw. When invoked this method starts an
14274     * animation to fade the scrollbars out after a fixed delay. If a subclass
14275     * provides animated scrolling, the start delay should equal the duration of
14276     * the scrolling animation.
14277     * </p>
14278     *
14279     * <p>
14280     * The animation starts only if at least one of the scrollbars is enabled,
14281     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14282     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14283     * this method returns true, and false otherwise. If the animation is
14284     * started, this method calls {@link #invalidate()}; in that case the caller
14285     * should not call {@link #invalidate()}.
14286     * </p>
14287     *
14288     * <p>
14289     * This method should be invoked every time a subclass directly updates the
14290     * scroll parameters.
14291     * </p>
14292     *
14293     * @param startDelay the delay, in milliseconds, after which the animation
14294     *        should start; when the delay is 0, the animation starts
14295     *        immediately
14296     * @return true if the animation is played, false otherwise
14297     *
14298     * @see #scrollBy(int, int)
14299     * @see #scrollTo(int, int)
14300     * @see #isHorizontalScrollBarEnabled()
14301     * @see #isVerticalScrollBarEnabled()
14302     * @see #setHorizontalScrollBarEnabled(boolean)
14303     * @see #setVerticalScrollBarEnabled(boolean)
14304     */
14305    protected boolean awakenScrollBars(int startDelay) {
14306        return awakenScrollBars(startDelay, true);
14307    }
14308
14309    /**
14310     * <p>
14311     * Trigger the scrollbars to draw. When invoked this method starts an
14312     * animation to fade the scrollbars out after a fixed delay. If a subclass
14313     * provides animated scrolling, the start delay should equal the duration of
14314     * the scrolling animation.
14315     * </p>
14316     *
14317     * <p>
14318     * The animation starts only if at least one of the scrollbars is enabled,
14319     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14320     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14321     * this method returns true, and false otherwise. If the animation is
14322     * started, this method calls {@link #invalidate()} if the invalidate parameter
14323     * is set to true; in that case the caller
14324     * should not call {@link #invalidate()}.
14325     * </p>
14326     *
14327     * <p>
14328     * This method should be invoked every time a subclass directly updates the
14329     * scroll parameters.
14330     * </p>
14331     *
14332     * @param startDelay the delay, in milliseconds, after which the animation
14333     *        should start; when the delay is 0, the animation starts
14334     *        immediately
14335     *
14336     * @param invalidate Whether this method should call invalidate
14337     *
14338     * @return true if the animation is played, false otherwise
14339     *
14340     * @see #scrollBy(int, int)
14341     * @see #scrollTo(int, int)
14342     * @see #isHorizontalScrollBarEnabled()
14343     * @see #isVerticalScrollBarEnabled()
14344     * @see #setHorizontalScrollBarEnabled(boolean)
14345     * @see #setVerticalScrollBarEnabled(boolean)
14346     */
14347    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
14348        final ScrollabilityCache scrollCache = mScrollCache;
14349
14350        if (scrollCache == null || !scrollCache.fadeScrollBars) {
14351            return false;
14352        }
14353
14354        if (scrollCache.scrollBar == null) {
14355            scrollCache.scrollBar = new ScrollBarDrawable();
14356            scrollCache.scrollBar.setState(getDrawableState());
14357            scrollCache.scrollBar.setCallback(this);
14358        }
14359
14360        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
14361
14362            if (invalidate) {
14363                // Invalidate to show the scrollbars
14364                postInvalidateOnAnimation();
14365            }
14366
14367            if (scrollCache.state == ScrollabilityCache.OFF) {
14368                // FIXME: this is copied from WindowManagerService.
14369                // We should get this value from the system when it
14370                // is possible to do so.
14371                final int KEY_REPEAT_FIRST_DELAY = 750;
14372                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
14373            }
14374
14375            // Tell mScrollCache when we should start fading. This may
14376            // extend the fade start time if one was already scheduled
14377            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
14378            scrollCache.fadeStartTime = fadeStartTime;
14379            scrollCache.state = ScrollabilityCache.ON;
14380
14381            // Schedule our fader to run, unscheduling any old ones first
14382            if (mAttachInfo != null) {
14383                mAttachInfo.mHandler.removeCallbacks(scrollCache);
14384                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
14385            }
14386
14387            return true;
14388        }
14389
14390        return false;
14391    }
14392
14393    /**
14394     * Do not invalidate views which are not visible and which are not running an animation. They
14395     * will not get drawn and they should not set dirty flags as if they will be drawn
14396     */
14397    private boolean skipInvalidate() {
14398        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
14399                (!(mParent instanceof ViewGroup) ||
14400                        !((ViewGroup) mParent).isViewTransitioning(this));
14401    }
14402
14403    /**
14404     * Mark the area defined by dirty as needing to be drawn. If the view is
14405     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14406     * point in the future.
14407     * <p>
14408     * This must be called from a UI thread. To call from a non-UI thread, call
14409     * {@link #postInvalidate()}.
14410     * <p>
14411     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
14412     * {@code dirty}.
14413     *
14414     * @param dirty the rectangle representing the bounds of the dirty region
14415     */
14416    public void invalidate(Rect dirty) {
14417        final int scrollX = mScrollX;
14418        final int scrollY = mScrollY;
14419        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
14420                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
14421    }
14422
14423    /**
14424     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
14425     * coordinates of the dirty rect are relative to the view. If the view is
14426     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14427     * point in the future.
14428     * <p>
14429     * This must be called from a UI thread. To call from a non-UI thread, call
14430     * {@link #postInvalidate()}.
14431     *
14432     * @param l the left position of the dirty region
14433     * @param t the top position of the dirty region
14434     * @param r the right position of the dirty region
14435     * @param b the bottom position of the dirty region
14436     */
14437    public void invalidate(int l, int t, int r, int b) {
14438        final int scrollX = mScrollX;
14439        final int scrollY = mScrollY;
14440        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
14441    }
14442
14443    /**
14444     * Invalidate the whole view. If the view is visible,
14445     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
14446     * the future.
14447     * <p>
14448     * This must be called from a UI thread. To call from a non-UI thread, call
14449     * {@link #postInvalidate()}.
14450     */
14451    public void invalidate() {
14452        invalidate(true);
14453    }
14454
14455    /**
14456     * This is where the invalidate() work actually happens. A full invalidate()
14457     * causes the drawing cache to be invalidated, but this function can be
14458     * called with invalidateCache set to false to skip that invalidation step
14459     * for cases that do not need it (for example, a component that remains at
14460     * the same dimensions with the same content).
14461     *
14462     * @param invalidateCache Whether the drawing cache for this view should be
14463     *            invalidated as well. This is usually true for a full
14464     *            invalidate, but may be set to false if the View's contents or
14465     *            dimensions have not changed.
14466     * @hide
14467     */
14468    public void invalidate(boolean invalidateCache) {
14469        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
14470    }
14471
14472    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
14473            boolean fullInvalidate) {
14474        if (mGhostView != null) {
14475            mGhostView.invalidate(true);
14476            return;
14477        }
14478
14479        if (skipInvalidate()) {
14480            return;
14481        }
14482
14483        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
14484                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
14485                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
14486                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
14487            if (fullInvalidate) {
14488                mLastIsOpaque = isOpaque();
14489                mPrivateFlags &= ~PFLAG_DRAWN;
14490            }
14491
14492            mPrivateFlags |= PFLAG_DIRTY;
14493
14494            if (invalidateCache) {
14495                mPrivateFlags |= PFLAG_INVALIDATED;
14496                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14497            }
14498
14499            // Propagate the damage rectangle to the parent view.
14500            final AttachInfo ai = mAttachInfo;
14501            final ViewParent p = mParent;
14502            if (p != null && ai != null && l < r && t < b) {
14503                final Rect damage = ai.mTmpInvalRect;
14504                damage.set(l, t, r, b);
14505                p.invalidateChild(this, damage);
14506            }
14507
14508            // Damage the entire projection receiver, if necessary.
14509            if (mBackground != null && mBackground.isProjected()) {
14510                final View receiver = getProjectionReceiver();
14511                if (receiver != null) {
14512                    receiver.damageInParent();
14513                }
14514            }
14515        }
14516    }
14517
14518    /**
14519     * @return this view's projection receiver, or {@code null} if none exists
14520     */
14521    private View getProjectionReceiver() {
14522        ViewParent p = getParent();
14523        while (p != null && p instanceof View) {
14524            final View v = (View) p;
14525            if (v.isProjectionReceiver()) {
14526                return v;
14527            }
14528            p = p.getParent();
14529        }
14530
14531        return null;
14532    }
14533
14534    /**
14535     * @return whether the view is a projection receiver
14536     */
14537    private boolean isProjectionReceiver() {
14538        return mBackground != null;
14539    }
14540
14541    /**
14542     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
14543     * set any flags or handle all of the cases handled by the default invalidation methods.
14544     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
14545     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
14546     * walk up the hierarchy, transforming the dirty rect as necessary.
14547     *
14548     * The method also handles normal invalidation logic if display list properties are not
14549     * being used in this view. The invalidateParent and forceRedraw flags are used by that
14550     * backup approach, to handle these cases used in the various property-setting methods.
14551     *
14552     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
14553     * are not being used in this view
14554     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
14555     * list properties are not being used in this view
14556     */
14557    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
14558        if (!isHardwareAccelerated()
14559                || !mRenderNode.isValid()
14560                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
14561            if (invalidateParent) {
14562                invalidateParentCaches();
14563            }
14564            if (forceRedraw) {
14565                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14566            }
14567            invalidate(false);
14568        } else {
14569            damageInParent();
14570        }
14571    }
14572
14573    /**
14574     * Tells the parent view to damage this view's bounds.
14575     *
14576     * @hide
14577     */
14578    protected void damageInParent() {
14579        if (mParent != null && mAttachInfo != null) {
14580            mParent.onDescendantInvalidated(this, this);
14581        }
14582    }
14583
14584    /**
14585     * Utility method to transform a given Rect by the current matrix of this view.
14586     */
14587    void transformRect(final Rect rect) {
14588        if (!getMatrix().isIdentity()) {
14589            RectF boundingRect = mAttachInfo.mTmpTransformRect;
14590            boundingRect.set(rect);
14591            getMatrix().mapRect(boundingRect);
14592            rect.set((int) Math.floor(boundingRect.left),
14593                    (int) Math.floor(boundingRect.top),
14594                    (int) Math.ceil(boundingRect.right),
14595                    (int) Math.ceil(boundingRect.bottom));
14596        }
14597    }
14598
14599    /**
14600     * Used to indicate that the parent of this view should clear its caches. This functionality
14601     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14602     * which is necessary when various parent-managed properties of the view change, such as
14603     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
14604     * clears the parent caches and does not causes an invalidate event.
14605     *
14606     * @hide
14607     */
14608    protected void invalidateParentCaches() {
14609        if (mParent instanceof View) {
14610            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
14611        }
14612    }
14613
14614    /**
14615     * Used to indicate that the parent of this view should be invalidated. This functionality
14616     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14617     * which is necessary when various parent-managed properties of the view change, such as
14618     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
14619     * an invalidation event to the parent.
14620     *
14621     * @hide
14622     */
14623    protected void invalidateParentIfNeeded() {
14624        if (isHardwareAccelerated() && mParent instanceof View) {
14625            ((View) mParent).invalidate(true);
14626        }
14627    }
14628
14629    /**
14630     * @hide
14631     */
14632    protected void invalidateParentIfNeededAndWasQuickRejected() {
14633        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
14634            // View was rejected last time it was drawn by its parent; this may have changed
14635            invalidateParentIfNeeded();
14636        }
14637    }
14638
14639    /**
14640     * Indicates whether this View is opaque. An opaque View guarantees that it will
14641     * draw all the pixels overlapping its bounds using a fully opaque color.
14642     *
14643     * Subclasses of View should override this method whenever possible to indicate
14644     * whether an instance is opaque. Opaque Views are treated in a special way by
14645     * the View hierarchy, possibly allowing it to perform optimizations during
14646     * invalidate/draw passes.
14647     *
14648     * @return True if this View is guaranteed to be fully opaque, false otherwise.
14649     */
14650    @ViewDebug.ExportedProperty(category = "drawing")
14651    public boolean isOpaque() {
14652        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
14653                getFinalAlpha() >= 1.0f;
14654    }
14655
14656    /**
14657     * @hide
14658     */
14659    protected void computeOpaqueFlags() {
14660        // Opaque if:
14661        //   - Has a background
14662        //   - Background is opaque
14663        //   - Doesn't have scrollbars or scrollbars overlay
14664
14665        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
14666            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
14667        } else {
14668            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
14669        }
14670
14671        final int flags = mViewFlags;
14672        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
14673                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
14674                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
14675            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
14676        } else {
14677            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
14678        }
14679    }
14680
14681    /**
14682     * @hide
14683     */
14684    protected boolean hasOpaqueScrollbars() {
14685        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
14686    }
14687
14688    /**
14689     * @return A handler associated with the thread running the View. This
14690     * handler can be used to pump events in the UI events queue.
14691     */
14692    public Handler getHandler() {
14693        final AttachInfo attachInfo = mAttachInfo;
14694        if (attachInfo != null) {
14695            return attachInfo.mHandler;
14696        }
14697        return null;
14698    }
14699
14700    /**
14701     * Returns the queue of runnable for this view.
14702     *
14703     * @return the queue of runnables for this view
14704     */
14705    private HandlerActionQueue getRunQueue() {
14706        if (mRunQueue == null) {
14707            mRunQueue = new HandlerActionQueue();
14708        }
14709        return mRunQueue;
14710    }
14711
14712    /**
14713     * Gets the view root associated with the View.
14714     * @return The view root, or null if none.
14715     * @hide
14716     */
14717    public ViewRootImpl getViewRootImpl() {
14718        if (mAttachInfo != null) {
14719            return mAttachInfo.mViewRootImpl;
14720        }
14721        return null;
14722    }
14723
14724    /**
14725     * @hide
14726     */
14727    public ThreadedRenderer getThreadedRenderer() {
14728        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
14729    }
14730
14731    /**
14732     * <p>Causes the Runnable to be added to the message queue.
14733     * The runnable will be run on the user interface thread.</p>
14734     *
14735     * @param action The Runnable that will be executed.
14736     *
14737     * @return Returns true if the Runnable was successfully placed in to the
14738     *         message queue.  Returns false on failure, usually because the
14739     *         looper processing the message queue is exiting.
14740     *
14741     * @see #postDelayed
14742     * @see #removeCallbacks
14743     */
14744    public boolean post(Runnable action) {
14745        final AttachInfo attachInfo = mAttachInfo;
14746        if (attachInfo != null) {
14747            return attachInfo.mHandler.post(action);
14748        }
14749
14750        // Postpone the runnable until we know on which thread it needs to run.
14751        // Assume that the runnable will be successfully placed after attach.
14752        getRunQueue().post(action);
14753        return true;
14754    }
14755
14756    /**
14757     * <p>Causes the Runnable to be added to the message queue, to be run
14758     * after the specified amount of time elapses.
14759     * The runnable will be run on the user interface thread.</p>
14760     *
14761     * @param action The Runnable that will be executed.
14762     * @param delayMillis The delay (in milliseconds) until the Runnable
14763     *        will be executed.
14764     *
14765     * @return true if the Runnable was successfully placed in to the
14766     *         message queue.  Returns false on failure, usually because the
14767     *         looper processing the message queue is exiting.  Note that a
14768     *         result of true does not mean the Runnable will be processed --
14769     *         if the looper is quit before the delivery time of the message
14770     *         occurs then the message will be dropped.
14771     *
14772     * @see #post
14773     * @see #removeCallbacks
14774     */
14775    public boolean postDelayed(Runnable action, long delayMillis) {
14776        final AttachInfo attachInfo = mAttachInfo;
14777        if (attachInfo != null) {
14778            return attachInfo.mHandler.postDelayed(action, delayMillis);
14779        }
14780
14781        // Postpone the runnable until we know on which thread it needs to run.
14782        // Assume that the runnable will be successfully placed after attach.
14783        getRunQueue().postDelayed(action, delayMillis);
14784        return true;
14785    }
14786
14787    /**
14788     * <p>Causes the Runnable to execute on the next animation time step.
14789     * The runnable will be run on the user interface thread.</p>
14790     *
14791     * @param action The Runnable that will be executed.
14792     *
14793     * @see #postOnAnimationDelayed
14794     * @see #removeCallbacks
14795     */
14796    public void postOnAnimation(Runnable action) {
14797        final AttachInfo attachInfo = mAttachInfo;
14798        if (attachInfo != null) {
14799            attachInfo.mViewRootImpl.mChoreographer.postCallback(
14800                    Choreographer.CALLBACK_ANIMATION, action, null);
14801        } else {
14802            // Postpone the runnable until we know
14803            // on which thread it needs to run.
14804            getRunQueue().post(action);
14805        }
14806    }
14807
14808    /**
14809     * <p>Causes the Runnable to execute on the next animation time step,
14810     * after the specified amount of time elapses.
14811     * The runnable will be run on the user interface thread.</p>
14812     *
14813     * @param action The Runnable that will be executed.
14814     * @param delayMillis The delay (in milliseconds) until the Runnable
14815     *        will be executed.
14816     *
14817     * @see #postOnAnimation
14818     * @see #removeCallbacks
14819     */
14820    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14821        final AttachInfo attachInfo = mAttachInfo;
14822        if (attachInfo != null) {
14823            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14824                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14825        } else {
14826            // Postpone the runnable until we know
14827            // on which thread it needs to run.
14828            getRunQueue().postDelayed(action, delayMillis);
14829        }
14830    }
14831
14832    /**
14833     * <p>Removes the specified Runnable from the message queue.</p>
14834     *
14835     * @param action The Runnable to remove from the message handling queue
14836     *
14837     * @return true if this view could ask the Handler to remove the Runnable,
14838     *         false otherwise. When the returned value is true, the Runnable
14839     *         may or may not have been actually removed from the message queue
14840     *         (for instance, if the Runnable was not in the queue already.)
14841     *
14842     * @see #post
14843     * @see #postDelayed
14844     * @see #postOnAnimation
14845     * @see #postOnAnimationDelayed
14846     */
14847    public boolean removeCallbacks(Runnable action) {
14848        if (action != null) {
14849            final AttachInfo attachInfo = mAttachInfo;
14850            if (attachInfo != null) {
14851                attachInfo.mHandler.removeCallbacks(action);
14852                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14853                        Choreographer.CALLBACK_ANIMATION, action, null);
14854            }
14855            getRunQueue().removeCallbacks(action);
14856        }
14857        return true;
14858    }
14859
14860    /**
14861     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14862     * Use this to invalidate the View from a non-UI thread.</p>
14863     *
14864     * <p>This method can be invoked from outside of the UI thread
14865     * only when this View is attached to a window.</p>
14866     *
14867     * @see #invalidate()
14868     * @see #postInvalidateDelayed(long)
14869     */
14870    public void postInvalidate() {
14871        postInvalidateDelayed(0);
14872    }
14873
14874    /**
14875     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14876     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14877     *
14878     * <p>This method can be invoked from outside of the UI thread
14879     * only when this View is attached to a window.</p>
14880     *
14881     * @param left The left coordinate of the rectangle to invalidate.
14882     * @param top The top coordinate of the rectangle to invalidate.
14883     * @param right The right coordinate of the rectangle to invalidate.
14884     * @param bottom The bottom coordinate of the rectangle to invalidate.
14885     *
14886     * @see #invalidate(int, int, int, int)
14887     * @see #invalidate(Rect)
14888     * @see #postInvalidateDelayed(long, int, int, int, int)
14889     */
14890    public void postInvalidate(int left, int top, int right, int bottom) {
14891        postInvalidateDelayed(0, left, top, right, bottom);
14892    }
14893
14894    /**
14895     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14896     * loop. Waits for the specified amount of time.</p>
14897     *
14898     * <p>This method can be invoked from outside of the UI thread
14899     * only when this View is attached to a window.</p>
14900     *
14901     * @param delayMilliseconds the duration in milliseconds to delay the
14902     *         invalidation by
14903     *
14904     * @see #invalidate()
14905     * @see #postInvalidate()
14906     */
14907    public void postInvalidateDelayed(long delayMilliseconds) {
14908        // We try only with the AttachInfo because there's no point in invalidating
14909        // if we are not attached to our window
14910        final AttachInfo attachInfo = mAttachInfo;
14911        if (attachInfo != null) {
14912            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14913        }
14914    }
14915
14916    /**
14917     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14918     * through the event loop. Waits for the specified amount of time.</p>
14919     *
14920     * <p>This method can be invoked from outside of the UI thread
14921     * only when this View is attached to a window.</p>
14922     *
14923     * @param delayMilliseconds the duration in milliseconds to delay the
14924     *         invalidation by
14925     * @param left The left coordinate of the rectangle to invalidate.
14926     * @param top The top coordinate of the rectangle to invalidate.
14927     * @param right The right coordinate of the rectangle to invalidate.
14928     * @param bottom The bottom coordinate of the rectangle to invalidate.
14929     *
14930     * @see #invalidate(int, int, int, int)
14931     * @see #invalidate(Rect)
14932     * @see #postInvalidate(int, int, int, int)
14933     */
14934    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14935            int right, int bottom) {
14936
14937        // We try only with the AttachInfo because there's no point in invalidating
14938        // if we are not attached to our window
14939        final AttachInfo attachInfo = mAttachInfo;
14940        if (attachInfo != null) {
14941            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14942            info.target = this;
14943            info.left = left;
14944            info.top = top;
14945            info.right = right;
14946            info.bottom = bottom;
14947
14948            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14949        }
14950    }
14951
14952    /**
14953     * <p>Cause an invalidate to happen on the next animation time step, typically the
14954     * next display frame.</p>
14955     *
14956     * <p>This method can be invoked from outside of the UI thread
14957     * only when this View is attached to a window.</p>
14958     *
14959     * @see #invalidate()
14960     */
14961    public void postInvalidateOnAnimation() {
14962        // We try only with the AttachInfo because there's no point in invalidating
14963        // if we are not attached to our window
14964        final AttachInfo attachInfo = mAttachInfo;
14965        if (attachInfo != null) {
14966            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14967        }
14968    }
14969
14970    /**
14971     * <p>Cause an invalidate of the specified area to happen on the next animation
14972     * time step, typically the next display frame.</p>
14973     *
14974     * <p>This method can be invoked from outside of the UI thread
14975     * only when this View is attached to a window.</p>
14976     *
14977     * @param left The left coordinate of the rectangle to invalidate.
14978     * @param top The top coordinate of the rectangle to invalidate.
14979     * @param right The right coordinate of the rectangle to invalidate.
14980     * @param bottom The bottom coordinate of the rectangle to invalidate.
14981     *
14982     * @see #invalidate(int, int, int, int)
14983     * @see #invalidate(Rect)
14984     */
14985    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14986        // We try only with the AttachInfo because there's no point in invalidating
14987        // if we are not attached to our window
14988        final AttachInfo attachInfo = mAttachInfo;
14989        if (attachInfo != null) {
14990            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14991            info.target = this;
14992            info.left = left;
14993            info.top = top;
14994            info.right = right;
14995            info.bottom = bottom;
14996
14997            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14998        }
14999    }
15000
15001    /**
15002     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
15003     * This event is sent at most once every
15004     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
15005     */
15006    private void postSendViewScrolledAccessibilityEventCallback() {
15007        if (mSendViewScrolledAccessibilityEvent == null) {
15008            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
15009        }
15010        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
15011            mSendViewScrolledAccessibilityEvent.mIsPending = true;
15012            postDelayed(mSendViewScrolledAccessibilityEvent,
15013                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
15014        }
15015    }
15016
15017    /**
15018     * Called by a parent to request that a child update its values for mScrollX
15019     * and mScrollY if necessary. This will typically be done if the child is
15020     * animating a scroll using a {@link android.widget.Scroller Scroller}
15021     * object.
15022     */
15023    public void computeScroll() {
15024    }
15025
15026    /**
15027     * <p>Indicate whether the horizontal edges are faded when the view is
15028     * scrolled horizontally.</p>
15029     *
15030     * @return true if the horizontal edges should are faded on scroll, false
15031     *         otherwise
15032     *
15033     * @see #setHorizontalFadingEdgeEnabled(boolean)
15034     *
15035     * @attr ref android.R.styleable#View_requiresFadingEdge
15036     */
15037    public boolean isHorizontalFadingEdgeEnabled() {
15038        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
15039    }
15040
15041    /**
15042     * <p>Define whether the horizontal edges should be faded when this view
15043     * is scrolled horizontally.</p>
15044     *
15045     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
15046     *                                    be faded when the view is scrolled
15047     *                                    horizontally
15048     *
15049     * @see #isHorizontalFadingEdgeEnabled()
15050     *
15051     * @attr ref android.R.styleable#View_requiresFadingEdge
15052     */
15053    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
15054        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
15055            if (horizontalFadingEdgeEnabled) {
15056                initScrollCache();
15057            }
15058
15059            mViewFlags ^= FADING_EDGE_HORIZONTAL;
15060        }
15061    }
15062
15063    /**
15064     * <p>Indicate whether the vertical edges are faded when the view is
15065     * scrolled horizontally.</p>
15066     *
15067     * @return true if the vertical edges should are faded on scroll, false
15068     *         otherwise
15069     *
15070     * @see #setVerticalFadingEdgeEnabled(boolean)
15071     *
15072     * @attr ref android.R.styleable#View_requiresFadingEdge
15073     */
15074    public boolean isVerticalFadingEdgeEnabled() {
15075        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
15076    }
15077
15078    /**
15079     * <p>Define whether the vertical edges should be faded when this view
15080     * is scrolled vertically.</p>
15081     *
15082     * @param verticalFadingEdgeEnabled true if the vertical edges should
15083     *                                  be faded when the view is scrolled
15084     *                                  vertically
15085     *
15086     * @see #isVerticalFadingEdgeEnabled()
15087     *
15088     * @attr ref android.R.styleable#View_requiresFadingEdge
15089     */
15090    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
15091        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
15092            if (verticalFadingEdgeEnabled) {
15093                initScrollCache();
15094            }
15095
15096            mViewFlags ^= FADING_EDGE_VERTICAL;
15097        }
15098    }
15099
15100    /**
15101     * Returns the strength, or intensity, of the top faded edge. The strength is
15102     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15103     * returns 0.0 or 1.0 but no value in between.
15104     *
15105     * Subclasses should override this method to provide a smoother fade transition
15106     * when scrolling occurs.
15107     *
15108     * @return the intensity of the top fade as a float between 0.0f and 1.0f
15109     */
15110    protected float getTopFadingEdgeStrength() {
15111        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
15112    }
15113
15114    /**
15115     * Returns the strength, or intensity, of the bottom faded edge. The strength is
15116     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15117     * returns 0.0 or 1.0 but no value in between.
15118     *
15119     * Subclasses should override this method to provide a smoother fade transition
15120     * when scrolling occurs.
15121     *
15122     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
15123     */
15124    protected float getBottomFadingEdgeStrength() {
15125        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
15126                computeVerticalScrollRange() ? 1.0f : 0.0f;
15127    }
15128
15129    /**
15130     * Returns the strength, or intensity, of the left faded edge. The strength is
15131     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15132     * returns 0.0 or 1.0 but no value in between.
15133     *
15134     * Subclasses should override this method to provide a smoother fade transition
15135     * when scrolling occurs.
15136     *
15137     * @return the intensity of the left fade as a float between 0.0f and 1.0f
15138     */
15139    protected float getLeftFadingEdgeStrength() {
15140        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
15141    }
15142
15143    /**
15144     * Returns the strength, or intensity, of the right faded edge. The strength is
15145     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15146     * returns 0.0 or 1.0 but no value in between.
15147     *
15148     * Subclasses should override this method to provide a smoother fade transition
15149     * when scrolling occurs.
15150     *
15151     * @return the intensity of the right fade as a float between 0.0f and 1.0f
15152     */
15153    protected float getRightFadingEdgeStrength() {
15154        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
15155                computeHorizontalScrollRange() ? 1.0f : 0.0f;
15156    }
15157
15158    /**
15159     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
15160     * scrollbar is not drawn by default.</p>
15161     *
15162     * @return true if the horizontal scrollbar should be painted, false
15163     *         otherwise
15164     *
15165     * @see #setHorizontalScrollBarEnabled(boolean)
15166     */
15167    public boolean isHorizontalScrollBarEnabled() {
15168        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
15169    }
15170
15171    /**
15172     * <p>Define whether the horizontal scrollbar should be drawn or not. The
15173     * scrollbar is not drawn by default.</p>
15174     *
15175     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
15176     *                                   be painted
15177     *
15178     * @see #isHorizontalScrollBarEnabled()
15179     */
15180    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
15181        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
15182            mViewFlags ^= SCROLLBARS_HORIZONTAL;
15183            computeOpaqueFlags();
15184            resolvePadding();
15185        }
15186    }
15187
15188    /**
15189     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
15190     * scrollbar is not drawn by default.</p>
15191     *
15192     * @return true if the vertical scrollbar should be painted, false
15193     *         otherwise
15194     *
15195     * @see #setVerticalScrollBarEnabled(boolean)
15196     */
15197    public boolean isVerticalScrollBarEnabled() {
15198        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
15199    }
15200
15201    /**
15202     * <p>Define whether the vertical scrollbar should be drawn or not. The
15203     * scrollbar is not drawn by default.</p>
15204     *
15205     * @param verticalScrollBarEnabled true if the vertical scrollbar should
15206     *                                 be painted
15207     *
15208     * @see #isVerticalScrollBarEnabled()
15209     */
15210    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
15211        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
15212            mViewFlags ^= SCROLLBARS_VERTICAL;
15213            computeOpaqueFlags();
15214            resolvePadding();
15215        }
15216    }
15217
15218    /**
15219     * @hide
15220     */
15221    protected void recomputePadding() {
15222        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15223    }
15224
15225    /**
15226     * Define whether scrollbars will fade when the view is not scrolling.
15227     *
15228     * @param fadeScrollbars whether to enable fading
15229     *
15230     * @attr ref android.R.styleable#View_fadeScrollbars
15231     */
15232    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
15233        initScrollCache();
15234        final ScrollabilityCache scrollabilityCache = mScrollCache;
15235        scrollabilityCache.fadeScrollBars = fadeScrollbars;
15236        if (fadeScrollbars) {
15237            scrollabilityCache.state = ScrollabilityCache.OFF;
15238        } else {
15239            scrollabilityCache.state = ScrollabilityCache.ON;
15240        }
15241    }
15242
15243    /**
15244     *
15245     * Returns true if scrollbars will fade when this view is not scrolling
15246     *
15247     * @return true if scrollbar fading is enabled
15248     *
15249     * @attr ref android.R.styleable#View_fadeScrollbars
15250     */
15251    public boolean isScrollbarFadingEnabled() {
15252        return mScrollCache != null && mScrollCache.fadeScrollBars;
15253    }
15254
15255    /**
15256     *
15257     * Returns the delay before scrollbars fade.
15258     *
15259     * @return the delay before scrollbars fade
15260     *
15261     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15262     */
15263    public int getScrollBarDefaultDelayBeforeFade() {
15264        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
15265                mScrollCache.scrollBarDefaultDelayBeforeFade;
15266    }
15267
15268    /**
15269     * Define the delay before scrollbars fade.
15270     *
15271     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
15272     *
15273     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15274     */
15275    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
15276        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
15277    }
15278
15279    /**
15280     *
15281     * Returns the scrollbar fade duration.
15282     *
15283     * @return the scrollbar fade duration, in milliseconds
15284     *
15285     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15286     */
15287    public int getScrollBarFadeDuration() {
15288        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
15289                mScrollCache.scrollBarFadeDuration;
15290    }
15291
15292    /**
15293     * Define the scrollbar fade duration.
15294     *
15295     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
15296     *
15297     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15298     */
15299    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
15300        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
15301    }
15302
15303    /**
15304     *
15305     * Returns the scrollbar size.
15306     *
15307     * @return the scrollbar size
15308     *
15309     * @attr ref android.R.styleable#View_scrollbarSize
15310     */
15311    public int getScrollBarSize() {
15312        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
15313                mScrollCache.scrollBarSize;
15314    }
15315
15316    /**
15317     * Define the scrollbar size.
15318     *
15319     * @param scrollBarSize - the scrollbar size
15320     *
15321     * @attr ref android.R.styleable#View_scrollbarSize
15322     */
15323    public void setScrollBarSize(int scrollBarSize) {
15324        getScrollCache().scrollBarSize = scrollBarSize;
15325    }
15326
15327    /**
15328     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
15329     * inset. When inset, they add to the padding of the view. And the scrollbars
15330     * can be drawn inside the padding area or on the edge of the view. For example,
15331     * if a view has a background drawable and you want to draw the scrollbars
15332     * inside the padding specified by the drawable, you can use
15333     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
15334     * appear at the edge of the view, ignoring the padding, then you can use
15335     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
15336     * @param style the style of the scrollbars. Should be one of
15337     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
15338     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
15339     * @see #SCROLLBARS_INSIDE_OVERLAY
15340     * @see #SCROLLBARS_INSIDE_INSET
15341     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15342     * @see #SCROLLBARS_OUTSIDE_INSET
15343     *
15344     * @attr ref android.R.styleable#View_scrollbarStyle
15345     */
15346    public void setScrollBarStyle(@ScrollBarStyle int style) {
15347        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
15348            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
15349            computeOpaqueFlags();
15350            resolvePadding();
15351        }
15352    }
15353
15354    /**
15355     * <p>Returns the current scrollbar style.</p>
15356     * @return the current scrollbar style
15357     * @see #SCROLLBARS_INSIDE_OVERLAY
15358     * @see #SCROLLBARS_INSIDE_INSET
15359     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15360     * @see #SCROLLBARS_OUTSIDE_INSET
15361     *
15362     * @attr ref android.R.styleable#View_scrollbarStyle
15363     */
15364    @ViewDebug.ExportedProperty(mapping = {
15365            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
15366            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
15367            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
15368            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
15369    })
15370    @ScrollBarStyle
15371    public int getScrollBarStyle() {
15372        return mViewFlags & SCROLLBARS_STYLE_MASK;
15373    }
15374
15375    /**
15376     * <p>Compute the horizontal range that the horizontal scrollbar
15377     * represents.</p>
15378     *
15379     * <p>The range is expressed in arbitrary units that must be the same as the
15380     * units used by {@link #computeHorizontalScrollExtent()} and
15381     * {@link #computeHorizontalScrollOffset()}.</p>
15382     *
15383     * <p>The default range is the drawing width of this view.</p>
15384     *
15385     * @return the total horizontal range represented by the horizontal
15386     *         scrollbar
15387     *
15388     * @see #computeHorizontalScrollExtent()
15389     * @see #computeHorizontalScrollOffset()
15390     * @see android.widget.ScrollBarDrawable
15391     */
15392    protected int computeHorizontalScrollRange() {
15393        return getWidth();
15394    }
15395
15396    /**
15397     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
15398     * within the horizontal range. This value is used to compute the position
15399     * of the thumb within the scrollbar's track.</p>
15400     *
15401     * <p>The range is expressed in arbitrary units that must be the same as the
15402     * units used by {@link #computeHorizontalScrollRange()} and
15403     * {@link #computeHorizontalScrollExtent()}.</p>
15404     *
15405     * <p>The default offset is the scroll offset of this view.</p>
15406     *
15407     * @return the horizontal offset of the scrollbar's thumb
15408     *
15409     * @see #computeHorizontalScrollRange()
15410     * @see #computeHorizontalScrollExtent()
15411     * @see android.widget.ScrollBarDrawable
15412     */
15413    protected int computeHorizontalScrollOffset() {
15414        return mScrollX;
15415    }
15416
15417    /**
15418     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
15419     * within the horizontal range. This value is used to compute the length
15420     * of the thumb within the scrollbar's track.</p>
15421     *
15422     * <p>The range is expressed in arbitrary units that must be the same as the
15423     * units used by {@link #computeHorizontalScrollRange()} and
15424     * {@link #computeHorizontalScrollOffset()}.</p>
15425     *
15426     * <p>The default extent is the drawing width of this view.</p>
15427     *
15428     * @return the horizontal extent of the scrollbar's thumb
15429     *
15430     * @see #computeHorizontalScrollRange()
15431     * @see #computeHorizontalScrollOffset()
15432     * @see android.widget.ScrollBarDrawable
15433     */
15434    protected int computeHorizontalScrollExtent() {
15435        return getWidth();
15436    }
15437
15438    /**
15439     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
15440     *
15441     * <p>The range is expressed in arbitrary units that must be the same as the
15442     * units used by {@link #computeVerticalScrollExtent()} and
15443     * {@link #computeVerticalScrollOffset()}.</p>
15444     *
15445     * @return the total vertical range represented by the vertical scrollbar
15446     *
15447     * <p>The default range is the drawing height of this view.</p>
15448     *
15449     * @see #computeVerticalScrollExtent()
15450     * @see #computeVerticalScrollOffset()
15451     * @see android.widget.ScrollBarDrawable
15452     */
15453    protected int computeVerticalScrollRange() {
15454        return getHeight();
15455    }
15456
15457    /**
15458     * <p>Compute the vertical offset of the vertical scrollbar's thumb
15459     * within the horizontal range. This value is used to compute the position
15460     * of the thumb within the scrollbar's track.</p>
15461     *
15462     * <p>The range is expressed in arbitrary units that must be the same as the
15463     * units used by {@link #computeVerticalScrollRange()} and
15464     * {@link #computeVerticalScrollExtent()}.</p>
15465     *
15466     * <p>The default offset is the scroll offset of this view.</p>
15467     *
15468     * @return the vertical offset of the scrollbar's thumb
15469     *
15470     * @see #computeVerticalScrollRange()
15471     * @see #computeVerticalScrollExtent()
15472     * @see android.widget.ScrollBarDrawable
15473     */
15474    protected int computeVerticalScrollOffset() {
15475        return mScrollY;
15476    }
15477
15478    /**
15479     * <p>Compute the vertical extent of the vertical scrollbar's thumb
15480     * within the vertical range. This value is used to compute the length
15481     * of the thumb within the scrollbar's track.</p>
15482     *
15483     * <p>The range is expressed in arbitrary units that must be the same as the
15484     * units used by {@link #computeVerticalScrollRange()} and
15485     * {@link #computeVerticalScrollOffset()}.</p>
15486     *
15487     * <p>The default extent is the drawing height of this view.</p>
15488     *
15489     * @return the vertical extent of the scrollbar's thumb
15490     *
15491     * @see #computeVerticalScrollRange()
15492     * @see #computeVerticalScrollOffset()
15493     * @see android.widget.ScrollBarDrawable
15494     */
15495    protected int computeVerticalScrollExtent() {
15496        return getHeight();
15497    }
15498
15499    /**
15500     * Check if this view can be scrolled horizontally in a certain direction.
15501     *
15502     * @param direction Negative to check scrolling left, positive to check scrolling right.
15503     * @return true if this view can be scrolled in the specified direction, false otherwise.
15504     */
15505    public boolean canScrollHorizontally(int direction) {
15506        final int offset = computeHorizontalScrollOffset();
15507        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
15508        if (range == 0) return false;
15509        if (direction < 0) {
15510            return offset > 0;
15511        } else {
15512            return offset < range - 1;
15513        }
15514    }
15515
15516    /**
15517     * Check if this view can be scrolled vertically in a certain direction.
15518     *
15519     * @param direction Negative to check scrolling up, positive to check scrolling down.
15520     * @return true if this view can be scrolled in the specified direction, false otherwise.
15521     */
15522    public boolean canScrollVertically(int direction) {
15523        final int offset = computeVerticalScrollOffset();
15524        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
15525        if (range == 0) return false;
15526        if (direction < 0) {
15527            return offset > 0;
15528        } else {
15529            return offset < range - 1;
15530        }
15531    }
15532
15533    void getScrollIndicatorBounds(@NonNull Rect out) {
15534        out.left = mScrollX;
15535        out.right = mScrollX + mRight - mLeft;
15536        out.top = mScrollY;
15537        out.bottom = mScrollY + mBottom - mTop;
15538    }
15539
15540    private void onDrawScrollIndicators(Canvas c) {
15541        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
15542            // No scroll indicators enabled.
15543            return;
15544        }
15545
15546        final Drawable dr = mScrollIndicatorDrawable;
15547        if (dr == null) {
15548            // Scroll indicators aren't supported here.
15549            return;
15550        }
15551
15552        final int h = dr.getIntrinsicHeight();
15553        final int w = dr.getIntrinsicWidth();
15554        final Rect rect = mAttachInfo.mTmpInvalRect;
15555        getScrollIndicatorBounds(rect);
15556
15557        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
15558            final boolean canScrollUp = canScrollVertically(-1);
15559            if (canScrollUp) {
15560                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
15561                dr.draw(c);
15562            }
15563        }
15564
15565        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
15566            final boolean canScrollDown = canScrollVertically(1);
15567            if (canScrollDown) {
15568                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
15569                dr.draw(c);
15570            }
15571        }
15572
15573        final int leftRtl;
15574        final int rightRtl;
15575        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15576            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
15577            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
15578        } else {
15579            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
15580            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
15581        }
15582
15583        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
15584        if ((mPrivateFlags3 & leftMask) != 0) {
15585            final boolean canScrollLeft = canScrollHorizontally(-1);
15586            if (canScrollLeft) {
15587                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
15588                dr.draw(c);
15589            }
15590        }
15591
15592        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
15593        if ((mPrivateFlags3 & rightMask) != 0) {
15594            final boolean canScrollRight = canScrollHorizontally(1);
15595            if (canScrollRight) {
15596                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
15597                dr.draw(c);
15598            }
15599        }
15600    }
15601
15602    private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds,
15603            @Nullable Rect touchBounds) {
15604        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
15605        if (bounds == null) {
15606            return;
15607        }
15608        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15609        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15610                && !isVerticalScrollBarHidden();
15611        final int size = getHorizontalScrollbarHeight();
15612        final int verticalScrollBarGap = drawVerticalScrollBar ?
15613                getVerticalScrollbarWidth() : 0;
15614        final int width = mRight - mLeft;
15615        final int height = mBottom - mTop;
15616        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
15617        bounds.left = mScrollX + (mPaddingLeft & inside);
15618        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
15619        bounds.bottom = bounds.top + size;
15620
15621        if (touchBounds == null) {
15622            return;
15623        }
15624        if (touchBounds != bounds) {
15625            touchBounds.set(bounds);
15626        }
15627        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
15628        if (touchBounds.height() < minTouchTarget) {
15629            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
15630            touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height);
15631            touchBounds.top = touchBounds.bottom - minTouchTarget;
15632        }
15633        if (touchBounds.width() < minTouchTarget) {
15634            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
15635            touchBounds.left -= adjust;
15636            touchBounds.right = touchBounds.left + minTouchTarget;
15637        }
15638    }
15639
15640    private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) {
15641        if (mRoundScrollbarRenderer == null) {
15642            getStraightVerticalScrollBarBounds(bounds, touchBounds);
15643        } else {
15644            getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds);
15645        }
15646    }
15647
15648    private void getRoundVerticalScrollBarBounds(Rect bounds) {
15649        final int width = mRight - mLeft;
15650        final int height = mBottom - mTop;
15651        // Do not take padding into account as we always want the scrollbars
15652        // to hug the screen for round wearable devices.
15653        bounds.left = mScrollX;
15654        bounds.top = mScrollY;
15655        bounds.right = bounds.left + width;
15656        bounds.bottom = mScrollY + height;
15657    }
15658
15659    private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds,
15660            @Nullable Rect touchBounds) {
15661        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
15662        if (bounds == null) {
15663            return;
15664        }
15665        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15666        final int size = getVerticalScrollbarWidth();
15667        int verticalScrollbarPosition = mVerticalScrollbarPosition;
15668        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
15669            verticalScrollbarPosition = isLayoutRtl() ?
15670                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
15671        }
15672        final int width = mRight - mLeft;
15673        final int height = mBottom - mTop;
15674        switch (verticalScrollbarPosition) {
15675            default:
15676            case SCROLLBAR_POSITION_RIGHT:
15677                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
15678                break;
15679            case SCROLLBAR_POSITION_LEFT:
15680                bounds.left = mScrollX + (mUserPaddingLeft & inside);
15681                break;
15682        }
15683        bounds.top = mScrollY + (mPaddingTop & inside);
15684        bounds.right = bounds.left + size;
15685        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
15686
15687        if (touchBounds == null) {
15688            return;
15689        }
15690        if (touchBounds != bounds) {
15691            touchBounds.set(bounds);
15692        }
15693        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
15694        if (touchBounds.width() < minTouchTarget) {
15695            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
15696            if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) {
15697                touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width);
15698                touchBounds.left = touchBounds.right - minTouchTarget;
15699            } else {
15700                touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX);
15701                touchBounds.right = touchBounds.left + minTouchTarget;
15702            }
15703        }
15704        if (touchBounds.height() < minTouchTarget) {
15705            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
15706            touchBounds.top -= adjust;
15707            touchBounds.bottom = touchBounds.top + minTouchTarget;
15708        }
15709    }
15710
15711    /**
15712     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
15713     * scrollbars are painted only if they have been awakened first.</p>
15714     *
15715     * @param canvas the canvas on which to draw the scrollbars
15716     *
15717     * @see #awakenScrollBars(int)
15718     */
15719    protected final void onDrawScrollBars(Canvas canvas) {
15720        // scrollbars are drawn only when the animation is running
15721        final ScrollabilityCache cache = mScrollCache;
15722
15723        if (cache != null) {
15724
15725            int state = cache.state;
15726
15727            if (state == ScrollabilityCache.OFF) {
15728                return;
15729            }
15730
15731            boolean invalidate = false;
15732
15733            if (state == ScrollabilityCache.FADING) {
15734                // We're fading -- get our fade interpolation
15735                if (cache.interpolatorValues == null) {
15736                    cache.interpolatorValues = new float[1];
15737                }
15738
15739                float[] values = cache.interpolatorValues;
15740
15741                // Stops the animation if we're done
15742                if (cache.scrollBarInterpolator.timeToValues(values) ==
15743                        Interpolator.Result.FREEZE_END) {
15744                    cache.state = ScrollabilityCache.OFF;
15745                } else {
15746                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
15747                }
15748
15749                // This will make the scroll bars inval themselves after
15750                // drawing. We only want this when we're fading so that
15751                // we prevent excessive redraws
15752                invalidate = true;
15753            } else {
15754                // We're just on -- but we may have been fading before so
15755                // reset alpha
15756                cache.scrollBar.mutate().setAlpha(255);
15757            }
15758
15759            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
15760            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15761                    && !isVerticalScrollBarHidden();
15762
15763            // Fork out the scroll bar drawing for round wearable devices.
15764            if (mRoundScrollbarRenderer != null) {
15765                if (drawVerticalScrollBar) {
15766                    final Rect bounds = cache.mScrollBarBounds;
15767                    getVerticalScrollBarBounds(bounds, null);
15768                    mRoundScrollbarRenderer.drawRoundScrollbars(
15769                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
15770                    if (invalidate) {
15771                        invalidate();
15772                    }
15773                }
15774                // Do not draw horizontal scroll bars for round wearable devices.
15775            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
15776                final ScrollBarDrawable scrollBar = cache.scrollBar;
15777
15778                if (drawHorizontalScrollBar) {
15779                    scrollBar.setParameters(computeHorizontalScrollRange(),
15780                            computeHorizontalScrollOffset(),
15781                            computeHorizontalScrollExtent(), false);
15782                    final Rect bounds = cache.mScrollBarBounds;
15783                    getHorizontalScrollBarBounds(bounds, null);
15784                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15785                            bounds.right, bounds.bottom);
15786                    if (invalidate) {
15787                        invalidate(bounds);
15788                    }
15789                }
15790
15791                if (drawVerticalScrollBar) {
15792                    scrollBar.setParameters(computeVerticalScrollRange(),
15793                            computeVerticalScrollOffset(),
15794                            computeVerticalScrollExtent(), true);
15795                    final Rect bounds = cache.mScrollBarBounds;
15796                    getVerticalScrollBarBounds(bounds, null);
15797                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15798                            bounds.right, bounds.bottom);
15799                    if (invalidate) {
15800                        invalidate(bounds);
15801                    }
15802                }
15803            }
15804        }
15805    }
15806
15807    /**
15808     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
15809     * FastScroller is visible.
15810     * @return whether to temporarily hide the vertical scrollbar
15811     * @hide
15812     */
15813    protected boolean isVerticalScrollBarHidden() {
15814        return false;
15815    }
15816
15817    /**
15818     * <p>Draw the horizontal scrollbar if
15819     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
15820     *
15821     * @param canvas the canvas on which to draw the scrollbar
15822     * @param scrollBar the scrollbar's drawable
15823     *
15824     * @see #isHorizontalScrollBarEnabled()
15825     * @see #computeHorizontalScrollRange()
15826     * @see #computeHorizontalScrollExtent()
15827     * @see #computeHorizontalScrollOffset()
15828     * @see android.widget.ScrollBarDrawable
15829     * @hide
15830     */
15831    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
15832            int l, int t, int r, int b) {
15833        scrollBar.setBounds(l, t, r, b);
15834        scrollBar.draw(canvas);
15835    }
15836
15837    /**
15838     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
15839     * returns true.</p>
15840     *
15841     * @param canvas the canvas on which to draw the scrollbar
15842     * @param scrollBar the scrollbar's drawable
15843     *
15844     * @see #isVerticalScrollBarEnabled()
15845     * @see #computeVerticalScrollRange()
15846     * @see #computeVerticalScrollExtent()
15847     * @see #computeVerticalScrollOffset()
15848     * @see android.widget.ScrollBarDrawable
15849     * @hide
15850     */
15851    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
15852            int l, int t, int r, int b) {
15853        scrollBar.setBounds(l, t, r, b);
15854        scrollBar.draw(canvas);
15855    }
15856
15857    /**
15858     * Implement this to do your drawing.
15859     *
15860     * @param canvas the canvas on which the background will be drawn
15861     */
15862    protected void onDraw(Canvas canvas) {
15863    }
15864
15865    /*
15866     * Caller is responsible for calling requestLayout if necessary.
15867     * (This allows addViewInLayout to not request a new layout.)
15868     */
15869    void assignParent(ViewParent parent) {
15870        if (mParent == null) {
15871            mParent = parent;
15872        } else if (parent == null) {
15873            mParent = null;
15874        } else {
15875            throw new RuntimeException("view " + this + " being added, but"
15876                    + " it already has a parent");
15877        }
15878    }
15879
15880    /**
15881     * This is called when the view is attached to a window.  At this point it
15882     * has a Surface and will start drawing.  Note that this function is
15883     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15884     * however it may be called any time before the first onDraw -- including
15885     * before or after {@link #onMeasure(int, int)}.
15886     *
15887     * @see #onDetachedFromWindow()
15888     */
15889    @CallSuper
15890    protected void onAttachedToWindow() {
15891        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15892            mParent.requestTransparentRegion(this);
15893        }
15894
15895        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15896
15897        jumpDrawablesToCurrentState();
15898
15899        resetSubtreeAccessibilityStateChanged();
15900
15901        // rebuild, since Outline not maintained while View is detached
15902        rebuildOutline();
15903
15904        if (isFocused()) {
15905            InputMethodManager imm = InputMethodManager.peekInstance();
15906            if (imm != null) {
15907                imm.focusIn(this);
15908            }
15909        }
15910    }
15911
15912    /**
15913     * Resolve all RTL related properties.
15914     *
15915     * @return true if resolution of RTL properties has been done
15916     *
15917     * @hide
15918     */
15919    public boolean resolveRtlPropertiesIfNeeded() {
15920        if (!needRtlPropertiesResolution()) return false;
15921
15922        // Order is important here: LayoutDirection MUST be resolved first
15923        if (!isLayoutDirectionResolved()) {
15924            resolveLayoutDirection();
15925            resolveLayoutParams();
15926        }
15927        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15928        if (!isTextDirectionResolved()) {
15929            resolveTextDirection();
15930        }
15931        if (!isTextAlignmentResolved()) {
15932            resolveTextAlignment();
15933        }
15934        // Should resolve Drawables before Padding because we need the layout direction of the
15935        // Drawable to correctly resolve Padding.
15936        if (!areDrawablesResolved()) {
15937            resolveDrawables();
15938        }
15939        if (!isPaddingResolved()) {
15940            resolvePadding();
15941        }
15942        onRtlPropertiesChanged(getLayoutDirection());
15943        return true;
15944    }
15945
15946    /**
15947     * Reset resolution of all RTL related properties.
15948     *
15949     * @hide
15950     */
15951    public void resetRtlProperties() {
15952        resetResolvedLayoutDirection();
15953        resetResolvedTextDirection();
15954        resetResolvedTextAlignment();
15955        resetResolvedPadding();
15956        resetResolvedDrawables();
15957    }
15958
15959    /**
15960     * @see #onScreenStateChanged(int)
15961     */
15962    void dispatchScreenStateChanged(int screenState) {
15963        onScreenStateChanged(screenState);
15964    }
15965
15966    /**
15967     * This method is called whenever the state of the screen this view is
15968     * attached to changes. A state change will usually occurs when the screen
15969     * turns on or off (whether it happens automatically or the user does it
15970     * manually.)
15971     *
15972     * @param screenState The new state of the screen. Can be either
15973     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15974     */
15975    public void onScreenStateChanged(int screenState) {
15976    }
15977
15978    /**
15979     * @see #onMovedToDisplay(int)
15980     */
15981    void dispatchMovedToDisplay(Display display) {
15982        mAttachInfo.mDisplay = display;
15983        mAttachInfo.mDisplayState = display.getState();
15984        onMovedToDisplay(display.getDisplayId());
15985    }
15986
15987    /**
15988     * Called by the system when the hosting activity is moved from one display to another without
15989     * recreation. This means that the activity is declared to handle all changes to configuration
15990     * that happened when it was switched to another display, so it wasn't destroyed and created
15991     * again. This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
15992     * applied configuration actually changed.
15993     *
15994     * <p>Use this callback to track changes to the displays if some functionality relies on an
15995     * association with some display properties.
15996     *
15997     * @param displayId The id of the display to which the view was moved.
15998     *
15999     * @see #onConfigurationChanged(Configuration)
16000     */
16001    public void onMovedToDisplay(int displayId) {
16002    }
16003
16004    /**
16005     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
16006     */
16007    private boolean hasRtlSupport() {
16008        return mContext.getApplicationInfo().hasRtlSupport();
16009    }
16010
16011    /**
16012     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
16013     * RTL not supported)
16014     */
16015    private boolean isRtlCompatibilityMode() {
16016        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
16017        return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport();
16018    }
16019
16020    /**
16021     * @return true if RTL properties need resolution.
16022     *
16023     */
16024    private boolean needRtlPropertiesResolution() {
16025        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
16026    }
16027
16028    /**
16029     * Called when any RTL property (layout direction or text direction or text alignment) has
16030     * been changed.
16031     *
16032     * Subclasses need to override this method to take care of cached information that depends on the
16033     * resolved layout direction, or to inform child views that inherit their layout direction.
16034     *
16035     * The default implementation does nothing.
16036     *
16037     * @param layoutDirection the direction of the layout
16038     *
16039     * @see #LAYOUT_DIRECTION_LTR
16040     * @see #LAYOUT_DIRECTION_RTL
16041     */
16042    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
16043    }
16044
16045    /**
16046     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
16047     * that the parent directionality can and will be resolved before its children.
16048     *
16049     * @return true if resolution has been done, false otherwise.
16050     *
16051     * @hide
16052     */
16053    public boolean resolveLayoutDirection() {
16054        // Clear any previous layout direction resolution
16055        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16056
16057        if (hasRtlSupport()) {
16058            // Set resolved depending on layout direction
16059            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
16060                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
16061                case LAYOUT_DIRECTION_INHERIT:
16062                    // We cannot resolve yet. LTR is by default and let the resolution happen again
16063                    // later to get the correct resolved value
16064                    if (!canResolveLayoutDirection()) return false;
16065
16066                    // Parent has not yet resolved, LTR is still the default
16067                    try {
16068                        if (!mParent.isLayoutDirectionResolved()) return false;
16069
16070                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
16071                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16072                        }
16073                    } catch (AbstractMethodError e) {
16074                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16075                                " does not fully implement ViewParent", e);
16076                    }
16077                    break;
16078                case LAYOUT_DIRECTION_RTL:
16079                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16080                    break;
16081                case LAYOUT_DIRECTION_LOCALE:
16082                    if((LAYOUT_DIRECTION_RTL ==
16083                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
16084                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16085                    }
16086                    break;
16087                default:
16088                    // Nothing to do, LTR by default
16089            }
16090        }
16091
16092        // Set to resolved
16093        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16094        return true;
16095    }
16096
16097    /**
16098     * Check if layout direction resolution can be done.
16099     *
16100     * @return true if layout direction resolution can be done otherwise return false.
16101     */
16102    public boolean canResolveLayoutDirection() {
16103        switch (getRawLayoutDirection()) {
16104            case LAYOUT_DIRECTION_INHERIT:
16105                if (mParent != null) {
16106                    try {
16107                        return mParent.canResolveLayoutDirection();
16108                    } catch (AbstractMethodError e) {
16109                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16110                                " does not fully implement ViewParent", e);
16111                    }
16112                }
16113                return false;
16114
16115            default:
16116                return true;
16117        }
16118    }
16119
16120    /**
16121     * Reset the resolved layout direction. Layout direction will be resolved during a call to
16122     * {@link #onMeasure(int, int)}.
16123     *
16124     * @hide
16125     */
16126    public void resetResolvedLayoutDirection() {
16127        // Reset the current resolved bits
16128        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16129    }
16130
16131    /**
16132     * @return true if the layout direction is inherited.
16133     *
16134     * @hide
16135     */
16136    public boolean isLayoutDirectionInherited() {
16137        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
16138    }
16139
16140    /**
16141     * @return true if layout direction has been resolved.
16142     */
16143    public boolean isLayoutDirectionResolved() {
16144        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16145    }
16146
16147    /**
16148     * Return if padding has been resolved
16149     *
16150     * @hide
16151     */
16152    boolean isPaddingResolved() {
16153        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
16154    }
16155
16156    /**
16157     * Resolves padding depending on layout direction, if applicable, and
16158     * recomputes internal padding values to adjust for scroll bars.
16159     *
16160     * @hide
16161     */
16162    public void resolvePadding() {
16163        final int resolvedLayoutDirection = getLayoutDirection();
16164
16165        if (!isRtlCompatibilityMode()) {
16166            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
16167            // If start / end padding are defined, they will be resolved (hence overriding) to
16168            // left / right or right / left depending on the resolved layout direction.
16169            // If start / end padding are not defined, use the left / right ones.
16170            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
16171                Rect padding = sThreadLocal.get();
16172                if (padding == null) {
16173                    padding = new Rect();
16174                    sThreadLocal.set(padding);
16175                }
16176                mBackground.getPadding(padding);
16177                if (!mLeftPaddingDefined) {
16178                    mUserPaddingLeftInitial = padding.left;
16179                }
16180                if (!mRightPaddingDefined) {
16181                    mUserPaddingRightInitial = padding.right;
16182                }
16183            }
16184            switch (resolvedLayoutDirection) {
16185                case LAYOUT_DIRECTION_RTL:
16186                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16187                        mUserPaddingRight = mUserPaddingStart;
16188                    } else {
16189                        mUserPaddingRight = mUserPaddingRightInitial;
16190                    }
16191                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16192                        mUserPaddingLeft = mUserPaddingEnd;
16193                    } else {
16194                        mUserPaddingLeft = mUserPaddingLeftInitial;
16195                    }
16196                    break;
16197                case LAYOUT_DIRECTION_LTR:
16198                default:
16199                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16200                        mUserPaddingLeft = mUserPaddingStart;
16201                    } else {
16202                        mUserPaddingLeft = mUserPaddingLeftInitial;
16203                    }
16204                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16205                        mUserPaddingRight = mUserPaddingEnd;
16206                    } else {
16207                        mUserPaddingRight = mUserPaddingRightInitial;
16208                    }
16209            }
16210
16211            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
16212        }
16213
16214        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
16215        onRtlPropertiesChanged(resolvedLayoutDirection);
16216
16217        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
16218    }
16219
16220    /**
16221     * Reset the resolved layout direction.
16222     *
16223     * @hide
16224     */
16225    public void resetResolvedPadding() {
16226        resetResolvedPaddingInternal();
16227    }
16228
16229    /**
16230     * Used when we only want to reset *this* view's padding and not trigger overrides
16231     * in ViewGroup that reset children too.
16232     */
16233    void resetResolvedPaddingInternal() {
16234        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
16235    }
16236
16237    /**
16238     * This is called when the view is detached from a window.  At this point it
16239     * no longer has a surface for drawing.
16240     *
16241     * @see #onAttachedToWindow()
16242     */
16243    @CallSuper
16244    protected void onDetachedFromWindow() {
16245    }
16246
16247    /**
16248     * This is a framework-internal mirror of onDetachedFromWindow() that's called
16249     * after onDetachedFromWindow().
16250     *
16251     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
16252     * The super method should be called at the end of the overridden method to ensure
16253     * subclasses are destroyed first
16254     *
16255     * @hide
16256     */
16257    @CallSuper
16258    protected void onDetachedFromWindowInternal() {
16259        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
16260        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
16261        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
16262
16263        removeUnsetPressCallback();
16264        removeLongPressCallback();
16265        removePerformClickCallback();
16266        removeSendViewScrolledAccessibilityEventCallback();
16267        stopNestedScroll();
16268
16269        // Anything that started animating right before detach should already
16270        // be in its final state when re-attached.
16271        jumpDrawablesToCurrentState();
16272
16273        destroyDrawingCache();
16274
16275        cleanupDraw();
16276        mCurrentAnimation = null;
16277
16278        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
16279            hideTooltip();
16280        }
16281    }
16282
16283    private void cleanupDraw() {
16284        resetDisplayList();
16285        if (mAttachInfo != null) {
16286            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
16287        }
16288    }
16289
16290    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
16291    }
16292
16293    /**
16294     * @return The number of times this view has been attached to a window
16295     */
16296    protected int getWindowAttachCount() {
16297        return mWindowAttachCount;
16298    }
16299
16300    /**
16301     * Retrieve a unique token identifying the window this view is attached to.
16302     * @return Return the window's token for use in
16303     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
16304     */
16305    public IBinder getWindowToken() {
16306        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
16307    }
16308
16309    /**
16310     * Retrieve the {@link WindowId} for the window this view is
16311     * currently attached to.
16312     */
16313    public WindowId getWindowId() {
16314        if (mAttachInfo == null) {
16315            return null;
16316        }
16317        if (mAttachInfo.mWindowId == null) {
16318            try {
16319                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
16320                        mAttachInfo.mWindowToken);
16321                mAttachInfo.mWindowId = new WindowId(
16322                        mAttachInfo.mIWindowId);
16323            } catch (RemoteException e) {
16324            }
16325        }
16326        return mAttachInfo.mWindowId;
16327    }
16328
16329    /**
16330     * Retrieve a unique token identifying the top-level "real" window of
16331     * the window that this view is attached to.  That is, this is like
16332     * {@link #getWindowToken}, except if the window this view in is a panel
16333     * window (attached to another containing window), then the token of
16334     * the containing window is returned instead.
16335     *
16336     * @return Returns the associated window token, either
16337     * {@link #getWindowToken()} or the containing window's token.
16338     */
16339    public IBinder getApplicationWindowToken() {
16340        AttachInfo ai = mAttachInfo;
16341        if (ai != null) {
16342            IBinder appWindowToken = ai.mPanelParentWindowToken;
16343            if (appWindowToken == null) {
16344                appWindowToken = ai.mWindowToken;
16345            }
16346            return appWindowToken;
16347        }
16348        return null;
16349    }
16350
16351    /**
16352     * Gets the logical display to which the view's window has been attached.
16353     *
16354     * @return The logical display, or null if the view is not currently attached to a window.
16355     */
16356    public Display getDisplay() {
16357        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
16358    }
16359
16360    /**
16361     * Retrieve private session object this view hierarchy is using to
16362     * communicate with the window manager.
16363     * @return the session object to communicate with the window manager
16364     */
16365    /*package*/ IWindowSession getWindowSession() {
16366        return mAttachInfo != null ? mAttachInfo.mSession : null;
16367    }
16368
16369    /**
16370     * Return the visibility value of the least visible component passed.
16371     */
16372    int combineVisibility(int vis1, int vis2) {
16373        // This works because VISIBLE < INVISIBLE < GONE.
16374        return Math.max(vis1, vis2);
16375    }
16376
16377    /**
16378     * @param info the {@link android.view.View.AttachInfo} to associated with
16379     *        this view
16380     */
16381    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
16382        mAttachInfo = info;
16383        if (mOverlay != null) {
16384            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
16385        }
16386        mWindowAttachCount++;
16387        // We will need to evaluate the drawable state at least once.
16388        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16389        if (mFloatingTreeObserver != null) {
16390            info.mTreeObserver.merge(mFloatingTreeObserver);
16391            mFloatingTreeObserver = null;
16392        }
16393
16394        registerPendingFrameMetricsObservers();
16395
16396        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
16397            mAttachInfo.mScrollContainers.add(this);
16398            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
16399        }
16400        // Transfer all pending runnables.
16401        if (mRunQueue != null) {
16402            mRunQueue.executeActions(info.mHandler);
16403            mRunQueue = null;
16404        }
16405        performCollectViewAttributes(mAttachInfo, visibility);
16406        onAttachedToWindow();
16407
16408        ListenerInfo li = mListenerInfo;
16409        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16410                li != null ? li.mOnAttachStateChangeListeners : null;
16411        if (listeners != null && listeners.size() > 0) {
16412            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16413            // perform the dispatching. The iterator is a safe guard against listeners that
16414            // could mutate the list by calling the various add/remove methods. This prevents
16415            // the array from being modified while we iterate it.
16416            for (OnAttachStateChangeListener listener : listeners) {
16417                listener.onViewAttachedToWindow(this);
16418            }
16419        }
16420
16421        int vis = info.mWindowVisibility;
16422        if (vis != GONE) {
16423            onWindowVisibilityChanged(vis);
16424            if (isShown()) {
16425                // Calling onVisibilityAggregated directly here since the subtree will also
16426                // receive dispatchAttachedToWindow and this same call
16427                onVisibilityAggregated(vis == VISIBLE);
16428            }
16429        }
16430
16431        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
16432        // As all views in the subtree will already receive dispatchAttachedToWindow
16433        // traversing the subtree again here is not desired.
16434        onVisibilityChanged(this, visibility);
16435
16436        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
16437            // If nobody has evaluated the drawable state yet, then do it now.
16438            refreshDrawableState();
16439        }
16440        needGlobalAttributesUpdate(false);
16441    }
16442
16443    void dispatchDetachedFromWindow() {
16444        AttachInfo info = mAttachInfo;
16445        if (info != null) {
16446            int vis = info.mWindowVisibility;
16447            if (vis != GONE) {
16448                onWindowVisibilityChanged(GONE);
16449                if (isShown()) {
16450                    // Invoking onVisibilityAggregated directly here since the subtree
16451                    // will also receive detached from window
16452                    onVisibilityAggregated(false);
16453                }
16454            }
16455        }
16456
16457        onDetachedFromWindow();
16458        onDetachedFromWindowInternal();
16459
16460        InputMethodManager imm = InputMethodManager.peekInstance();
16461        if (imm != null) {
16462            imm.onViewDetachedFromWindow(this);
16463        }
16464
16465        ListenerInfo li = mListenerInfo;
16466        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16467                li != null ? li.mOnAttachStateChangeListeners : null;
16468        if (listeners != null && listeners.size() > 0) {
16469            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16470            // perform the dispatching. The iterator is a safe guard against listeners that
16471            // could mutate the list by calling the various add/remove methods. This prevents
16472            // the array from being modified while we iterate it.
16473            for (OnAttachStateChangeListener listener : listeners) {
16474                listener.onViewDetachedFromWindow(this);
16475            }
16476        }
16477
16478        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
16479            mAttachInfo.mScrollContainers.remove(this);
16480            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
16481        }
16482
16483        mAttachInfo = null;
16484        if (mOverlay != null) {
16485            mOverlay.getOverlayView().dispatchDetachedFromWindow();
16486        }
16487    }
16488
16489    /**
16490     * Cancel any deferred high-level input events that were previously posted to the event queue.
16491     *
16492     * <p>Many views post high-level events such as click handlers to the event queue
16493     * to run deferred in order to preserve a desired user experience - clearing visible
16494     * pressed states before executing, etc. This method will abort any events of this nature
16495     * that are currently in flight.</p>
16496     *
16497     * <p>Custom views that generate their own high-level deferred input events should override
16498     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
16499     *
16500     * <p>This will also cancel pending input events for any child views.</p>
16501     *
16502     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
16503     * This will not impact newer events posted after this call that may occur as a result of
16504     * lower-level input events still waiting in the queue. If you are trying to prevent
16505     * double-submitted  events for the duration of some sort of asynchronous transaction
16506     * you should also take other steps to protect against unexpected double inputs e.g. calling
16507     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
16508     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
16509     */
16510    public final void cancelPendingInputEvents() {
16511        dispatchCancelPendingInputEvents();
16512    }
16513
16514    /**
16515     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
16516     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
16517     */
16518    void dispatchCancelPendingInputEvents() {
16519        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
16520        onCancelPendingInputEvents();
16521        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
16522            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
16523                    " did not call through to super.onCancelPendingInputEvents()");
16524        }
16525    }
16526
16527    /**
16528     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
16529     * a parent view.
16530     *
16531     * <p>This method is responsible for removing any pending high-level input events that were
16532     * posted to the event queue to run later. Custom view classes that post their own deferred
16533     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
16534     * {@link android.os.Handler} should override this method, call
16535     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
16536     * </p>
16537     */
16538    public void onCancelPendingInputEvents() {
16539        removePerformClickCallback();
16540        cancelLongPress();
16541        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
16542    }
16543
16544    /**
16545     * Store this view hierarchy's frozen state into the given container.
16546     *
16547     * @param container The SparseArray in which to save the view's state.
16548     *
16549     * @see #restoreHierarchyState(android.util.SparseArray)
16550     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16551     * @see #onSaveInstanceState()
16552     */
16553    public void saveHierarchyState(SparseArray<Parcelable> container) {
16554        dispatchSaveInstanceState(container);
16555    }
16556
16557    /**
16558     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
16559     * this view and its children. May be overridden to modify how freezing happens to a
16560     * view's children; for example, some views may want to not store state for their children.
16561     *
16562     * @param container The SparseArray in which to save the view's state.
16563     *
16564     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16565     * @see #saveHierarchyState(android.util.SparseArray)
16566     * @see #onSaveInstanceState()
16567     */
16568    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
16569        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
16570            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16571            Parcelable state = onSaveInstanceState();
16572            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16573                throw new IllegalStateException(
16574                        "Derived class did not call super.onSaveInstanceState()");
16575            }
16576            if (state != null) {
16577                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
16578                // + ": " + state);
16579                container.put(mID, state);
16580            }
16581        }
16582    }
16583
16584    /**
16585     * Hook allowing a view to generate a representation of its internal state
16586     * that can later be used to create a new instance with that same state.
16587     * This state should only contain information that is not persistent or can
16588     * not be reconstructed later. For example, you will never store your
16589     * current position on screen because that will be computed again when a
16590     * new instance of the view is placed in its view hierarchy.
16591     * <p>
16592     * Some examples of things you may store here: the current cursor position
16593     * in a text view (but usually not the text itself since that is stored in a
16594     * content provider or other persistent storage), the currently selected
16595     * item in a list view.
16596     *
16597     * @return Returns a Parcelable object containing the view's current dynamic
16598     *         state, or null if there is nothing interesting to save. The
16599     *         default implementation returns null.
16600     * @see #onRestoreInstanceState(android.os.Parcelable)
16601     * @see #saveHierarchyState(android.util.SparseArray)
16602     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16603     * @see #setSaveEnabled(boolean)
16604     */
16605    @CallSuper
16606    protected Parcelable onSaveInstanceState() {
16607        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16608        if (mStartActivityRequestWho != null) {
16609            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
16610            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
16611            return state;
16612        }
16613        return BaseSavedState.EMPTY_STATE;
16614    }
16615
16616    /**
16617     * Restore this view hierarchy's frozen state from the given container.
16618     *
16619     * @param container The SparseArray which holds previously frozen states.
16620     *
16621     * @see #saveHierarchyState(android.util.SparseArray)
16622     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16623     * @see #onRestoreInstanceState(android.os.Parcelable)
16624     */
16625    public void restoreHierarchyState(SparseArray<Parcelable> container) {
16626        dispatchRestoreInstanceState(container);
16627    }
16628
16629    /**
16630     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
16631     * state for this view and its children. May be overridden to modify how restoring
16632     * happens to a view's children; for example, some views may want to not store state
16633     * for their children.
16634     *
16635     * @param container The SparseArray which holds previously saved state.
16636     *
16637     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16638     * @see #restoreHierarchyState(android.util.SparseArray)
16639     * @see #onRestoreInstanceState(android.os.Parcelable)
16640     */
16641    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
16642        if (mID != NO_ID) {
16643            Parcelable state = container.get(mID);
16644            if (state != null) {
16645                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
16646                // + ": " + state);
16647                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16648                onRestoreInstanceState(state);
16649                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16650                    throw new IllegalStateException(
16651                            "Derived class did not call super.onRestoreInstanceState()");
16652                }
16653            }
16654        }
16655    }
16656
16657    /**
16658     * Hook allowing a view to re-apply a representation of its internal state that had previously
16659     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
16660     * null state.
16661     *
16662     * @param state The frozen state that had previously been returned by
16663     *        {@link #onSaveInstanceState}.
16664     *
16665     * @see #onSaveInstanceState()
16666     * @see #restoreHierarchyState(android.util.SparseArray)
16667     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16668     */
16669    @CallSuper
16670    protected void onRestoreInstanceState(Parcelable state) {
16671        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16672        if (state != null && !(state instanceof AbsSavedState)) {
16673            throw new IllegalArgumentException("Wrong state class, expecting View State but "
16674                    + "received " + state.getClass().toString() + " instead. This usually happens "
16675                    + "when two views of different type have the same id in the same hierarchy. "
16676                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
16677                    + "other views do not use the same id.");
16678        }
16679        if (state != null && state instanceof BaseSavedState) {
16680            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
16681        }
16682    }
16683
16684    /**
16685     * <p>Return the time at which the drawing of the view hierarchy started.</p>
16686     *
16687     * @return the drawing start time in milliseconds
16688     */
16689    public long getDrawingTime() {
16690        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
16691    }
16692
16693    /**
16694     * <p>Enables or disables the duplication of the parent's state into this view. When
16695     * duplication is enabled, this view gets its drawable state from its parent rather
16696     * than from its own internal properties.</p>
16697     *
16698     * <p>Note: in the current implementation, setting this property to true after the
16699     * view was added to a ViewGroup might have no effect at all. This property should
16700     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
16701     *
16702     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
16703     * property is enabled, an exception will be thrown.</p>
16704     *
16705     * <p>Note: if the child view uses and updates additional states which are unknown to the
16706     * parent, these states should not be affected by this method.</p>
16707     *
16708     * @param enabled True to enable duplication of the parent's drawable state, false
16709     *                to disable it.
16710     *
16711     * @see #getDrawableState()
16712     * @see #isDuplicateParentStateEnabled()
16713     */
16714    public void setDuplicateParentStateEnabled(boolean enabled) {
16715        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
16716    }
16717
16718    /**
16719     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
16720     *
16721     * @return True if this view's drawable state is duplicated from the parent,
16722     *         false otherwise
16723     *
16724     * @see #getDrawableState()
16725     * @see #setDuplicateParentStateEnabled(boolean)
16726     */
16727    public boolean isDuplicateParentStateEnabled() {
16728        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
16729    }
16730
16731    /**
16732     * <p>Specifies the type of layer backing this view. The layer can be
16733     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16734     * {@link #LAYER_TYPE_HARDWARE}.</p>
16735     *
16736     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16737     * instance that controls how the layer is composed on screen. The following
16738     * properties of the paint are taken into account when composing the layer:</p>
16739     * <ul>
16740     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16741     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16742     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16743     * </ul>
16744     *
16745     * <p>If this view has an alpha value set to < 1.0 by calling
16746     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
16747     * by this view's alpha value.</p>
16748     *
16749     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
16750     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
16751     * for more information on when and how to use layers.</p>
16752     *
16753     * @param layerType The type of layer to use with this view, must be one of
16754     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16755     *        {@link #LAYER_TYPE_HARDWARE}
16756     * @param paint The paint used to compose the layer. This argument is optional
16757     *        and can be null. It is ignored when the layer type is
16758     *        {@link #LAYER_TYPE_NONE}
16759     *
16760     * @see #getLayerType()
16761     * @see #LAYER_TYPE_NONE
16762     * @see #LAYER_TYPE_SOFTWARE
16763     * @see #LAYER_TYPE_HARDWARE
16764     * @see #setAlpha(float)
16765     *
16766     * @attr ref android.R.styleable#View_layerType
16767     */
16768    public void setLayerType(int layerType, @Nullable Paint paint) {
16769        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
16770            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
16771                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
16772        }
16773
16774        boolean typeChanged = mRenderNode.setLayerType(layerType);
16775
16776        if (!typeChanged) {
16777            setLayerPaint(paint);
16778            return;
16779        }
16780
16781        if (layerType != LAYER_TYPE_SOFTWARE) {
16782            // Destroy any previous software drawing cache if present
16783            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
16784            // drawing cache created in View#draw when drawing to a SW canvas.
16785            destroyDrawingCache();
16786        }
16787
16788        mLayerType = layerType;
16789        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
16790        mRenderNode.setLayerPaint(mLayerPaint);
16791
16792        // draw() behaves differently if we are on a layer, so we need to
16793        // invalidate() here
16794        invalidateParentCaches();
16795        invalidate(true);
16796    }
16797
16798    /**
16799     * Updates the {@link Paint} object used with the current layer (used only if the current
16800     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
16801     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
16802     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
16803     * ensure that the view gets redrawn immediately.
16804     *
16805     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16806     * instance that controls how the layer is composed on screen. The following
16807     * properties of the paint are taken into account when composing the layer:</p>
16808     * <ul>
16809     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16810     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16811     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16812     * </ul>
16813     *
16814     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
16815     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
16816     *
16817     * @param paint The paint used to compose the layer. This argument is optional
16818     *        and can be null. It is ignored when the layer type is
16819     *        {@link #LAYER_TYPE_NONE}
16820     *
16821     * @see #setLayerType(int, android.graphics.Paint)
16822     */
16823    public void setLayerPaint(@Nullable Paint paint) {
16824        int layerType = getLayerType();
16825        if (layerType != LAYER_TYPE_NONE) {
16826            mLayerPaint = paint;
16827            if (layerType == LAYER_TYPE_HARDWARE) {
16828                if (mRenderNode.setLayerPaint(paint)) {
16829                    invalidateViewProperty(false, false);
16830                }
16831            } else {
16832                invalidate();
16833            }
16834        }
16835    }
16836
16837    /**
16838     * Indicates what type of layer is currently associated with this view. By default
16839     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
16840     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
16841     * for more information on the different types of layers.
16842     *
16843     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16844     *         {@link #LAYER_TYPE_HARDWARE}
16845     *
16846     * @see #setLayerType(int, android.graphics.Paint)
16847     * @see #buildLayer()
16848     * @see #LAYER_TYPE_NONE
16849     * @see #LAYER_TYPE_SOFTWARE
16850     * @see #LAYER_TYPE_HARDWARE
16851     */
16852    public int getLayerType() {
16853        return mLayerType;
16854    }
16855
16856    /**
16857     * Forces this view's layer to be created and this view to be rendered
16858     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
16859     * invoking this method will have no effect.
16860     *
16861     * This method can for instance be used to render a view into its layer before
16862     * starting an animation. If this view is complex, rendering into the layer
16863     * before starting the animation will avoid skipping frames.
16864     *
16865     * @throws IllegalStateException If this view is not attached to a window
16866     *
16867     * @see #setLayerType(int, android.graphics.Paint)
16868     */
16869    public void buildLayer() {
16870        if (mLayerType == LAYER_TYPE_NONE) return;
16871
16872        final AttachInfo attachInfo = mAttachInfo;
16873        if (attachInfo == null) {
16874            throw new IllegalStateException("This view must be attached to a window first");
16875        }
16876
16877        if (getWidth() == 0 || getHeight() == 0) {
16878            return;
16879        }
16880
16881        switch (mLayerType) {
16882            case LAYER_TYPE_HARDWARE:
16883                updateDisplayListIfDirty();
16884                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
16885                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
16886                }
16887                break;
16888            case LAYER_TYPE_SOFTWARE:
16889                buildDrawingCache(true);
16890                break;
16891        }
16892    }
16893
16894    /**
16895     * Destroys all hardware rendering resources. This method is invoked
16896     * when the system needs to reclaim resources. Upon execution of this
16897     * method, you should free any OpenGL resources created by the view.
16898     *
16899     * Note: you <strong>must</strong> call
16900     * <code>super.destroyHardwareResources()</code> when overriding
16901     * this method.
16902     *
16903     * @hide
16904     */
16905    @CallSuper
16906    protected void destroyHardwareResources() {
16907        if (mOverlay != null) {
16908            mOverlay.getOverlayView().destroyHardwareResources();
16909        }
16910        if (mGhostView != null) {
16911            mGhostView.destroyHardwareResources();
16912        }
16913    }
16914
16915    /**
16916     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16917     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16918     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16919     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16920     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16921     * null.</p>
16922     *
16923     * <p>Enabling the drawing cache is similar to
16924     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16925     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16926     * drawing cache has no effect on rendering because the system uses a different mechanism
16927     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16928     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16929     * for information on how to enable software and hardware layers.</p>
16930     *
16931     * <p>This API can be used to manually generate
16932     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16933     * {@link #getDrawingCache()}.</p>
16934     *
16935     * @param enabled true to enable the drawing cache, false otherwise
16936     *
16937     * @see #isDrawingCacheEnabled()
16938     * @see #getDrawingCache()
16939     * @see #buildDrawingCache()
16940     * @see #setLayerType(int, android.graphics.Paint)
16941     */
16942    public void setDrawingCacheEnabled(boolean enabled) {
16943        mCachingFailed = false;
16944        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16945    }
16946
16947    /**
16948     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16949     *
16950     * @return true if the drawing cache is enabled
16951     *
16952     * @see #setDrawingCacheEnabled(boolean)
16953     * @see #getDrawingCache()
16954     */
16955    @ViewDebug.ExportedProperty(category = "drawing")
16956    public boolean isDrawingCacheEnabled() {
16957        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16958    }
16959
16960    /**
16961     * Debugging utility which recursively outputs the dirty state of a view and its
16962     * descendants.
16963     *
16964     * @hide
16965     */
16966    @SuppressWarnings({"UnusedDeclaration"})
16967    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16968        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16969                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16970                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16971                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16972        if (clear) {
16973            mPrivateFlags &= clearMask;
16974        }
16975        if (this instanceof ViewGroup) {
16976            ViewGroup parent = (ViewGroup) this;
16977            final int count = parent.getChildCount();
16978            for (int i = 0; i < count; i++) {
16979                final View child = parent.getChildAt(i);
16980                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16981            }
16982        }
16983    }
16984
16985    /**
16986     * This method is used by ViewGroup to cause its children to restore or recreate their
16987     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16988     * to recreate its own display list, which would happen if it went through the normal
16989     * draw/dispatchDraw mechanisms.
16990     *
16991     * @hide
16992     */
16993    protected void dispatchGetDisplayList() {}
16994
16995    /**
16996     * A view that is not attached or hardware accelerated cannot create a display list.
16997     * This method checks these conditions and returns the appropriate result.
16998     *
16999     * @return true if view has the ability to create a display list, false otherwise.
17000     *
17001     * @hide
17002     */
17003    public boolean canHaveDisplayList() {
17004        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
17005    }
17006
17007    /**
17008     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
17009     * @hide
17010     */
17011    @NonNull
17012    public RenderNode updateDisplayListIfDirty() {
17013        final RenderNode renderNode = mRenderNode;
17014        if (!canHaveDisplayList()) {
17015            // can't populate RenderNode, don't try
17016            return renderNode;
17017        }
17018
17019        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
17020                || !renderNode.isValid()
17021                || (mRecreateDisplayList)) {
17022            // Don't need to recreate the display list, just need to tell our
17023            // children to restore/recreate theirs
17024            if (renderNode.isValid()
17025                    && !mRecreateDisplayList) {
17026                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17027                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17028                dispatchGetDisplayList();
17029
17030                return renderNode; // no work needed
17031            }
17032
17033            // If we got here, we're recreating it. Mark it as such to ensure that
17034            // we copy in child display lists into ours in drawChild()
17035            mRecreateDisplayList = true;
17036
17037            int width = mRight - mLeft;
17038            int height = mBottom - mTop;
17039            int layerType = getLayerType();
17040
17041            final DisplayListCanvas canvas = renderNode.start(width, height);
17042            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
17043
17044            try {
17045                if (layerType == LAYER_TYPE_SOFTWARE) {
17046                    buildDrawingCache(true);
17047                    Bitmap cache = getDrawingCache(true);
17048                    if (cache != null) {
17049                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
17050                    }
17051                } else {
17052                    computeScroll();
17053
17054                    canvas.translate(-mScrollX, -mScrollY);
17055                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17056                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17057
17058                    // Fast path for layouts with no backgrounds
17059                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17060                        dispatchDraw(canvas);
17061                        if (mOverlay != null && !mOverlay.isEmpty()) {
17062                            mOverlay.getOverlayView().draw(canvas);
17063                        }
17064                        if (debugDraw()) {
17065                            debugDrawFocus(canvas);
17066                        }
17067                    } else {
17068                        draw(canvas);
17069                    }
17070                }
17071            } finally {
17072                renderNode.end(canvas);
17073                setDisplayListProperties(renderNode);
17074            }
17075        } else {
17076            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17077            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17078        }
17079        return renderNode;
17080    }
17081
17082    private void resetDisplayList() {
17083        mRenderNode.discardDisplayList();
17084        if (mBackgroundRenderNode != null) {
17085            mBackgroundRenderNode.discardDisplayList();
17086        }
17087    }
17088
17089    /**
17090     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
17091     *
17092     * @return A non-scaled bitmap representing this view or null if cache is disabled.
17093     *
17094     * @see #getDrawingCache(boolean)
17095     */
17096    public Bitmap getDrawingCache() {
17097        return getDrawingCache(false);
17098    }
17099
17100    /**
17101     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
17102     * is null when caching is disabled. If caching is enabled and the cache is not ready,
17103     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
17104     * draw from the cache when the cache is enabled. To benefit from the cache, you must
17105     * request the drawing cache by calling this method and draw it on screen if the
17106     * returned bitmap is not null.</p>
17107     *
17108     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17109     * this method will create a bitmap of the same size as this view. Because this bitmap
17110     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17111     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17112     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17113     * size than the view. This implies that your application must be able to handle this
17114     * size.</p>
17115     *
17116     * @param autoScale Indicates whether the generated bitmap should be scaled based on
17117     *        the current density of the screen when the application is in compatibility
17118     *        mode.
17119     *
17120     * @return A bitmap representing this view or null if cache is disabled.
17121     *
17122     * @see #setDrawingCacheEnabled(boolean)
17123     * @see #isDrawingCacheEnabled()
17124     * @see #buildDrawingCache(boolean)
17125     * @see #destroyDrawingCache()
17126     */
17127    public Bitmap getDrawingCache(boolean autoScale) {
17128        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
17129            return null;
17130        }
17131        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
17132            buildDrawingCache(autoScale);
17133        }
17134        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
17135    }
17136
17137    /**
17138     * <p>Frees the resources used by the drawing cache. If you call
17139     * {@link #buildDrawingCache()} manually without calling
17140     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17141     * should cleanup the cache with this method afterwards.</p>
17142     *
17143     * @see #setDrawingCacheEnabled(boolean)
17144     * @see #buildDrawingCache()
17145     * @see #getDrawingCache()
17146     */
17147    public void destroyDrawingCache() {
17148        if (mDrawingCache != null) {
17149            mDrawingCache.recycle();
17150            mDrawingCache = null;
17151        }
17152        if (mUnscaledDrawingCache != null) {
17153            mUnscaledDrawingCache.recycle();
17154            mUnscaledDrawingCache = null;
17155        }
17156    }
17157
17158    /**
17159     * Setting a solid background color for the drawing cache's bitmaps will improve
17160     * performance and memory usage. Note, though that this should only be used if this
17161     * view will always be drawn on top of a solid color.
17162     *
17163     * @param color The background color to use for the drawing cache's bitmap
17164     *
17165     * @see #setDrawingCacheEnabled(boolean)
17166     * @see #buildDrawingCache()
17167     * @see #getDrawingCache()
17168     */
17169    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
17170        if (color != mDrawingCacheBackgroundColor) {
17171            mDrawingCacheBackgroundColor = color;
17172            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
17173        }
17174    }
17175
17176    /**
17177     * @see #setDrawingCacheBackgroundColor(int)
17178     *
17179     * @return The background color to used for the drawing cache's bitmap
17180     */
17181    @ColorInt
17182    public int getDrawingCacheBackgroundColor() {
17183        return mDrawingCacheBackgroundColor;
17184    }
17185
17186    /**
17187     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
17188     *
17189     * @see #buildDrawingCache(boolean)
17190     */
17191    public void buildDrawingCache() {
17192        buildDrawingCache(false);
17193    }
17194
17195    /**
17196     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
17197     *
17198     * <p>If you call {@link #buildDrawingCache()} manually without calling
17199     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17200     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
17201     *
17202     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17203     * this method will create a bitmap of the same size as this view. Because this bitmap
17204     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17205     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17206     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17207     * size than the view. This implies that your application must be able to handle this
17208     * size.</p>
17209     *
17210     * <p>You should avoid calling this method when hardware acceleration is enabled. If
17211     * you do not need the drawing cache bitmap, calling this method will increase memory
17212     * usage and cause the view to be rendered in software once, thus negatively impacting
17213     * performance.</p>
17214     *
17215     * @see #getDrawingCache()
17216     * @see #destroyDrawingCache()
17217     */
17218    public void buildDrawingCache(boolean autoScale) {
17219        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
17220                mDrawingCache == null : mUnscaledDrawingCache == null)) {
17221            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
17222                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
17223                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
17224            }
17225            try {
17226                buildDrawingCacheImpl(autoScale);
17227            } finally {
17228                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
17229            }
17230        }
17231    }
17232
17233    /**
17234     * private, internal implementation of buildDrawingCache, used to enable tracing
17235     */
17236    private void buildDrawingCacheImpl(boolean autoScale) {
17237        mCachingFailed = false;
17238
17239        int width = mRight - mLeft;
17240        int height = mBottom - mTop;
17241
17242        final AttachInfo attachInfo = mAttachInfo;
17243        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
17244
17245        if (autoScale && scalingRequired) {
17246            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
17247            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
17248        }
17249
17250        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
17251        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
17252        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
17253
17254        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
17255        final long drawingCacheSize =
17256                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
17257        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
17258            if (width > 0 && height > 0) {
17259                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
17260                        + " too large to fit into a software layer (or drawing cache), needs "
17261                        + projectedBitmapSize + " bytes, only "
17262                        + drawingCacheSize + " available");
17263            }
17264            destroyDrawingCache();
17265            mCachingFailed = true;
17266            return;
17267        }
17268
17269        boolean clear = true;
17270        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
17271
17272        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
17273            Bitmap.Config quality;
17274            if (!opaque) {
17275                // Never pick ARGB_4444 because it looks awful
17276                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
17277                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
17278                    case DRAWING_CACHE_QUALITY_AUTO:
17279                    case DRAWING_CACHE_QUALITY_LOW:
17280                    case DRAWING_CACHE_QUALITY_HIGH:
17281                    default:
17282                        quality = Bitmap.Config.ARGB_8888;
17283                        break;
17284                }
17285            } else {
17286                // Optimization for translucent windows
17287                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
17288                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
17289            }
17290
17291            // Try to cleanup memory
17292            if (bitmap != null) bitmap.recycle();
17293
17294            try {
17295                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17296                        width, height, quality);
17297                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
17298                if (autoScale) {
17299                    mDrawingCache = bitmap;
17300                } else {
17301                    mUnscaledDrawingCache = bitmap;
17302                }
17303                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
17304            } catch (OutOfMemoryError e) {
17305                // If there is not enough memory to create the bitmap cache, just
17306                // ignore the issue as bitmap caches are not required to draw the
17307                // view hierarchy
17308                if (autoScale) {
17309                    mDrawingCache = null;
17310                } else {
17311                    mUnscaledDrawingCache = null;
17312                }
17313                mCachingFailed = true;
17314                return;
17315            }
17316
17317            clear = drawingCacheBackgroundColor != 0;
17318        }
17319
17320        Canvas canvas;
17321        if (attachInfo != null) {
17322            canvas = attachInfo.mCanvas;
17323            if (canvas == null) {
17324                canvas = new Canvas();
17325            }
17326            canvas.setBitmap(bitmap);
17327            // Temporarily clobber the cached Canvas in case one of our children
17328            // is also using a drawing cache. Without this, the children would
17329            // steal the canvas by attaching their own bitmap to it and bad, bad
17330            // thing would happen (invisible views, corrupted drawings, etc.)
17331            attachInfo.mCanvas = null;
17332        } else {
17333            // This case should hopefully never or seldom happen
17334            canvas = new Canvas(bitmap);
17335        }
17336
17337        if (clear) {
17338            bitmap.eraseColor(drawingCacheBackgroundColor);
17339        }
17340
17341        computeScroll();
17342        final int restoreCount = canvas.save();
17343
17344        if (autoScale && scalingRequired) {
17345            final float scale = attachInfo.mApplicationScale;
17346            canvas.scale(scale, scale);
17347        }
17348
17349        canvas.translate(-mScrollX, -mScrollY);
17350
17351        mPrivateFlags |= PFLAG_DRAWN;
17352        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
17353                mLayerType != LAYER_TYPE_NONE) {
17354            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
17355        }
17356
17357        // Fast path for layouts with no backgrounds
17358        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17359            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17360            dispatchDraw(canvas);
17361            if (mOverlay != null && !mOverlay.isEmpty()) {
17362                mOverlay.getOverlayView().draw(canvas);
17363            }
17364        } else {
17365            draw(canvas);
17366        }
17367
17368        canvas.restoreToCount(restoreCount);
17369        canvas.setBitmap(null);
17370
17371        if (attachInfo != null) {
17372            // Restore the cached Canvas for our siblings
17373            attachInfo.mCanvas = canvas;
17374        }
17375    }
17376
17377    /**
17378     * Create a snapshot of the view into a bitmap.  We should probably make
17379     * some form of this public, but should think about the API.
17380     *
17381     * @hide
17382     */
17383    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
17384        int width = mRight - mLeft;
17385        int height = mBottom - mTop;
17386
17387        final AttachInfo attachInfo = mAttachInfo;
17388        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
17389        width = (int) ((width * scale) + 0.5f);
17390        height = (int) ((height * scale) + 0.5f);
17391
17392        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17393                width > 0 ? width : 1, height > 0 ? height : 1, quality);
17394        if (bitmap == null) {
17395            throw new OutOfMemoryError();
17396        }
17397
17398        Resources resources = getResources();
17399        if (resources != null) {
17400            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
17401        }
17402
17403        Canvas canvas;
17404        if (attachInfo != null) {
17405            canvas = attachInfo.mCanvas;
17406            if (canvas == null) {
17407                canvas = new Canvas();
17408            }
17409            canvas.setBitmap(bitmap);
17410            // Temporarily clobber the cached Canvas in case one of our children
17411            // is also using a drawing cache. Without this, the children would
17412            // steal the canvas by attaching their own bitmap to it and bad, bad
17413            // things would happen (invisible views, corrupted drawings, etc.)
17414            attachInfo.mCanvas = null;
17415        } else {
17416            // This case should hopefully never or seldom happen
17417            canvas = new Canvas(bitmap);
17418        }
17419
17420        if ((backgroundColor & 0xff000000) != 0) {
17421            bitmap.eraseColor(backgroundColor);
17422        }
17423
17424        computeScroll();
17425        final int restoreCount = canvas.save();
17426        canvas.scale(scale, scale);
17427        canvas.translate(-mScrollX, -mScrollY);
17428
17429        // Temporarily remove the dirty mask
17430        int flags = mPrivateFlags;
17431        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17432
17433        // Fast path for layouts with no backgrounds
17434        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17435            dispatchDraw(canvas);
17436            if (mOverlay != null && !mOverlay.isEmpty()) {
17437                mOverlay.getOverlayView().draw(canvas);
17438            }
17439        } else {
17440            draw(canvas);
17441        }
17442
17443        mPrivateFlags = flags;
17444
17445        canvas.restoreToCount(restoreCount);
17446        canvas.setBitmap(null);
17447
17448        if (attachInfo != null) {
17449            // Restore the cached Canvas for our siblings
17450            attachInfo.mCanvas = canvas;
17451        }
17452
17453        return bitmap;
17454    }
17455
17456    /**
17457     * Indicates whether this View is currently in edit mode. A View is usually
17458     * in edit mode when displayed within a developer tool. For instance, if
17459     * this View is being drawn by a visual user interface builder, this method
17460     * should return true.
17461     *
17462     * Subclasses should check the return value of this method to provide
17463     * different behaviors if their normal behavior might interfere with the
17464     * host environment. For instance: the class spawns a thread in its
17465     * constructor, the drawing code relies on device-specific features, etc.
17466     *
17467     * This method is usually checked in the drawing code of custom widgets.
17468     *
17469     * @return True if this View is in edit mode, false otherwise.
17470     */
17471    public boolean isInEditMode() {
17472        return false;
17473    }
17474
17475    /**
17476     * If the View draws content inside its padding and enables fading edges,
17477     * it needs to support padding offsets. Padding offsets are added to the
17478     * fading edges to extend the length of the fade so that it covers pixels
17479     * drawn inside the padding.
17480     *
17481     * Subclasses of this class should override this method if they need
17482     * to draw content inside the padding.
17483     *
17484     * @return True if padding offset must be applied, false otherwise.
17485     *
17486     * @see #getLeftPaddingOffset()
17487     * @see #getRightPaddingOffset()
17488     * @see #getTopPaddingOffset()
17489     * @see #getBottomPaddingOffset()
17490     *
17491     * @since CURRENT
17492     */
17493    protected boolean isPaddingOffsetRequired() {
17494        return false;
17495    }
17496
17497    /**
17498     * Amount by which to extend the left fading region. Called only when
17499     * {@link #isPaddingOffsetRequired()} returns true.
17500     *
17501     * @return The left padding offset in pixels.
17502     *
17503     * @see #isPaddingOffsetRequired()
17504     *
17505     * @since CURRENT
17506     */
17507    protected int getLeftPaddingOffset() {
17508        return 0;
17509    }
17510
17511    /**
17512     * Amount by which to extend the right fading region. Called only when
17513     * {@link #isPaddingOffsetRequired()} returns true.
17514     *
17515     * @return The right padding offset in pixels.
17516     *
17517     * @see #isPaddingOffsetRequired()
17518     *
17519     * @since CURRENT
17520     */
17521    protected int getRightPaddingOffset() {
17522        return 0;
17523    }
17524
17525    /**
17526     * Amount by which to extend the top fading region. Called only when
17527     * {@link #isPaddingOffsetRequired()} returns true.
17528     *
17529     * @return The top padding offset in pixels.
17530     *
17531     * @see #isPaddingOffsetRequired()
17532     *
17533     * @since CURRENT
17534     */
17535    protected int getTopPaddingOffset() {
17536        return 0;
17537    }
17538
17539    /**
17540     * Amount by which to extend the bottom fading region. Called only when
17541     * {@link #isPaddingOffsetRequired()} returns true.
17542     *
17543     * @return The bottom padding offset in pixels.
17544     *
17545     * @see #isPaddingOffsetRequired()
17546     *
17547     * @since CURRENT
17548     */
17549    protected int getBottomPaddingOffset() {
17550        return 0;
17551    }
17552
17553    /**
17554     * @hide
17555     * @param offsetRequired
17556     */
17557    protected int getFadeTop(boolean offsetRequired) {
17558        int top = mPaddingTop;
17559        if (offsetRequired) top += getTopPaddingOffset();
17560        return top;
17561    }
17562
17563    /**
17564     * @hide
17565     * @param offsetRequired
17566     */
17567    protected int getFadeHeight(boolean offsetRequired) {
17568        int padding = mPaddingTop;
17569        if (offsetRequired) padding += getTopPaddingOffset();
17570        return mBottom - mTop - mPaddingBottom - padding;
17571    }
17572
17573    /**
17574     * <p>Indicates whether this view is attached to a hardware accelerated
17575     * window or not.</p>
17576     *
17577     * <p>Even if this method returns true, it does not mean that every call
17578     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
17579     * accelerated {@link android.graphics.Canvas}. For instance, if this view
17580     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
17581     * window is hardware accelerated,
17582     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
17583     * return false, and this method will return true.</p>
17584     *
17585     * @return True if the view is attached to a window and the window is
17586     *         hardware accelerated; false in any other case.
17587     */
17588    @ViewDebug.ExportedProperty(category = "drawing")
17589    public boolean isHardwareAccelerated() {
17590        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
17591    }
17592
17593    /**
17594     * Sets a rectangular area on this view to which the view will be clipped
17595     * when it is drawn. Setting the value to null will remove the clip bounds
17596     * and the view will draw normally, using its full bounds.
17597     *
17598     * @param clipBounds The rectangular area, in the local coordinates of
17599     * this view, to which future drawing operations will be clipped.
17600     */
17601    public void setClipBounds(Rect clipBounds) {
17602        if (clipBounds == mClipBounds
17603                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
17604            return;
17605        }
17606        if (clipBounds != null) {
17607            if (mClipBounds == null) {
17608                mClipBounds = new Rect(clipBounds);
17609            } else {
17610                mClipBounds.set(clipBounds);
17611            }
17612        } else {
17613            mClipBounds = null;
17614        }
17615        mRenderNode.setClipBounds(mClipBounds);
17616        invalidateViewProperty(false, false);
17617    }
17618
17619    /**
17620     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
17621     *
17622     * @return A copy of the current clip bounds if clip bounds are set,
17623     * otherwise null.
17624     */
17625    public Rect getClipBounds() {
17626        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
17627    }
17628
17629
17630    /**
17631     * Populates an output rectangle with the clip bounds of the view,
17632     * returning {@code true} if successful or {@code false} if the view's
17633     * clip bounds are {@code null}.
17634     *
17635     * @param outRect rectangle in which to place the clip bounds of the view
17636     * @return {@code true} if successful or {@code false} if the view's
17637     *         clip bounds are {@code null}
17638     */
17639    public boolean getClipBounds(Rect outRect) {
17640        if (mClipBounds != null) {
17641            outRect.set(mClipBounds);
17642            return true;
17643        }
17644        return false;
17645    }
17646
17647    /**
17648     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
17649     * case of an active Animation being run on the view.
17650     */
17651    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
17652            Animation a, boolean scalingRequired) {
17653        Transformation invalidationTransform;
17654        final int flags = parent.mGroupFlags;
17655        final boolean initialized = a.isInitialized();
17656        if (!initialized) {
17657            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
17658            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
17659            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
17660            onAnimationStart();
17661        }
17662
17663        final Transformation t = parent.getChildTransformation();
17664        boolean more = a.getTransformation(drawingTime, t, 1f);
17665        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
17666            if (parent.mInvalidationTransformation == null) {
17667                parent.mInvalidationTransformation = new Transformation();
17668            }
17669            invalidationTransform = parent.mInvalidationTransformation;
17670            a.getTransformation(drawingTime, invalidationTransform, 1f);
17671        } else {
17672            invalidationTransform = t;
17673        }
17674
17675        if (more) {
17676            if (!a.willChangeBounds()) {
17677                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
17678                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
17679                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
17680                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
17681                    // The child need to draw an animation, potentially offscreen, so
17682                    // make sure we do not cancel invalidate requests
17683                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17684                    parent.invalidate(mLeft, mTop, mRight, mBottom);
17685                }
17686            } else {
17687                if (parent.mInvalidateRegion == null) {
17688                    parent.mInvalidateRegion = new RectF();
17689                }
17690                final RectF region = parent.mInvalidateRegion;
17691                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
17692                        invalidationTransform);
17693
17694                // The child need to draw an animation, potentially offscreen, so
17695                // make sure we do not cancel invalidate requests
17696                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17697
17698                final int left = mLeft + (int) region.left;
17699                final int top = mTop + (int) region.top;
17700                parent.invalidate(left, top, left + (int) (region.width() + .5f),
17701                        top + (int) (region.height() + .5f));
17702            }
17703        }
17704        return more;
17705    }
17706
17707    /**
17708     * This method is called by getDisplayList() when a display list is recorded for a View.
17709     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
17710     */
17711    void setDisplayListProperties(RenderNode renderNode) {
17712        if (renderNode != null) {
17713            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
17714            renderNode.setClipToBounds(mParent instanceof ViewGroup
17715                    && ((ViewGroup) mParent).getClipChildren());
17716
17717            float alpha = 1;
17718            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
17719                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17720                ViewGroup parentVG = (ViewGroup) mParent;
17721                final Transformation t = parentVG.getChildTransformation();
17722                if (parentVG.getChildStaticTransformation(this, t)) {
17723                    final int transformType = t.getTransformationType();
17724                    if (transformType != Transformation.TYPE_IDENTITY) {
17725                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
17726                            alpha = t.getAlpha();
17727                        }
17728                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
17729                            renderNode.setStaticMatrix(t.getMatrix());
17730                        }
17731                    }
17732                }
17733            }
17734            if (mTransformationInfo != null) {
17735                alpha *= getFinalAlpha();
17736                if (alpha < 1) {
17737                    final int multipliedAlpha = (int) (255 * alpha);
17738                    if (onSetAlpha(multipliedAlpha)) {
17739                        alpha = 1;
17740                    }
17741                }
17742                renderNode.setAlpha(alpha);
17743            } else if (alpha < 1) {
17744                renderNode.setAlpha(alpha);
17745            }
17746        }
17747    }
17748
17749    /**
17750     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
17751     *
17752     * This is where the View specializes rendering behavior based on layer type,
17753     * and hardware acceleration.
17754     */
17755    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
17756        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
17757        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
17758         *
17759         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
17760         * HW accelerated, it can't handle drawing RenderNodes.
17761         */
17762        boolean drawingWithRenderNode = mAttachInfo != null
17763                && mAttachInfo.mHardwareAccelerated
17764                && hardwareAcceleratedCanvas;
17765
17766        boolean more = false;
17767        final boolean childHasIdentityMatrix = hasIdentityMatrix();
17768        final int parentFlags = parent.mGroupFlags;
17769
17770        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
17771            parent.getChildTransformation().clear();
17772            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17773        }
17774
17775        Transformation transformToApply = null;
17776        boolean concatMatrix = false;
17777        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
17778        final Animation a = getAnimation();
17779        if (a != null) {
17780            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
17781            concatMatrix = a.willChangeTransformationMatrix();
17782            if (concatMatrix) {
17783                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17784            }
17785            transformToApply = parent.getChildTransformation();
17786        } else {
17787            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
17788                // No longer animating: clear out old animation matrix
17789                mRenderNode.setAnimationMatrix(null);
17790                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17791            }
17792            if (!drawingWithRenderNode
17793                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17794                final Transformation t = parent.getChildTransformation();
17795                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
17796                if (hasTransform) {
17797                    final int transformType = t.getTransformationType();
17798                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
17799                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
17800                }
17801            }
17802        }
17803
17804        concatMatrix |= !childHasIdentityMatrix;
17805
17806        // Sets the flag as early as possible to allow draw() implementations
17807        // to call invalidate() successfully when doing animations
17808        mPrivateFlags |= PFLAG_DRAWN;
17809
17810        if (!concatMatrix &&
17811                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
17812                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
17813                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
17814                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
17815            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
17816            return more;
17817        }
17818        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
17819
17820        if (hardwareAcceleratedCanvas) {
17821            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
17822            // retain the flag's value temporarily in the mRecreateDisplayList flag
17823            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
17824            mPrivateFlags &= ~PFLAG_INVALIDATED;
17825        }
17826
17827        RenderNode renderNode = null;
17828        Bitmap cache = null;
17829        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
17830        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
17831             if (layerType != LAYER_TYPE_NONE) {
17832                 // If not drawing with RenderNode, treat HW layers as SW
17833                 layerType = LAYER_TYPE_SOFTWARE;
17834                 buildDrawingCache(true);
17835            }
17836            cache = getDrawingCache(true);
17837        }
17838
17839        if (drawingWithRenderNode) {
17840            // Delay getting the display list until animation-driven alpha values are
17841            // set up and possibly passed on to the view
17842            renderNode = updateDisplayListIfDirty();
17843            if (!renderNode.isValid()) {
17844                // Uncommon, but possible. If a view is removed from the hierarchy during the call
17845                // to getDisplayList(), the display list will be marked invalid and we should not
17846                // try to use it again.
17847                renderNode = null;
17848                drawingWithRenderNode = false;
17849            }
17850        }
17851
17852        int sx = 0;
17853        int sy = 0;
17854        if (!drawingWithRenderNode) {
17855            computeScroll();
17856            sx = mScrollX;
17857            sy = mScrollY;
17858        }
17859
17860        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
17861        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
17862
17863        int restoreTo = -1;
17864        if (!drawingWithRenderNode || transformToApply != null) {
17865            restoreTo = canvas.save();
17866        }
17867        if (offsetForScroll) {
17868            canvas.translate(mLeft - sx, mTop - sy);
17869        } else {
17870            if (!drawingWithRenderNode) {
17871                canvas.translate(mLeft, mTop);
17872            }
17873            if (scalingRequired) {
17874                if (drawingWithRenderNode) {
17875                    // TODO: Might not need this if we put everything inside the DL
17876                    restoreTo = canvas.save();
17877                }
17878                // mAttachInfo cannot be null, otherwise scalingRequired == false
17879                final float scale = 1.0f / mAttachInfo.mApplicationScale;
17880                canvas.scale(scale, scale);
17881            }
17882        }
17883
17884        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
17885        if (transformToApply != null
17886                || alpha < 1
17887                || !hasIdentityMatrix()
17888                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17889            if (transformToApply != null || !childHasIdentityMatrix) {
17890                int transX = 0;
17891                int transY = 0;
17892
17893                if (offsetForScroll) {
17894                    transX = -sx;
17895                    transY = -sy;
17896                }
17897
17898                if (transformToApply != null) {
17899                    if (concatMatrix) {
17900                        if (drawingWithRenderNode) {
17901                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17902                        } else {
17903                            // Undo the scroll translation, apply the transformation matrix,
17904                            // then redo the scroll translate to get the correct result.
17905                            canvas.translate(-transX, -transY);
17906                            canvas.concat(transformToApply.getMatrix());
17907                            canvas.translate(transX, transY);
17908                        }
17909                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17910                    }
17911
17912                    float transformAlpha = transformToApply.getAlpha();
17913                    if (transformAlpha < 1) {
17914                        alpha *= transformAlpha;
17915                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17916                    }
17917                }
17918
17919                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17920                    canvas.translate(-transX, -transY);
17921                    canvas.concat(getMatrix());
17922                    canvas.translate(transX, transY);
17923                }
17924            }
17925
17926            // Deal with alpha if it is or used to be <1
17927            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17928                if (alpha < 1) {
17929                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17930                } else {
17931                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17932                }
17933                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17934                if (!drawingWithDrawingCache) {
17935                    final int multipliedAlpha = (int) (255 * alpha);
17936                    if (!onSetAlpha(multipliedAlpha)) {
17937                        if (drawingWithRenderNode) {
17938                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17939                        } else if (layerType == LAYER_TYPE_NONE) {
17940                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17941                                    multipliedAlpha);
17942                        }
17943                    } else {
17944                        // Alpha is handled by the child directly, clobber the layer's alpha
17945                        mPrivateFlags |= PFLAG_ALPHA_SET;
17946                    }
17947                }
17948            }
17949        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17950            onSetAlpha(255);
17951            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17952        }
17953
17954        if (!drawingWithRenderNode) {
17955            // apply clips directly, since RenderNode won't do it for this draw
17956            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17957                if (offsetForScroll) {
17958                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17959                } else {
17960                    if (!scalingRequired || cache == null) {
17961                        canvas.clipRect(0, 0, getWidth(), getHeight());
17962                    } else {
17963                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17964                    }
17965                }
17966            }
17967
17968            if (mClipBounds != null) {
17969                // clip bounds ignore scroll
17970                canvas.clipRect(mClipBounds);
17971            }
17972        }
17973
17974        if (!drawingWithDrawingCache) {
17975            if (drawingWithRenderNode) {
17976                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17977                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17978            } else {
17979                // Fast path for layouts with no backgrounds
17980                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17981                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17982                    dispatchDraw(canvas);
17983                } else {
17984                    draw(canvas);
17985                }
17986            }
17987        } else if (cache != null) {
17988            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17989            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17990                // no layer paint, use temporary paint to draw bitmap
17991                Paint cachePaint = parent.mCachePaint;
17992                if (cachePaint == null) {
17993                    cachePaint = new Paint();
17994                    cachePaint.setDither(false);
17995                    parent.mCachePaint = cachePaint;
17996                }
17997                cachePaint.setAlpha((int) (alpha * 255));
17998                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17999            } else {
18000                // use layer paint to draw the bitmap, merging the two alphas, but also restore
18001                int layerPaintAlpha = mLayerPaint.getAlpha();
18002                if (alpha < 1) {
18003                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
18004                }
18005                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
18006                if (alpha < 1) {
18007                    mLayerPaint.setAlpha(layerPaintAlpha);
18008                }
18009            }
18010        }
18011
18012        if (restoreTo >= 0) {
18013            canvas.restoreToCount(restoreTo);
18014        }
18015
18016        if (a != null && !more) {
18017            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
18018                onSetAlpha(255);
18019            }
18020            parent.finishAnimatingView(this, a);
18021        }
18022
18023        if (more && hardwareAcceleratedCanvas) {
18024            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
18025                // alpha animations should cause the child to recreate its display list
18026                invalidate(true);
18027            }
18028        }
18029
18030        mRecreateDisplayList = false;
18031
18032        return more;
18033    }
18034
18035    static Paint getDebugPaint() {
18036        if (sDebugPaint == null) {
18037            sDebugPaint = new Paint();
18038            sDebugPaint.setAntiAlias(false);
18039        }
18040        return sDebugPaint;
18041    }
18042
18043    final int dipsToPixels(int dips) {
18044        float scale = getContext().getResources().getDisplayMetrics().density;
18045        return (int) (dips * scale + 0.5f);
18046    }
18047
18048    final private void debugDrawFocus(Canvas canvas) {
18049        if (isFocused()) {
18050            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
18051            final int l = mScrollX;
18052            final int r = l + mRight - mLeft;
18053            final int t = mScrollY;
18054            final int b = t + mBottom - mTop;
18055
18056            final Paint paint = getDebugPaint();
18057            paint.setColor(DEBUG_CORNERS_COLOR);
18058
18059            // Draw squares in corners.
18060            paint.setStyle(Paint.Style.FILL);
18061            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
18062            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
18063            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
18064            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
18065
18066            // Draw big X across the view.
18067            paint.setStyle(Paint.Style.STROKE);
18068            canvas.drawLine(l, t, r, b, paint);
18069            canvas.drawLine(l, b, r, t, paint);
18070        }
18071    }
18072
18073    /**
18074     * Manually render this view (and all of its children) to the given Canvas.
18075     * The view must have already done a full layout before this function is
18076     * called.  When implementing a view, implement
18077     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
18078     * If you do need to override this method, call the superclass version.
18079     *
18080     * @param canvas The Canvas to which the View is rendered.
18081     */
18082    @CallSuper
18083    public void draw(Canvas canvas) {
18084        final int privateFlags = mPrivateFlags;
18085        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
18086                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
18087        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
18088
18089        /*
18090         * Draw traversal performs several drawing steps which must be executed
18091         * in the appropriate order:
18092         *
18093         *      1. Draw the background
18094         *      2. If necessary, save the canvas' layers to prepare for fading
18095         *      3. Draw view's content
18096         *      4. Draw children
18097         *      5. If necessary, draw the fading edges and restore layers
18098         *      6. Draw decorations (scrollbars for instance)
18099         */
18100
18101        // Step 1, draw the background, if needed
18102        int saveCount;
18103
18104        if (!dirtyOpaque) {
18105            drawBackground(canvas);
18106        }
18107
18108        // skip step 2 & 5 if possible (common case)
18109        final int viewFlags = mViewFlags;
18110        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
18111        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
18112        if (!verticalEdges && !horizontalEdges) {
18113            // Step 3, draw the content
18114            if (!dirtyOpaque) onDraw(canvas);
18115
18116            // Step 4, draw the children
18117            dispatchDraw(canvas);
18118
18119            // Overlay is part of the content and draws beneath Foreground
18120            if (mOverlay != null && !mOverlay.isEmpty()) {
18121                mOverlay.getOverlayView().dispatchDraw(canvas);
18122            }
18123
18124            // Step 6, draw decorations (foreground, scrollbars)
18125            onDrawForeground(canvas);
18126
18127            if (debugDraw()) {
18128                debugDrawFocus(canvas);
18129            }
18130
18131            // we're done...
18132            return;
18133        }
18134
18135        /*
18136         * Here we do the full fledged routine...
18137         * (this is an uncommon case where speed matters less,
18138         * this is why we repeat some of the tests that have been
18139         * done above)
18140         */
18141
18142        boolean drawTop = false;
18143        boolean drawBottom = false;
18144        boolean drawLeft = false;
18145        boolean drawRight = false;
18146
18147        float topFadeStrength = 0.0f;
18148        float bottomFadeStrength = 0.0f;
18149        float leftFadeStrength = 0.0f;
18150        float rightFadeStrength = 0.0f;
18151
18152        // Step 2, save the canvas' layers
18153        int paddingLeft = mPaddingLeft;
18154
18155        final boolean offsetRequired = isPaddingOffsetRequired();
18156        if (offsetRequired) {
18157            paddingLeft += getLeftPaddingOffset();
18158        }
18159
18160        int left = mScrollX + paddingLeft;
18161        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
18162        int top = mScrollY + getFadeTop(offsetRequired);
18163        int bottom = top + getFadeHeight(offsetRequired);
18164
18165        if (offsetRequired) {
18166            right += getRightPaddingOffset();
18167            bottom += getBottomPaddingOffset();
18168        }
18169
18170        final ScrollabilityCache scrollabilityCache = mScrollCache;
18171        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
18172        int length = (int) fadeHeight;
18173
18174        // clip the fade length if top and bottom fades overlap
18175        // overlapping fades produce odd-looking artifacts
18176        if (verticalEdges && (top + length > bottom - length)) {
18177            length = (bottom - top) / 2;
18178        }
18179
18180        // also clip horizontal fades if necessary
18181        if (horizontalEdges && (left + length > right - length)) {
18182            length = (right - left) / 2;
18183        }
18184
18185        if (verticalEdges) {
18186            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
18187            drawTop = topFadeStrength * fadeHeight > 1.0f;
18188            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
18189            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
18190        }
18191
18192        if (horizontalEdges) {
18193            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
18194            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
18195            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
18196            drawRight = rightFadeStrength * fadeHeight > 1.0f;
18197        }
18198
18199        saveCount = canvas.getSaveCount();
18200
18201        int solidColor = getSolidColor();
18202        if (solidColor == 0) {
18203            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
18204
18205            if (drawTop) {
18206                canvas.saveLayer(left, top, right, top + length, null, flags);
18207            }
18208
18209            if (drawBottom) {
18210                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
18211            }
18212
18213            if (drawLeft) {
18214                canvas.saveLayer(left, top, left + length, bottom, null, flags);
18215            }
18216
18217            if (drawRight) {
18218                canvas.saveLayer(right - length, top, right, bottom, null, flags);
18219            }
18220        } else {
18221            scrollabilityCache.setFadeColor(solidColor);
18222        }
18223
18224        // Step 3, draw the content
18225        if (!dirtyOpaque) onDraw(canvas);
18226
18227        // Step 4, draw the children
18228        dispatchDraw(canvas);
18229
18230        // Step 5, draw the fade effect and restore layers
18231        final Paint p = scrollabilityCache.paint;
18232        final Matrix matrix = scrollabilityCache.matrix;
18233        final Shader fade = scrollabilityCache.shader;
18234
18235        if (drawTop) {
18236            matrix.setScale(1, fadeHeight * topFadeStrength);
18237            matrix.postTranslate(left, top);
18238            fade.setLocalMatrix(matrix);
18239            p.setShader(fade);
18240            canvas.drawRect(left, top, right, top + length, p);
18241        }
18242
18243        if (drawBottom) {
18244            matrix.setScale(1, fadeHeight * bottomFadeStrength);
18245            matrix.postRotate(180);
18246            matrix.postTranslate(left, bottom);
18247            fade.setLocalMatrix(matrix);
18248            p.setShader(fade);
18249            canvas.drawRect(left, bottom - length, right, bottom, p);
18250        }
18251
18252        if (drawLeft) {
18253            matrix.setScale(1, fadeHeight * leftFadeStrength);
18254            matrix.postRotate(-90);
18255            matrix.postTranslate(left, top);
18256            fade.setLocalMatrix(matrix);
18257            p.setShader(fade);
18258            canvas.drawRect(left, top, left + length, bottom, p);
18259        }
18260
18261        if (drawRight) {
18262            matrix.setScale(1, fadeHeight * rightFadeStrength);
18263            matrix.postRotate(90);
18264            matrix.postTranslate(right, top);
18265            fade.setLocalMatrix(matrix);
18266            p.setShader(fade);
18267            canvas.drawRect(right - length, top, right, bottom, p);
18268        }
18269
18270        canvas.restoreToCount(saveCount);
18271
18272        // Overlay is part of the content and draws beneath Foreground
18273        if (mOverlay != null && !mOverlay.isEmpty()) {
18274            mOverlay.getOverlayView().dispatchDraw(canvas);
18275        }
18276
18277        // Step 6, draw decorations (foreground, scrollbars)
18278        onDrawForeground(canvas);
18279
18280        if (debugDraw()) {
18281            debugDrawFocus(canvas);
18282        }
18283    }
18284
18285    /**
18286     * Draws the background onto the specified canvas.
18287     *
18288     * @param canvas Canvas on which to draw the background
18289     */
18290    private void drawBackground(Canvas canvas) {
18291        final Drawable background = mBackground;
18292        if (background == null) {
18293            return;
18294        }
18295
18296        setBackgroundBounds();
18297
18298        // Attempt to use a display list if requested.
18299        if (canvas.isHardwareAccelerated() && mAttachInfo != null
18300                && mAttachInfo.mThreadedRenderer != null) {
18301            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
18302
18303            final RenderNode renderNode = mBackgroundRenderNode;
18304            if (renderNode != null && renderNode.isValid()) {
18305                setBackgroundRenderNodeProperties(renderNode);
18306                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18307                return;
18308            }
18309        }
18310
18311        final int scrollX = mScrollX;
18312        final int scrollY = mScrollY;
18313        if ((scrollX | scrollY) == 0) {
18314            background.draw(canvas);
18315        } else {
18316            canvas.translate(scrollX, scrollY);
18317            background.draw(canvas);
18318            canvas.translate(-scrollX, -scrollY);
18319        }
18320    }
18321
18322    /**
18323     * Sets the correct background bounds and rebuilds the outline, if needed.
18324     * <p/>
18325     * This is called by LayoutLib.
18326     */
18327    void setBackgroundBounds() {
18328        if (mBackgroundSizeChanged && mBackground != null) {
18329            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
18330            mBackgroundSizeChanged = false;
18331            rebuildOutline();
18332        }
18333    }
18334
18335    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
18336        renderNode.setTranslationX(mScrollX);
18337        renderNode.setTranslationY(mScrollY);
18338    }
18339
18340    /**
18341     * Creates a new display list or updates the existing display list for the
18342     * specified Drawable.
18343     *
18344     * @param drawable Drawable for which to create a display list
18345     * @param renderNode Existing RenderNode, or {@code null}
18346     * @return A valid display list for the specified drawable
18347     */
18348    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
18349        if (renderNode == null) {
18350            renderNode = RenderNode.create(drawable.getClass().getName(), this);
18351        }
18352
18353        final Rect bounds = drawable.getBounds();
18354        final int width = bounds.width();
18355        final int height = bounds.height();
18356        final DisplayListCanvas canvas = renderNode.start(width, height);
18357
18358        // Reverse left/top translation done by drawable canvas, which will
18359        // instead be applied by rendernode's LTRB bounds below. This way, the
18360        // drawable's bounds match with its rendernode bounds and its content
18361        // will lie within those bounds in the rendernode tree.
18362        canvas.translate(-bounds.left, -bounds.top);
18363
18364        try {
18365            drawable.draw(canvas);
18366        } finally {
18367            renderNode.end(canvas);
18368        }
18369
18370        // Set up drawable properties that are view-independent.
18371        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
18372        renderNode.setProjectBackwards(drawable.isProjected());
18373        renderNode.setProjectionReceiver(true);
18374        renderNode.setClipToBounds(false);
18375        return renderNode;
18376    }
18377
18378    /**
18379     * Returns the overlay for this view, creating it if it does not yet exist.
18380     * Adding drawables to the overlay will cause them to be displayed whenever
18381     * the view itself is redrawn. Objects in the overlay should be actively
18382     * managed: remove them when they should not be displayed anymore. The
18383     * overlay will always have the same size as its host view.
18384     *
18385     * <p>Note: Overlays do not currently work correctly with {@link
18386     * SurfaceView} or {@link TextureView}; contents in overlays for these
18387     * types of views may not display correctly.</p>
18388     *
18389     * @return The ViewOverlay object for this view.
18390     * @see ViewOverlay
18391     */
18392    public ViewOverlay getOverlay() {
18393        if (mOverlay == null) {
18394            mOverlay = new ViewOverlay(mContext, this);
18395        }
18396        return mOverlay;
18397    }
18398
18399    /**
18400     * Override this if your view is known to always be drawn on top of a solid color background,
18401     * and needs to draw fading edges. Returning a non-zero color enables the view system to
18402     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
18403     * should be set to 0xFF.
18404     *
18405     * @see #setVerticalFadingEdgeEnabled(boolean)
18406     * @see #setHorizontalFadingEdgeEnabled(boolean)
18407     *
18408     * @return The known solid color background for this view, or 0 if the color may vary
18409     */
18410    @ViewDebug.ExportedProperty(category = "drawing")
18411    @ColorInt
18412    public int getSolidColor() {
18413        return 0;
18414    }
18415
18416    /**
18417     * Build a human readable string representation of the specified view flags.
18418     *
18419     * @param flags the view flags to convert to a string
18420     * @return a String representing the supplied flags
18421     */
18422    private static String printFlags(int flags) {
18423        String output = "";
18424        int numFlags = 0;
18425        if ((flags & FOCUSABLE) == FOCUSABLE) {
18426            output += "TAKES_FOCUS";
18427            numFlags++;
18428        }
18429
18430        switch (flags & VISIBILITY_MASK) {
18431        case INVISIBLE:
18432            if (numFlags > 0) {
18433                output += " ";
18434            }
18435            output += "INVISIBLE";
18436            // USELESS HERE numFlags++;
18437            break;
18438        case GONE:
18439            if (numFlags > 0) {
18440                output += " ";
18441            }
18442            output += "GONE";
18443            // USELESS HERE numFlags++;
18444            break;
18445        default:
18446            break;
18447        }
18448        return output;
18449    }
18450
18451    /**
18452     * Build a human readable string representation of the specified private
18453     * view flags.
18454     *
18455     * @param privateFlags the private view flags to convert to a string
18456     * @return a String representing the supplied flags
18457     */
18458    private static String printPrivateFlags(int privateFlags) {
18459        String output = "";
18460        int numFlags = 0;
18461
18462        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
18463            output += "WANTS_FOCUS";
18464            numFlags++;
18465        }
18466
18467        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
18468            if (numFlags > 0) {
18469                output += " ";
18470            }
18471            output += "FOCUSED";
18472            numFlags++;
18473        }
18474
18475        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
18476            if (numFlags > 0) {
18477                output += " ";
18478            }
18479            output += "SELECTED";
18480            numFlags++;
18481        }
18482
18483        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
18484            if (numFlags > 0) {
18485                output += " ";
18486            }
18487            output += "IS_ROOT_NAMESPACE";
18488            numFlags++;
18489        }
18490
18491        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
18492            if (numFlags > 0) {
18493                output += " ";
18494            }
18495            output += "HAS_BOUNDS";
18496            numFlags++;
18497        }
18498
18499        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
18500            if (numFlags > 0) {
18501                output += " ";
18502            }
18503            output += "DRAWN";
18504            // USELESS HERE numFlags++;
18505        }
18506        return output;
18507    }
18508
18509    /**
18510     * <p>Indicates whether or not this view's layout will be requested during
18511     * the next hierarchy layout pass.</p>
18512     *
18513     * @return true if the layout will be forced during next layout pass
18514     */
18515    public boolean isLayoutRequested() {
18516        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18517    }
18518
18519    /**
18520     * Return true if o is a ViewGroup that is laying out using optical bounds.
18521     * @hide
18522     */
18523    public static boolean isLayoutModeOptical(Object o) {
18524        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
18525    }
18526
18527    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
18528        Insets parentInsets = mParent instanceof View ?
18529                ((View) mParent).getOpticalInsets() : Insets.NONE;
18530        Insets childInsets = getOpticalInsets();
18531        return setFrame(
18532                left   + parentInsets.left - childInsets.left,
18533                top    + parentInsets.top  - childInsets.top,
18534                right  + parentInsets.left + childInsets.right,
18535                bottom + parentInsets.top  + childInsets.bottom);
18536    }
18537
18538    /**
18539     * Assign a size and position to a view and all of its
18540     * descendants
18541     *
18542     * <p>This is the second phase of the layout mechanism.
18543     * (The first is measuring). In this phase, each parent calls
18544     * layout on all of its children to position them.
18545     * This is typically done using the child measurements
18546     * that were stored in the measure pass().</p>
18547     *
18548     * <p>Derived classes should not override this method.
18549     * Derived classes with children should override
18550     * onLayout. In that method, they should
18551     * call layout on each of their children.</p>
18552     *
18553     * @param l Left position, relative to parent
18554     * @param t Top position, relative to parent
18555     * @param r Right position, relative to parent
18556     * @param b Bottom position, relative to parent
18557     */
18558    @SuppressWarnings({"unchecked"})
18559    public void layout(int l, int t, int r, int b) {
18560        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
18561            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
18562            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18563        }
18564
18565        int oldL = mLeft;
18566        int oldT = mTop;
18567        int oldB = mBottom;
18568        int oldR = mRight;
18569
18570        boolean changed = isLayoutModeOptical(mParent) ?
18571                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
18572
18573        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
18574            onLayout(changed, l, t, r, b);
18575
18576            if (shouldDrawRoundScrollbar()) {
18577                if(mRoundScrollbarRenderer == null) {
18578                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
18579                }
18580            } else {
18581                mRoundScrollbarRenderer = null;
18582            }
18583
18584            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
18585
18586            ListenerInfo li = mListenerInfo;
18587            if (li != null && li.mOnLayoutChangeListeners != null) {
18588                ArrayList<OnLayoutChangeListener> listenersCopy =
18589                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
18590                int numListeners = listenersCopy.size();
18591                for (int i = 0; i < numListeners; ++i) {
18592                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
18593                }
18594            }
18595        }
18596
18597        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
18598        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
18599    }
18600
18601    /**
18602     * Called from layout when this view should
18603     * assign a size and position to each of its children.
18604     *
18605     * Derived classes with children should override
18606     * this method and call layout on each of
18607     * their children.
18608     * @param changed This is a new size or position for this view
18609     * @param left Left position, relative to parent
18610     * @param top Top position, relative to parent
18611     * @param right Right position, relative to parent
18612     * @param bottom Bottom position, relative to parent
18613     */
18614    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
18615    }
18616
18617    /**
18618     * Assign a size and position to this view.
18619     *
18620     * This is called from layout.
18621     *
18622     * @param left Left position, relative to parent
18623     * @param top Top position, relative to parent
18624     * @param right Right position, relative to parent
18625     * @param bottom Bottom position, relative to parent
18626     * @return true if the new size and position are different than the
18627     *         previous ones
18628     * {@hide}
18629     */
18630    protected boolean setFrame(int left, int top, int right, int bottom) {
18631        boolean changed = false;
18632
18633        if (DBG) {
18634            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
18635                    + right + "," + bottom + ")");
18636        }
18637
18638        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
18639            changed = true;
18640
18641            // Remember our drawn bit
18642            int drawn = mPrivateFlags & PFLAG_DRAWN;
18643
18644            int oldWidth = mRight - mLeft;
18645            int oldHeight = mBottom - mTop;
18646            int newWidth = right - left;
18647            int newHeight = bottom - top;
18648            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
18649
18650            // Invalidate our old position
18651            invalidate(sizeChanged);
18652
18653            mLeft = left;
18654            mTop = top;
18655            mRight = right;
18656            mBottom = bottom;
18657            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
18658
18659            mPrivateFlags |= PFLAG_HAS_BOUNDS;
18660
18661
18662            if (sizeChanged) {
18663                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
18664            }
18665
18666            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
18667                // If we are visible, force the DRAWN bit to on so that
18668                // this invalidate will go through (at least to our parent).
18669                // This is because someone may have invalidated this view
18670                // before this call to setFrame came in, thereby clearing
18671                // the DRAWN bit.
18672                mPrivateFlags |= PFLAG_DRAWN;
18673                invalidate(sizeChanged);
18674                // parent display list may need to be recreated based on a change in the bounds
18675                // of any child
18676                invalidateParentCaches();
18677            }
18678
18679            // Reset drawn bit to original value (invalidate turns it off)
18680            mPrivateFlags |= drawn;
18681
18682            mBackgroundSizeChanged = true;
18683            if (mForegroundInfo != null) {
18684                mForegroundInfo.mBoundsChanged = true;
18685            }
18686
18687            notifySubtreeAccessibilityStateChangedIfNeeded();
18688        }
18689        return changed;
18690    }
18691
18692    /**
18693     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
18694     * @hide
18695     */
18696    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
18697        setFrame(left, top, right, bottom);
18698    }
18699
18700    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
18701        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
18702        if (mOverlay != null) {
18703            mOverlay.getOverlayView().setRight(newWidth);
18704            mOverlay.getOverlayView().setBottom(newHeight);
18705        }
18706        rebuildOutline();
18707    }
18708
18709    /**
18710     * Finalize inflating a view from XML.  This is called as the last phase
18711     * of inflation, after all child views have been added.
18712     *
18713     * <p>Even if the subclass overrides onFinishInflate, they should always be
18714     * sure to call the super method, so that we get called.
18715     */
18716    @CallSuper
18717    protected void onFinishInflate() {
18718    }
18719
18720    /**
18721     * Returns the resources associated with this view.
18722     *
18723     * @return Resources object.
18724     */
18725    public Resources getResources() {
18726        return mResources;
18727    }
18728
18729    /**
18730     * Invalidates the specified Drawable.
18731     *
18732     * @param drawable the drawable to invalidate
18733     */
18734    @Override
18735    public void invalidateDrawable(@NonNull Drawable drawable) {
18736        if (verifyDrawable(drawable)) {
18737            final Rect dirty = drawable.getDirtyBounds();
18738            final int scrollX = mScrollX;
18739            final int scrollY = mScrollY;
18740
18741            invalidate(dirty.left + scrollX, dirty.top + scrollY,
18742                    dirty.right + scrollX, dirty.bottom + scrollY);
18743            rebuildOutline();
18744        }
18745    }
18746
18747    /**
18748     * Schedules an action on a drawable to occur at a specified time.
18749     *
18750     * @param who the recipient of the action
18751     * @param what the action to run on the drawable
18752     * @param when the time at which the action must occur. Uses the
18753     *        {@link SystemClock#uptimeMillis} timebase.
18754     */
18755    @Override
18756    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
18757        if (verifyDrawable(who) && what != null) {
18758            final long delay = when - SystemClock.uptimeMillis();
18759            if (mAttachInfo != null) {
18760                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
18761                        Choreographer.CALLBACK_ANIMATION, what, who,
18762                        Choreographer.subtractFrameDelay(delay));
18763            } else {
18764                // Postpone the runnable until we know
18765                // on which thread it needs to run.
18766                getRunQueue().postDelayed(what, delay);
18767            }
18768        }
18769    }
18770
18771    /**
18772     * Cancels a scheduled action on a drawable.
18773     *
18774     * @param who the recipient of the action
18775     * @param what the action to cancel
18776     */
18777    @Override
18778    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
18779        if (verifyDrawable(who) && what != null) {
18780            if (mAttachInfo != null) {
18781                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18782                        Choreographer.CALLBACK_ANIMATION, what, who);
18783            }
18784            getRunQueue().removeCallbacks(what);
18785        }
18786    }
18787
18788    /**
18789     * Unschedule any events associated with the given Drawable.  This can be
18790     * used when selecting a new Drawable into a view, so that the previous
18791     * one is completely unscheduled.
18792     *
18793     * @param who The Drawable to unschedule.
18794     *
18795     * @see #drawableStateChanged
18796     */
18797    public void unscheduleDrawable(Drawable who) {
18798        if (mAttachInfo != null && who != null) {
18799            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18800                    Choreographer.CALLBACK_ANIMATION, null, who);
18801        }
18802    }
18803
18804    /**
18805     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
18806     * that the View directionality can and will be resolved before its Drawables.
18807     *
18808     * Will call {@link View#onResolveDrawables} when resolution is done.
18809     *
18810     * @hide
18811     */
18812    protected void resolveDrawables() {
18813        // Drawables resolution may need to happen before resolving the layout direction (which is
18814        // done only during the measure() call).
18815        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
18816        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
18817        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
18818        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
18819        // direction to be resolved as its resolved value will be the same as its raw value.
18820        if (!isLayoutDirectionResolved() &&
18821                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
18822            return;
18823        }
18824
18825        final int layoutDirection = isLayoutDirectionResolved() ?
18826                getLayoutDirection() : getRawLayoutDirection();
18827
18828        if (mBackground != null) {
18829            mBackground.setLayoutDirection(layoutDirection);
18830        }
18831        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18832            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
18833        }
18834        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
18835        onResolveDrawables(layoutDirection);
18836    }
18837
18838    boolean areDrawablesResolved() {
18839        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
18840    }
18841
18842    /**
18843     * Called when layout direction has been resolved.
18844     *
18845     * The default implementation does nothing.
18846     *
18847     * @param layoutDirection The resolved layout direction.
18848     *
18849     * @see #LAYOUT_DIRECTION_LTR
18850     * @see #LAYOUT_DIRECTION_RTL
18851     *
18852     * @hide
18853     */
18854    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
18855    }
18856
18857    /**
18858     * @hide
18859     */
18860    protected void resetResolvedDrawables() {
18861        resetResolvedDrawablesInternal();
18862    }
18863
18864    void resetResolvedDrawablesInternal() {
18865        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
18866    }
18867
18868    /**
18869     * If your view subclass is displaying its own Drawable objects, it should
18870     * override this function and return true for any Drawable it is
18871     * displaying.  This allows animations for those drawables to be
18872     * scheduled.
18873     *
18874     * <p>Be sure to call through to the super class when overriding this
18875     * function.
18876     *
18877     * @param who The Drawable to verify.  Return true if it is one you are
18878     *            displaying, else return the result of calling through to the
18879     *            super class.
18880     *
18881     * @return boolean If true than the Drawable is being displayed in the
18882     *         view; else false and it is not allowed to animate.
18883     *
18884     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
18885     * @see #drawableStateChanged()
18886     */
18887    @CallSuper
18888    protected boolean verifyDrawable(@NonNull Drawable who) {
18889        // Avoid verifying the scroll bar drawable so that we don't end up in
18890        // an invalidation loop. This effectively prevents the scroll bar
18891        // drawable from triggering invalidations and scheduling runnables.
18892        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
18893    }
18894
18895    /**
18896     * This function is called whenever the state of the view changes in such
18897     * a way that it impacts the state of drawables being shown.
18898     * <p>
18899     * If the View has a StateListAnimator, it will also be called to run necessary state
18900     * change animations.
18901     * <p>
18902     * Be sure to call through to the superclass when overriding this function.
18903     *
18904     * @see Drawable#setState(int[])
18905     */
18906    @CallSuper
18907    protected void drawableStateChanged() {
18908        final int[] state = getDrawableState();
18909        boolean changed = false;
18910
18911        final Drawable bg = mBackground;
18912        if (bg != null && bg.isStateful()) {
18913            changed |= bg.setState(state);
18914        }
18915
18916        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18917        if (fg != null && fg.isStateful()) {
18918            changed |= fg.setState(state);
18919        }
18920
18921        if (mScrollCache != null) {
18922            final Drawable scrollBar = mScrollCache.scrollBar;
18923            if (scrollBar != null && scrollBar.isStateful()) {
18924                changed |= scrollBar.setState(state)
18925                        && mScrollCache.state != ScrollabilityCache.OFF;
18926            }
18927        }
18928
18929        if (mStateListAnimator != null) {
18930            mStateListAnimator.setState(state);
18931        }
18932
18933        if (changed) {
18934            invalidate();
18935        }
18936    }
18937
18938    /**
18939     * This function is called whenever the view hotspot changes and needs to
18940     * be propagated to drawables or child views managed by the view.
18941     * <p>
18942     * Dispatching to child views is handled by
18943     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18944     * <p>
18945     * Be sure to call through to the superclass when overriding this function.
18946     *
18947     * @param x hotspot x coordinate
18948     * @param y hotspot y coordinate
18949     */
18950    @CallSuper
18951    public void drawableHotspotChanged(float x, float y) {
18952        if (mBackground != null) {
18953            mBackground.setHotspot(x, y);
18954        }
18955        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18956            mForegroundInfo.mDrawable.setHotspot(x, y);
18957        }
18958
18959        dispatchDrawableHotspotChanged(x, y);
18960    }
18961
18962    /**
18963     * Dispatches drawableHotspotChanged to all of this View's children.
18964     *
18965     * @param x hotspot x coordinate
18966     * @param y hotspot y coordinate
18967     * @see #drawableHotspotChanged(float, float)
18968     */
18969    public void dispatchDrawableHotspotChanged(float x, float y) {
18970    }
18971
18972    /**
18973     * Call this to force a view to update its drawable state. This will cause
18974     * drawableStateChanged to be called on this view. Views that are interested
18975     * in the new state should call getDrawableState.
18976     *
18977     * @see #drawableStateChanged
18978     * @see #getDrawableState
18979     */
18980    public void refreshDrawableState() {
18981        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18982        drawableStateChanged();
18983
18984        ViewParent parent = mParent;
18985        if (parent != null) {
18986            parent.childDrawableStateChanged(this);
18987        }
18988    }
18989
18990    /**
18991     * Return an array of resource IDs of the drawable states representing the
18992     * current state of the view.
18993     *
18994     * @return The current drawable state
18995     *
18996     * @see Drawable#setState(int[])
18997     * @see #drawableStateChanged()
18998     * @see #onCreateDrawableState(int)
18999     */
19000    public final int[] getDrawableState() {
19001        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
19002            return mDrawableState;
19003        } else {
19004            mDrawableState = onCreateDrawableState(0);
19005            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
19006            return mDrawableState;
19007        }
19008    }
19009
19010    /**
19011     * Generate the new {@link android.graphics.drawable.Drawable} state for
19012     * this view. This is called by the view
19013     * system when the cached Drawable state is determined to be invalid.  To
19014     * retrieve the current state, you should use {@link #getDrawableState}.
19015     *
19016     * @param extraSpace if non-zero, this is the number of extra entries you
19017     * would like in the returned array in which you can place your own
19018     * states.
19019     *
19020     * @return Returns an array holding the current {@link Drawable} state of
19021     * the view.
19022     *
19023     * @see #mergeDrawableStates(int[], int[])
19024     */
19025    protected int[] onCreateDrawableState(int extraSpace) {
19026        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
19027                mParent instanceof View) {
19028            return ((View) mParent).onCreateDrawableState(extraSpace);
19029        }
19030
19031        int[] drawableState;
19032
19033        int privateFlags = mPrivateFlags;
19034
19035        int viewStateIndex = 0;
19036        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
19037        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
19038        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
19039        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
19040        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
19041        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
19042        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
19043                ThreadedRenderer.isAvailable()) {
19044            // This is set if HW acceleration is requested, even if the current
19045            // process doesn't allow it.  This is just to allow app preview
19046            // windows to better match their app.
19047            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
19048        }
19049        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
19050
19051        final int privateFlags2 = mPrivateFlags2;
19052        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
19053            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
19054        }
19055        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
19056            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
19057        }
19058
19059        drawableState = StateSet.get(viewStateIndex);
19060
19061        //noinspection ConstantIfStatement
19062        if (false) {
19063            Log.i("View", "drawableStateIndex=" + viewStateIndex);
19064            Log.i("View", toString()
19065                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
19066                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
19067                    + " fo=" + hasFocus()
19068                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
19069                    + " wf=" + hasWindowFocus()
19070                    + ": " + Arrays.toString(drawableState));
19071        }
19072
19073        if (extraSpace == 0) {
19074            return drawableState;
19075        }
19076
19077        final int[] fullState;
19078        if (drawableState != null) {
19079            fullState = new int[drawableState.length + extraSpace];
19080            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
19081        } else {
19082            fullState = new int[extraSpace];
19083        }
19084
19085        return fullState;
19086    }
19087
19088    /**
19089     * Merge your own state values in <var>additionalState</var> into the base
19090     * state values <var>baseState</var> that were returned by
19091     * {@link #onCreateDrawableState(int)}.
19092     *
19093     * @param baseState The base state values returned by
19094     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
19095     * own additional state values.
19096     *
19097     * @param additionalState The additional state values you would like
19098     * added to <var>baseState</var>; this array is not modified.
19099     *
19100     * @return As a convenience, the <var>baseState</var> array you originally
19101     * passed into the function is returned.
19102     *
19103     * @see #onCreateDrawableState(int)
19104     */
19105    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
19106        final int N = baseState.length;
19107        int i = N - 1;
19108        while (i >= 0 && baseState[i] == 0) {
19109            i--;
19110        }
19111        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
19112        return baseState;
19113    }
19114
19115    /**
19116     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
19117     * on all Drawable objects associated with this view.
19118     * <p>
19119     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
19120     * attached to this view.
19121     */
19122    @CallSuper
19123    public void jumpDrawablesToCurrentState() {
19124        if (mBackground != null) {
19125            mBackground.jumpToCurrentState();
19126        }
19127        if (mStateListAnimator != null) {
19128            mStateListAnimator.jumpToCurrentState();
19129        }
19130        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19131            mForegroundInfo.mDrawable.jumpToCurrentState();
19132        }
19133    }
19134
19135    /**
19136     * Sets the background color for this view.
19137     * @param color the color of the background
19138     */
19139    @RemotableViewMethod
19140    public void setBackgroundColor(@ColorInt int color) {
19141        if (mBackground instanceof ColorDrawable) {
19142            ((ColorDrawable) mBackground.mutate()).setColor(color);
19143            computeOpaqueFlags();
19144            mBackgroundResource = 0;
19145        } else {
19146            setBackground(new ColorDrawable(color));
19147        }
19148    }
19149
19150    /**
19151     * Set the background to a given resource. The resource should refer to
19152     * a Drawable object or 0 to remove the background.
19153     * @param resid The identifier of the resource.
19154     *
19155     * @attr ref android.R.styleable#View_background
19156     */
19157    @RemotableViewMethod
19158    public void setBackgroundResource(@DrawableRes int resid) {
19159        if (resid != 0 && resid == mBackgroundResource) {
19160            return;
19161        }
19162
19163        Drawable d = null;
19164        if (resid != 0) {
19165            d = mContext.getDrawable(resid);
19166        }
19167        setBackground(d);
19168
19169        mBackgroundResource = resid;
19170    }
19171
19172    /**
19173     * Set the background to a given Drawable, or remove the background. If the
19174     * background has padding, this View's padding is set to the background's
19175     * padding. However, when a background is removed, this View's padding isn't
19176     * touched. If setting the padding is desired, please use
19177     * {@link #setPadding(int, int, int, int)}.
19178     *
19179     * @param background The Drawable to use as the background, or null to remove the
19180     *        background
19181     */
19182    public void setBackground(Drawable background) {
19183        //noinspection deprecation
19184        setBackgroundDrawable(background);
19185    }
19186
19187    /**
19188     * @deprecated use {@link #setBackground(Drawable)} instead
19189     */
19190    @Deprecated
19191    public void setBackgroundDrawable(Drawable background) {
19192        computeOpaqueFlags();
19193
19194        if (background == mBackground) {
19195            return;
19196        }
19197
19198        boolean requestLayout = false;
19199
19200        mBackgroundResource = 0;
19201
19202        /*
19203         * Regardless of whether we're setting a new background or not, we want
19204         * to clear the previous drawable. setVisible first while we still have the callback set.
19205         */
19206        if (mBackground != null) {
19207            if (isAttachedToWindow()) {
19208                mBackground.setVisible(false, false);
19209            }
19210            mBackground.setCallback(null);
19211            unscheduleDrawable(mBackground);
19212        }
19213
19214        if (background != null) {
19215            Rect padding = sThreadLocal.get();
19216            if (padding == null) {
19217                padding = new Rect();
19218                sThreadLocal.set(padding);
19219            }
19220            resetResolvedDrawablesInternal();
19221            background.setLayoutDirection(getLayoutDirection());
19222            if (background.getPadding(padding)) {
19223                resetResolvedPaddingInternal();
19224                switch (background.getLayoutDirection()) {
19225                    case LAYOUT_DIRECTION_RTL:
19226                        mUserPaddingLeftInitial = padding.right;
19227                        mUserPaddingRightInitial = padding.left;
19228                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
19229                        break;
19230                    case LAYOUT_DIRECTION_LTR:
19231                    default:
19232                        mUserPaddingLeftInitial = padding.left;
19233                        mUserPaddingRightInitial = padding.right;
19234                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
19235                }
19236                mLeftPaddingDefined = false;
19237                mRightPaddingDefined = false;
19238            }
19239
19240            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
19241            // if it has a different minimum size, we should layout again
19242            if (mBackground == null
19243                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
19244                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
19245                requestLayout = true;
19246            }
19247
19248            // Set mBackground before we set this as the callback and start making other
19249            // background drawable state change calls. In particular, the setVisible call below
19250            // can result in drawables attempting to start animations or otherwise invalidate,
19251            // which requires the view set as the callback (us) to recognize the drawable as
19252            // belonging to it as per verifyDrawable.
19253            mBackground = background;
19254            if (background.isStateful()) {
19255                background.setState(getDrawableState());
19256            }
19257            if (isAttachedToWindow()) {
19258                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19259            }
19260
19261            applyBackgroundTint();
19262
19263            // Set callback last, since the view may still be initializing.
19264            background.setCallback(this);
19265
19266            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19267                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19268                requestLayout = true;
19269            }
19270        } else {
19271            /* Remove the background */
19272            mBackground = null;
19273            if ((mViewFlags & WILL_NOT_DRAW) != 0
19274                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
19275                mPrivateFlags |= PFLAG_SKIP_DRAW;
19276            }
19277
19278            /*
19279             * When the background is set, we try to apply its padding to this
19280             * View. When the background is removed, we don't touch this View's
19281             * padding. This is noted in the Javadocs. Hence, we don't need to
19282             * requestLayout(), the invalidate() below is sufficient.
19283             */
19284
19285            // The old background's minimum size could have affected this
19286            // View's layout, so let's requestLayout
19287            requestLayout = true;
19288        }
19289
19290        computeOpaqueFlags();
19291
19292        if (requestLayout) {
19293            requestLayout();
19294        }
19295
19296        mBackgroundSizeChanged = true;
19297        invalidate(true);
19298        invalidateOutline();
19299    }
19300
19301    /**
19302     * Gets the background drawable
19303     *
19304     * @return The drawable used as the background for this view, if any.
19305     *
19306     * @see #setBackground(Drawable)
19307     *
19308     * @attr ref android.R.styleable#View_background
19309     */
19310    public Drawable getBackground() {
19311        return mBackground;
19312    }
19313
19314    /**
19315     * Applies a tint to the background drawable. Does not modify the current tint
19316     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19317     * <p>
19318     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
19319     * mutate the drawable and apply the specified tint and tint mode using
19320     * {@link Drawable#setTintList(ColorStateList)}.
19321     *
19322     * @param tint the tint to apply, may be {@code null} to clear tint
19323     *
19324     * @attr ref android.R.styleable#View_backgroundTint
19325     * @see #getBackgroundTintList()
19326     * @see Drawable#setTintList(ColorStateList)
19327     */
19328    public void setBackgroundTintList(@Nullable ColorStateList tint) {
19329        if (mBackgroundTint == null) {
19330            mBackgroundTint = new TintInfo();
19331        }
19332        mBackgroundTint.mTintList = tint;
19333        mBackgroundTint.mHasTintList = true;
19334
19335        applyBackgroundTint();
19336    }
19337
19338    /**
19339     * Return the tint applied to the background drawable, if specified.
19340     *
19341     * @return the tint applied to the background drawable
19342     * @attr ref android.R.styleable#View_backgroundTint
19343     * @see #setBackgroundTintList(ColorStateList)
19344     */
19345    @Nullable
19346    public ColorStateList getBackgroundTintList() {
19347        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
19348    }
19349
19350    /**
19351     * Specifies the blending mode used to apply the tint specified by
19352     * {@link #setBackgroundTintList(ColorStateList)}} to the background
19353     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19354     *
19355     * @param tintMode the blending mode used to apply the tint, may be
19356     *                 {@code null} to clear tint
19357     * @attr ref android.R.styleable#View_backgroundTintMode
19358     * @see #getBackgroundTintMode()
19359     * @see Drawable#setTintMode(PorterDuff.Mode)
19360     */
19361    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19362        if (mBackgroundTint == null) {
19363            mBackgroundTint = new TintInfo();
19364        }
19365        mBackgroundTint.mTintMode = tintMode;
19366        mBackgroundTint.mHasTintMode = true;
19367
19368        applyBackgroundTint();
19369    }
19370
19371    /**
19372     * Return the blending mode used to apply the tint to the background
19373     * drawable, if specified.
19374     *
19375     * @return the blending mode used to apply the tint to the background
19376     *         drawable
19377     * @attr ref android.R.styleable#View_backgroundTintMode
19378     * @see #setBackgroundTintMode(PorterDuff.Mode)
19379     */
19380    @Nullable
19381    public PorterDuff.Mode getBackgroundTintMode() {
19382        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
19383    }
19384
19385    private void applyBackgroundTint() {
19386        if (mBackground != null && mBackgroundTint != null) {
19387            final TintInfo tintInfo = mBackgroundTint;
19388            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19389                mBackground = mBackground.mutate();
19390
19391                if (tintInfo.mHasTintList) {
19392                    mBackground.setTintList(tintInfo.mTintList);
19393                }
19394
19395                if (tintInfo.mHasTintMode) {
19396                    mBackground.setTintMode(tintInfo.mTintMode);
19397                }
19398
19399                // The drawable (or one of its children) may not have been
19400                // stateful before applying the tint, so let's try again.
19401                if (mBackground.isStateful()) {
19402                    mBackground.setState(getDrawableState());
19403                }
19404            }
19405        }
19406    }
19407
19408    /**
19409     * Returns the drawable used as the foreground of this View. The
19410     * foreground drawable, if non-null, is always drawn on top of the view's content.
19411     *
19412     * @return a Drawable or null if no foreground was set
19413     *
19414     * @see #onDrawForeground(Canvas)
19415     */
19416    public Drawable getForeground() {
19417        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19418    }
19419
19420    /**
19421     * Supply a Drawable that is to be rendered on top of all of the content in the view.
19422     *
19423     * @param foreground the Drawable to be drawn on top of the children
19424     *
19425     * @attr ref android.R.styleable#View_foreground
19426     */
19427    public void setForeground(Drawable foreground) {
19428        if (mForegroundInfo == null) {
19429            if (foreground == null) {
19430                // Nothing to do.
19431                return;
19432            }
19433            mForegroundInfo = new ForegroundInfo();
19434        }
19435
19436        if (foreground == mForegroundInfo.mDrawable) {
19437            // Nothing to do
19438            return;
19439        }
19440
19441        if (mForegroundInfo.mDrawable != null) {
19442            if (isAttachedToWindow()) {
19443                mForegroundInfo.mDrawable.setVisible(false, false);
19444            }
19445            mForegroundInfo.mDrawable.setCallback(null);
19446            unscheduleDrawable(mForegroundInfo.mDrawable);
19447        }
19448
19449        mForegroundInfo.mDrawable = foreground;
19450        mForegroundInfo.mBoundsChanged = true;
19451        if (foreground != null) {
19452            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19453                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19454            }
19455            foreground.setLayoutDirection(getLayoutDirection());
19456            if (foreground.isStateful()) {
19457                foreground.setState(getDrawableState());
19458            }
19459            applyForegroundTint();
19460            if (isAttachedToWindow()) {
19461                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19462            }
19463            // Set callback last, since the view may still be initializing.
19464            foreground.setCallback(this);
19465        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
19466            mPrivateFlags |= PFLAG_SKIP_DRAW;
19467        }
19468        requestLayout();
19469        invalidate();
19470    }
19471
19472    /**
19473     * Magic bit used to support features of framework-internal window decor implementation details.
19474     * This used to live exclusively in FrameLayout.
19475     *
19476     * @return true if the foreground should draw inside the padding region or false
19477     *         if it should draw inset by the view's padding
19478     * @hide internal use only; only used by FrameLayout and internal screen layouts.
19479     */
19480    public boolean isForegroundInsidePadding() {
19481        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
19482    }
19483
19484    /**
19485     * Describes how the foreground is positioned.
19486     *
19487     * @return foreground gravity.
19488     *
19489     * @see #setForegroundGravity(int)
19490     *
19491     * @attr ref android.R.styleable#View_foregroundGravity
19492     */
19493    public int getForegroundGravity() {
19494        return mForegroundInfo != null ? mForegroundInfo.mGravity
19495                : Gravity.START | Gravity.TOP;
19496    }
19497
19498    /**
19499     * Describes how the foreground is positioned. Defaults to START and TOP.
19500     *
19501     * @param gravity see {@link android.view.Gravity}
19502     *
19503     * @see #getForegroundGravity()
19504     *
19505     * @attr ref android.R.styleable#View_foregroundGravity
19506     */
19507    public void setForegroundGravity(int gravity) {
19508        if (mForegroundInfo == null) {
19509            mForegroundInfo = new ForegroundInfo();
19510        }
19511
19512        if (mForegroundInfo.mGravity != gravity) {
19513            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
19514                gravity |= Gravity.START;
19515            }
19516
19517            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
19518                gravity |= Gravity.TOP;
19519            }
19520
19521            mForegroundInfo.mGravity = gravity;
19522            requestLayout();
19523        }
19524    }
19525
19526    /**
19527     * Applies a tint to the foreground drawable. Does not modify the current tint
19528     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19529     * <p>
19530     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
19531     * mutate the drawable and apply the specified tint and tint mode using
19532     * {@link Drawable#setTintList(ColorStateList)}.
19533     *
19534     * @param tint the tint to apply, may be {@code null} to clear tint
19535     *
19536     * @attr ref android.R.styleable#View_foregroundTint
19537     * @see #getForegroundTintList()
19538     * @see Drawable#setTintList(ColorStateList)
19539     */
19540    public void setForegroundTintList(@Nullable ColorStateList tint) {
19541        if (mForegroundInfo == null) {
19542            mForegroundInfo = new ForegroundInfo();
19543        }
19544        if (mForegroundInfo.mTintInfo == null) {
19545            mForegroundInfo.mTintInfo = new TintInfo();
19546        }
19547        mForegroundInfo.mTintInfo.mTintList = tint;
19548        mForegroundInfo.mTintInfo.mHasTintList = true;
19549
19550        applyForegroundTint();
19551    }
19552
19553    /**
19554     * Return the tint applied to the foreground drawable, if specified.
19555     *
19556     * @return the tint applied to the foreground drawable
19557     * @attr ref android.R.styleable#View_foregroundTint
19558     * @see #setForegroundTintList(ColorStateList)
19559     */
19560    @Nullable
19561    public ColorStateList getForegroundTintList() {
19562        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19563                ? mForegroundInfo.mTintInfo.mTintList : null;
19564    }
19565
19566    /**
19567     * Specifies the blending mode used to apply the tint specified by
19568     * {@link #setForegroundTintList(ColorStateList)}} to the background
19569     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19570     *
19571     * @param tintMode the blending mode used to apply the tint, may be
19572     *                 {@code null} to clear tint
19573     * @attr ref android.R.styleable#View_foregroundTintMode
19574     * @see #getForegroundTintMode()
19575     * @see Drawable#setTintMode(PorterDuff.Mode)
19576     */
19577    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19578        if (mForegroundInfo == null) {
19579            mForegroundInfo = new ForegroundInfo();
19580        }
19581        if (mForegroundInfo.mTintInfo == null) {
19582            mForegroundInfo.mTintInfo = new TintInfo();
19583        }
19584        mForegroundInfo.mTintInfo.mTintMode = tintMode;
19585        mForegroundInfo.mTintInfo.mHasTintMode = true;
19586
19587        applyForegroundTint();
19588    }
19589
19590    /**
19591     * Return the blending mode used to apply the tint to the foreground
19592     * drawable, if specified.
19593     *
19594     * @return the blending mode used to apply the tint to the foreground
19595     *         drawable
19596     * @attr ref android.R.styleable#View_foregroundTintMode
19597     * @see #setForegroundTintMode(PorterDuff.Mode)
19598     */
19599    @Nullable
19600    public PorterDuff.Mode getForegroundTintMode() {
19601        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19602                ? mForegroundInfo.mTintInfo.mTintMode : null;
19603    }
19604
19605    private void applyForegroundTint() {
19606        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19607                && mForegroundInfo.mTintInfo != null) {
19608            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
19609            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19610                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
19611
19612                if (tintInfo.mHasTintList) {
19613                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
19614                }
19615
19616                if (tintInfo.mHasTintMode) {
19617                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
19618                }
19619
19620                // The drawable (or one of its children) may not have been
19621                // stateful before applying the tint, so let's try again.
19622                if (mForegroundInfo.mDrawable.isStateful()) {
19623                    mForegroundInfo.mDrawable.setState(getDrawableState());
19624                }
19625            }
19626        }
19627    }
19628
19629    /**
19630     * Draw any foreground content for this view.
19631     *
19632     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
19633     * drawable or other view-specific decorations. The foreground is drawn on top of the
19634     * primary view content.</p>
19635     *
19636     * @param canvas canvas to draw into
19637     */
19638    public void onDrawForeground(Canvas canvas) {
19639        onDrawScrollIndicators(canvas);
19640        onDrawScrollBars(canvas);
19641
19642        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19643        if (foreground != null) {
19644            if (mForegroundInfo.mBoundsChanged) {
19645                mForegroundInfo.mBoundsChanged = false;
19646                final Rect selfBounds = mForegroundInfo.mSelfBounds;
19647                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
19648
19649                if (mForegroundInfo.mInsidePadding) {
19650                    selfBounds.set(0, 0, getWidth(), getHeight());
19651                } else {
19652                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
19653                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
19654                }
19655
19656                final int ld = getLayoutDirection();
19657                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
19658                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
19659                foreground.setBounds(overlayBounds);
19660            }
19661
19662            foreground.draw(canvas);
19663        }
19664    }
19665
19666    /**
19667     * Sets the padding. The view may add on the space required to display
19668     * the scrollbars, depending on the style and visibility of the scrollbars.
19669     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
19670     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
19671     * from the values set in this call.
19672     *
19673     * @attr ref android.R.styleable#View_padding
19674     * @attr ref android.R.styleable#View_paddingBottom
19675     * @attr ref android.R.styleable#View_paddingLeft
19676     * @attr ref android.R.styleable#View_paddingRight
19677     * @attr ref android.R.styleable#View_paddingTop
19678     * @param left the left padding in pixels
19679     * @param top the top padding in pixels
19680     * @param right the right padding in pixels
19681     * @param bottom the bottom padding in pixels
19682     */
19683    public void setPadding(int left, int top, int right, int bottom) {
19684        resetResolvedPaddingInternal();
19685
19686        mUserPaddingStart = UNDEFINED_PADDING;
19687        mUserPaddingEnd = UNDEFINED_PADDING;
19688
19689        mUserPaddingLeftInitial = left;
19690        mUserPaddingRightInitial = right;
19691
19692        mLeftPaddingDefined = true;
19693        mRightPaddingDefined = true;
19694
19695        internalSetPadding(left, top, right, bottom);
19696    }
19697
19698    /**
19699     * @hide
19700     */
19701    protected void internalSetPadding(int left, int top, int right, int bottom) {
19702        mUserPaddingLeft = left;
19703        mUserPaddingRight = right;
19704        mUserPaddingBottom = bottom;
19705
19706        final int viewFlags = mViewFlags;
19707        boolean changed = false;
19708
19709        // Common case is there are no scroll bars.
19710        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
19711            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
19712                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
19713                        ? 0 : getVerticalScrollbarWidth();
19714                switch (mVerticalScrollbarPosition) {
19715                    case SCROLLBAR_POSITION_DEFAULT:
19716                        if (isLayoutRtl()) {
19717                            left += offset;
19718                        } else {
19719                            right += offset;
19720                        }
19721                        break;
19722                    case SCROLLBAR_POSITION_RIGHT:
19723                        right += offset;
19724                        break;
19725                    case SCROLLBAR_POSITION_LEFT:
19726                        left += offset;
19727                        break;
19728                }
19729            }
19730            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
19731                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
19732                        ? 0 : getHorizontalScrollbarHeight();
19733            }
19734        }
19735
19736        if (mPaddingLeft != left) {
19737            changed = true;
19738            mPaddingLeft = left;
19739        }
19740        if (mPaddingTop != top) {
19741            changed = true;
19742            mPaddingTop = top;
19743        }
19744        if (mPaddingRight != right) {
19745            changed = true;
19746            mPaddingRight = right;
19747        }
19748        if (mPaddingBottom != bottom) {
19749            changed = true;
19750            mPaddingBottom = bottom;
19751        }
19752
19753        if (changed) {
19754            requestLayout();
19755            invalidateOutline();
19756        }
19757    }
19758
19759    /**
19760     * Sets the relative padding. The view may add on the space required to display
19761     * the scrollbars, depending on the style and visibility of the scrollbars.
19762     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
19763     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
19764     * from the values set in this call.
19765     *
19766     * @attr ref android.R.styleable#View_padding
19767     * @attr ref android.R.styleable#View_paddingBottom
19768     * @attr ref android.R.styleable#View_paddingStart
19769     * @attr ref android.R.styleable#View_paddingEnd
19770     * @attr ref android.R.styleable#View_paddingTop
19771     * @param start the start padding in pixels
19772     * @param top the top padding in pixels
19773     * @param end the end padding in pixels
19774     * @param bottom the bottom padding in pixels
19775     */
19776    public void setPaddingRelative(int start, int top, int end, int bottom) {
19777        resetResolvedPaddingInternal();
19778
19779        mUserPaddingStart = start;
19780        mUserPaddingEnd = end;
19781        mLeftPaddingDefined = true;
19782        mRightPaddingDefined = true;
19783
19784        switch(getLayoutDirection()) {
19785            case LAYOUT_DIRECTION_RTL:
19786                mUserPaddingLeftInitial = end;
19787                mUserPaddingRightInitial = start;
19788                internalSetPadding(end, top, start, bottom);
19789                break;
19790            case LAYOUT_DIRECTION_LTR:
19791            default:
19792                mUserPaddingLeftInitial = start;
19793                mUserPaddingRightInitial = end;
19794                internalSetPadding(start, top, end, bottom);
19795        }
19796    }
19797
19798    /**
19799     * Returns the top padding of this view.
19800     *
19801     * @return the top padding in pixels
19802     */
19803    public int getPaddingTop() {
19804        return mPaddingTop;
19805    }
19806
19807    /**
19808     * Returns the bottom padding of this view. If there are inset and enabled
19809     * scrollbars, this value may include the space required to display the
19810     * scrollbars as well.
19811     *
19812     * @return the bottom padding in pixels
19813     */
19814    public int getPaddingBottom() {
19815        return mPaddingBottom;
19816    }
19817
19818    /**
19819     * Returns the left padding of this view. If there are inset and enabled
19820     * scrollbars, this value may include the space required to display the
19821     * scrollbars as well.
19822     *
19823     * @return the left padding in pixels
19824     */
19825    public int getPaddingLeft() {
19826        if (!isPaddingResolved()) {
19827            resolvePadding();
19828        }
19829        return mPaddingLeft;
19830    }
19831
19832    /**
19833     * Returns the start padding of this view depending on its resolved layout direction.
19834     * If there are inset and enabled scrollbars, this value may include the space
19835     * required to display the scrollbars as well.
19836     *
19837     * @return the start padding in pixels
19838     */
19839    public int getPaddingStart() {
19840        if (!isPaddingResolved()) {
19841            resolvePadding();
19842        }
19843        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19844                mPaddingRight : mPaddingLeft;
19845    }
19846
19847    /**
19848     * Returns the right padding of this view. If there are inset and enabled
19849     * scrollbars, this value may include the space required to display the
19850     * scrollbars as well.
19851     *
19852     * @return the right padding in pixels
19853     */
19854    public int getPaddingRight() {
19855        if (!isPaddingResolved()) {
19856            resolvePadding();
19857        }
19858        return mPaddingRight;
19859    }
19860
19861    /**
19862     * Returns the end padding of this view depending on its resolved layout direction.
19863     * If there are inset and enabled scrollbars, this value may include the space
19864     * required to display the scrollbars as well.
19865     *
19866     * @return the end padding in pixels
19867     */
19868    public int getPaddingEnd() {
19869        if (!isPaddingResolved()) {
19870            resolvePadding();
19871        }
19872        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19873                mPaddingLeft : mPaddingRight;
19874    }
19875
19876    /**
19877     * Return if the padding has been set through relative values
19878     * {@link #setPaddingRelative(int, int, int, int)} or through
19879     * @attr ref android.R.styleable#View_paddingStart or
19880     * @attr ref android.R.styleable#View_paddingEnd
19881     *
19882     * @return true if the padding is relative or false if it is not.
19883     */
19884    public boolean isPaddingRelative() {
19885        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
19886    }
19887
19888    Insets computeOpticalInsets() {
19889        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
19890    }
19891
19892    /**
19893     * @hide
19894     */
19895    public void resetPaddingToInitialValues() {
19896        if (isRtlCompatibilityMode()) {
19897            mPaddingLeft = mUserPaddingLeftInitial;
19898            mPaddingRight = mUserPaddingRightInitial;
19899            return;
19900        }
19901        if (isLayoutRtl()) {
19902            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
19903            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
19904        } else {
19905            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
19906            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
19907        }
19908    }
19909
19910    /**
19911     * @hide
19912     */
19913    public Insets getOpticalInsets() {
19914        if (mLayoutInsets == null) {
19915            mLayoutInsets = computeOpticalInsets();
19916        }
19917        return mLayoutInsets;
19918    }
19919
19920    /**
19921     * Set this view's optical insets.
19922     *
19923     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
19924     * property. Views that compute their own optical insets should call it as part of measurement.
19925     * This method does not request layout. If you are setting optical insets outside of
19926     * measure/layout itself you will want to call requestLayout() yourself.
19927     * </p>
19928     * @hide
19929     */
19930    public void setOpticalInsets(Insets insets) {
19931        mLayoutInsets = insets;
19932    }
19933
19934    /**
19935     * Changes the selection state of this view. A view can be selected or not.
19936     * Note that selection is not the same as focus. Views are typically
19937     * selected in the context of an AdapterView like ListView or GridView;
19938     * the selected view is the view that is highlighted.
19939     *
19940     * @param selected true if the view must be selected, false otherwise
19941     */
19942    public void setSelected(boolean selected) {
19943        //noinspection DoubleNegation
19944        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19945            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19946            if (!selected) resetPressedState();
19947            invalidate(true);
19948            refreshDrawableState();
19949            dispatchSetSelected(selected);
19950            if (selected) {
19951                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19952            } else {
19953                notifyViewAccessibilityStateChangedIfNeeded(
19954                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19955            }
19956        }
19957    }
19958
19959    /**
19960     * Dispatch setSelected to all of this View's children.
19961     *
19962     * @see #setSelected(boolean)
19963     *
19964     * @param selected The new selected state
19965     */
19966    protected void dispatchSetSelected(boolean selected) {
19967    }
19968
19969    /**
19970     * Indicates the selection state of this view.
19971     *
19972     * @return true if the view is selected, false otherwise
19973     */
19974    @ViewDebug.ExportedProperty
19975    public boolean isSelected() {
19976        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19977    }
19978
19979    /**
19980     * Changes the activated state of this view. A view can be activated or not.
19981     * Note that activation is not the same as selection.  Selection is
19982     * a transient property, representing the view (hierarchy) the user is
19983     * currently interacting with.  Activation is a longer-term state that the
19984     * user can move views in and out of.  For example, in a list view with
19985     * single or multiple selection enabled, the views in the current selection
19986     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19987     * here.)  The activated state is propagated down to children of the view it
19988     * is set on.
19989     *
19990     * @param activated true if the view must be activated, false otherwise
19991     */
19992    public void setActivated(boolean activated) {
19993        //noinspection DoubleNegation
19994        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19995            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19996            invalidate(true);
19997            refreshDrawableState();
19998            dispatchSetActivated(activated);
19999        }
20000    }
20001
20002    /**
20003     * Dispatch setActivated to all of this View's children.
20004     *
20005     * @see #setActivated(boolean)
20006     *
20007     * @param activated The new activated state
20008     */
20009    protected void dispatchSetActivated(boolean activated) {
20010    }
20011
20012    /**
20013     * Indicates the activation state of this view.
20014     *
20015     * @return true if the view is activated, false otherwise
20016     */
20017    @ViewDebug.ExportedProperty
20018    public boolean isActivated() {
20019        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
20020    }
20021
20022    /**
20023     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
20024     * observer can be used to get notifications when global events, like
20025     * layout, happen.
20026     *
20027     * The returned ViewTreeObserver observer is not guaranteed to remain
20028     * valid for the lifetime of this View. If the caller of this method keeps
20029     * a long-lived reference to ViewTreeObserver, it should always check for
20030     * the return value of {@link ViewTreeObserver#isAlive()}.
20031     *
20032     * @return The ViewTreeObserver for this view's hierarchy.
20033     */
20034    public ViewTreeObserver getViewTreeObserver() {
20035        if (mAttachInfo != null) {
20036            return mAttachInfo.mTreeObserver;
20037        }
20038        if (mFloatingTreeObserver == null) {
20039            mFloatingTreeObserver = new ViewTreeObserver(mContext);
20040        }
20041        return mFloatingTreeObserver;
20042    }
20043
20044    /**
20045     * <p>Finds the topmost view in the current view hierarchy.</p>
20046     *
20047     * @return the topmost view containing this view
20048     */
20049    public View getRootView() {
20050        if (mAttachInfo != null) {
20051            final View v = mAttachInfo.mRootView;
20052            if (v != null) {
20053                return v;
20054            }
20055        }
20056
20057        View parent = this;
20058
20059        while (parent.mParent != null && parent.mParent instanceof View) {
20060            parent = (View) parent.mParent;
20061        }
20062
20063        return parent;
20064    }
20065
20066    /**
20067     * Transforms a motion event from view-local coordinates to on-screen
20068     * coordinates.
20069     *
20070     * @param ev the view-local motion event
20071     * @return false if the transformation could not be applied
20072     * @hide
20073     */
20074    public boolean toGlobalMotionEvent(MotionEvent ev) {
20075        final AttachInfo info = mAttachInfo;
20076        if (info == null) {
20077            return false;
20078        }
20079
20080        final Matrix m = info.mTmpMatrix;
20081        m.set(Matrix.IDENTITY_MATRIX);
20082        transformMatrixToGlobal(m);
20083        ev.transform(m);
20084        return true;
20085    }
20086
20087    /**
20088     * Transforms a motion event from on-screen coordinates to view-local
20089     * coordinates.
20090     *
20091     * @param ev the on-screen motion event
20092     * @return false if the transformation could not be applied
20093     * @hide
20094     */
20095    public boolean toLocalMotionEvent(MotionEvent ev) {
20096        final AttachInfo info = mAttachInfo;
20097        if (info == null) {
20098            return false;
20099        }
20100
20101        final Matrix m = info.mTmpMatrix;
20102        m.set(Matrix.IDENTITY_MATRIX);
20103        transformMatrixToLocal(m);
20104        ev.transform(m);
20105        return true;
20106    }
20107
20108    /**
20109     * Modifies the input matrix such that it maps view-local coordinates to
20110     * on-screen coordinates.
20111     *
20112     * @param m input matrix to modify
20113     * @hide
20114     */
20115    public void transformMatrixToGlobal(Matrix m) {
20116        final ViewParent parent = mParent;
20117        if (parent instanceof View) {
20118            final View vp = (View) parent;
20119            vp.transformMatrixToGlobal(m);
20120            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
20121        } else if (parent instanceof ViewRootImpl) {
20122            final ViewRootImpl vr = (ViewRootImpl) parent;
20123            vr.transformMatrixToGlobal(m);
20124            m.preTranslate(0, -vr.mCurScrollY);
20125        }
20126
20127        m.preTranslate(mLeft, mTop);
20128
20129        if (!hasIdentityMatrix()) {
20130            m.preConcat(getMatrix());
20131        }
20132    }
20133
20134    /**
20135     * Modifies the input matrix such that it maps on-screen coordinates to
20136     * view-local coordinates.
20137     *
20138     * @param m input matrix to modify
20139     * @hide
20140     */
20141    public void transformMatrixToLocal(Matrix m) {
20142        final ViewParent parent = mParent;
20143        if (parent instanceof View) {
20144            final View vp = (View) parent;
20145            vp.transformMatrixToLocal(m);
20146            m.postTranslate(vp.mScrollX, vp.mScrollY);
20147        } else if (parent instanceof ViewRootImpl) {
20148            final ViewRootImpl vr = (ViewRootImpl) parent;
20149            vr.transformMatrixToLocal(m);
20150            m.postTranslate(0, vr.mCurScrollY);
20151        }
20152
20153        m.postTranslate(-mLeft, -mTop);
20154
20155        if (!hasIdentityMatrix()) {
20156            m.postConcat(getInverseMatrix());
20157        }
20158    }
20159
20160    /**
20161     * @hide
20162     */
20163    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
20164            @ViewDebug.IntToString(from = 0, to = "x"),
20165            @ViewDebug.IntToString(from = 1, to = "y")
20166    })
20167    public int[] getLocationOnScreen() {
20168        int[] location = new int[2];
20169        getLocationOnScreen(location);
20170        return location;
20171    }
20172
20173    /**
20174     * <p>Computes the coordinates of this view on the screen. The argument
20175     * must be an array of two integers. After the method returns, the array
20176     * contains the x and y location in that order.</p>
20177     *
20178     * @param outLocation an array of two integers in which to hold the coordinates
20179     */
20180    public void getLocationOnScreen(@Size(2) int[] outLocation) {
20181        getLocationInWindow(outLocation);
20182
20183        final AttachInfo info = mAttachInfo;
20184        if (info != null) {
20185            outLocation[0] += info.mWindowLeft;
20186            outLocation[1] += info.mWindowTop;
20187        }
20188    }
20189
20190    /**
20191     * <p>Computes the coordinates of this view in its window. The argument
20192     * must be an array of two integers. After the method returns, the array
20193     * contains the x and y location in that order.</p>
20194     *
20195     * @param outLocation an array of two integers in which to hold the coordinates
20196     */
20197    public void getLocationInWindow(@Size(2) int[] outLocation) {
20198        if (outLocation == null || outLocation.length < 2) {
20199            throw new IllegalArgumentException("outLocation must be an array of two integers");
20200        }
20201
20202        outLocation[0] = 0;
20203        outLocation[1] = 0;
20204
20205        transformFromViewToWindowSpace(outLocation);
20206    }
20207
20208    /** @hide */
20209    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
20210        if (inOutLocation == null || inOutLocation.length < 2) {
20211            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
20212        }
20213
20214        if (mAttachInfo == null) {
20215            // When the view is not attached to a window, this method does not make sense
20216            inOutLocation[0] = inOutLocation[1] = 0;
20217            return;
20218        }
20219
20220        float position[] = mAttachInfo.mTmpTransformLocation;
20221        position[0] = inOutLocation[0];
20222        position[1] = inOutLocation[1];
20223
20224        if (!hasIdentityMatrix()) {
20225            getMatrix().mapPoints(position);
20226        }
20227
20228        position[0] += mLeft;
20229        position[1] += mTop;
20230
20231        ViewParent viewParent = mParent;
20232        while (viewParent instanceof View) {
20233            final View view = (View) viewParent;
20234
20235            position[0] -= view.mScrollX;
20236            position[1] -= view.mScrollY;
20237
20238            if (!view.hasIdentityMatrix()) {
20239                view.getMatrix().mapPoints(position);
20240            }
20241
20242            position[0] += view.mLeft;
20243            position[1] += view.mTop;
20244
20245            viewParent = view.mParent;
20246         }
20247
20248        if (viewParent instanceof ViewRootImpl) {
20249            // *cough*
20250            final ViewRootImpl vr = (ViewRootImpl) viewParent;
20251            position[1] -= vr.mCurScrollY;
20252        }
20253
20254        inOutLocation[0] = Math.round(position[0]);
20255        inOutLocation[1] = Math.round(position[1]);
20256    }
20257
20258    /**
20259     * @param id the id of the view to be found
20260     * @return the view of the specified id, null if cannot be found
20261     * @hide
20262     */
20263    protected <T extends View> T findViewTraversal(@IdRes int id) {
20264        if (id == mID) {
20265            return (T) this;
20266        }
20267        return null;
20268    }
20269
20270    /**
20271     * @param tag the tag of the view to be found
20272     * @return the view of specified tag, null if cannot be found
20273     * @hide
20274     */
20275    protected <T extends View> T findViewWithTagTraversal(Object tag) {
20276        if (tag != null && tag.equals(mTag)) {
20277            return (T) this;
20278        }
20279        return null;
20280    }
20281
20282    /**
20283     * @param predicate The predicate to evaluate.
20284     * @param childToSkip If not null, ignores this child during the recursive traversal.
20285     * @return The first view that matches the predicate or null.
20286     * @hide
20287     */
20288    protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate,
20289            View childToSkip) {
20290        if (predicate.test(this)) {
20291            return (T) this;
20292        }
20293        return null;
20294    }
20295
20296    /**
20297     * Look for a child view with the given id.  If this view has the given
20298     * id, return this view.
20299     *
20300     * @param id The id to search for.
20301     * @return The view that has the given id in the hierarchy or null
20302     */
20303    @Nullable
20304    public final <T extends View> T findViewById(@IdRes int id) {
20305        if (id < 0) {
20306            return null;
20307        }
20308        return findViewTraversal(id);
20309    }
20310
20311    /**
20312     * Finds a view by its unuque and stable accessibility id.
20313     *
20314     * @param accessibilityId The searched accessibility id.
20315     * @return The found view.
20316     */
20317    final <T extends View> T  findViewByAccessibilityId(int accessibilityId) {
20318        if (accessibilityId < 0) {
20319            return null;
20320        }
20321        T view = findViewByAccessibilityIdTraversal(accessibilityId);
20322        if (view != null) {
20323            return view.includeForAccessibility() ? view : null;
20324        }
20325        return null;
20326    }
20327
20328    /**
20329     * Performs the traversal to find a view by its unuque and stable accessibility id.
20330     *
20331     * <strong>Note:</strong>This method does not stop at the root namespace
20332     * boundary since the user can touch the screen at an arbitrary location
20333     * potentially crossing the root namespace bounday which will send an
20334     * accessibility event to accessibility services and they should be able
20335     * to obtain the event source. Also accessibility ids are guaranteed to be
20336     * unique in the window.
20337     *
20338     * @param accessibilityId The accessibility id.
20339     * @return The found view.
20340     * @hide
20341     */
20342    public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) {
20343        if (getAccessibilityViewId() == accessibilityId) {
20344            return (T) this;
20345        }
20346        return null;
20347    }
20348
20349    /**
20350     * Look for a child view with the given tag.  If this view has the given
20351     * tag, return this view.
20352     *
20353     * @param tag The tag to search for, using "tag.equals(getTag())".
20354     * @return The View that has the given tag in the hierarchy or null
20355     */
20356    public final <T extends View> T findViewWithTag(Object tag) {
20357        if (tag == null) {
20358            return null;
20359        }
20360        return findViewWithTagTraversal(tag);
20361    }
20362
20363    /**
20364     * Look for a child view that matches the specified predicate.
20365     * If this view matches the predicate, return this view.
20366     *
20367     * @param predicate The predicate to evaluate.
20368     * @return The first view that matches the predicate or null.
20369     * @hide
20370     */
20371    public final <T extends View> T findViewByPredicate(Predicate<View> predicate) {
20372        return findViewByPredicateTraversal(predicate, null);
20373    }
20374
20375    /**
20376     * Look for a child view that matches the specified predicate,
20377     * starting with the specified view and its descendents and then
20378     * recusively searching the ancestors and siblings of that view
20379     * until this view is reached.
20380     *
20381     * This method is useful in cases where the predicate does not match
20382     * a single unique view (perhaps multiple views use the same id)
20383     * and we are trying to find the view that is "closest" in scope to the
20384     * starting view.
20385     *
20386     * @param start The view to start from.
20387     * @param predicate The predicate to evaluate.
20388     * @return The first view that matches the predicate or null.
20389     * @hide
20390     */
20391    public final <T extends View> T findViewByPredicateInsideOut(
20392            View start, Predicate<View> predicate) {
20393        View childToSkip = null;
20394        for (;;) {
20395            T view = start.findViewByPredicateTraversal(predicate, childToSkip);
20396            if (view != null || start == this) {
20397                return view;
20398            }
20399
20400            ViewParent parent = start.getParent();
20401            if (parent == null || !(parent instanceof View)) {
20402                return null;
20403            }
20404
20405            childToSkip = start;
20406            start = (View) parent;
20407        }
20408    }
20409
20410    /**
20411     * Sets the identifier for this view. The identifier does not have to be
20412     * unique in this view's hierarchy. The identifier should be a positive
20413     * number.
20414     *
20415     * @see #NO_ID
20416     * @see #getId()
20417     * @see #findViewById(int)
20418     *
20419     * @param id a number used to identify the view
20420     *
20421     * @attr ref android.R.styleable#View_id
20422     */
20423    public void setId(@IdRes int id) {
20424        mID = id;
20425        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
20426            mID = generateViewId();
20427        }
20428    }
20429
20430    /**
20431     * {@hide}
20432     *
20433     * @param isRoot true if the view belongs to the root namespace, false
20434     *        otherwise
20435     */
20436    public void setIsRootNamespace(boolean isRoot) {
20437        if (isRoot) {
20438            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
20439        } else {
20440            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
20441        }
20442    }
20443
20444    /**
20445     * {@hide}
20446     *
20447     * @return true if the view belongs to the root namespace, false otherwise
20448     */
20449    public boolean isRootNamespace() {
20450        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
20451    }
20452
20453    /**
20454     * Returns this view's identifier.
20455     *
20456     * @return a positive integer used to identify the view or {@link #NO_ID}
20457     *         if the view has no ID
20458     *
20459     * @see #setId(int)
20460     * @see #findViewById(int)
20461     * @attr ref android.R.styleable#View_id
20462     */
20463    @IdRes
20464    @ViewDebug.CapturedViewProperty
20465    public int getId() {
20466        return mID;
20467    }
20468
20469    /**
20470     * Returns this view's tag.
20471     *
20472     * @return the Object stored in this view as a tag, or {@code null} if not
20473     *         set
20474     *
20475     * @see #setTag(Object)
20476     * @see #getTag(int)
20477     */
20478    @ViewDebug.ExportedProperty
20479    public Object getTag() {
20480        return mTag;
20481    }
20482
20483    /**
20484     * Sets the tag associated with this view. A tag can be used to mark
20485     * a view in its hierarchy and does not have to be unique within the
20486     * hierarchy. Tags can also be used to store data within a view without
20487     * resorting to another data structure.
20488     *
20489     * @param tag an Object to tag the view with
20490     *
20491     * @see #getTag()
20492     * @see #setTag(int, Object)
20493     */
20494    public void setTag(final Object tag) {
20495        mTag = tag;
20496    }
20497
20498    /**
20499     * Returns the tag associated with this view and the specified key.
20500     *
20501     * @param key The key identifying the tag
20502     *
20503     * @return the Object stored in this view as a tag, or {@code null} if not
20504     *         set
20505     *
20506     * @see #setTag(int, Object)
20507     * @see #getTag()
20508     */
20509    public Object getTag(int key) {
20510        if (mKeyedTags != null) return mKeyedTags.get(key);
20511        return null;
20512    }
20513
20514    /**
20515     * Sets a tag associated with this view and a key. A tag can be used
20516     * to mark a view in its hierarchy and does not have to be unique within
20517     * the hierarchy. Tags can also be used to store data within a view
20518     * without resorting to another data structure.
20519     *
20520     * The specified key should be an id declared in the resources of the
20521     * application to ensure it is unique (see the <a
20522     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
20523     * Keys identified as belonging to
20524     * the Android framework or not associated with any package will cause
20525     * an {@link IllegalArgumentException} to be thrown.
20526     *
20527     * @param key The key identifying the tag
20528     * @param tag An Object to tag the view with
20529     *
20530     * @throws IllegalArgumentException If they specified key is not valid
20531     *
20532     * @see #setTag(Object)
20533     * @see #getTag(int)
20534     */
20535    public void setTag(int key, final Object tag) {
20536        // If the package id is 0x00 or 0x01, it's either an undefined package
20537        // or a framework id
20538        if ((key >>> 24) < 2) {
20539            throw new IllegalArgumentException("The key must be an application-specific "
20540                    + "resource id.");
20541        }
20542
20543        setKeyedTag(key, tag);
20544    }
20545
20546    /**
20547     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
20548     * framework id.
20549     *
20550     * @hide
20551     */
20552    public void setTagInternal(int key, Object tag) {
20553        if ((key >>> 24) != 0x1) {
20554            throw new IllegalArgumentException("The key must be a framework-specific "
20555                    + "resource id.");
20556        }
20557
20558        setKeyedTag(key, tag);
20559    }
20560
20561    private void setKeyedTag(int key, Object tag) {
20562        if (mKeyedTags == null) {
20563            mKeyedTags = new SparseArray<Object>(2);
20564        }
20565
20566        mKeyedTags.put(key, tag);
20567    }
20568
20569    /**
20570     * Prints information about this view in the log output, with the tag
20571     * {@link #VIEW_LOG_TAG}.
20572     *
20573     * @hide
20574     */
20575    public void debug() {
20576        debug(0);
20577    }
20578
20579    /**
20580     * Prints information about this view in the log output, with the tag
20581     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
20582     * indentation defined by the <code>depth</code>.
20583     *
20584     * @param depth the indentation level
20585     *
20586     * @hide
20587     */
20588    protected void debug(int depth) {
20589        String output = debugIndent(depth - 1);
20590
20591        output += "+ " + this;
20592        int id = getId();
20593        if (id != -1) {
20594            output += " (id=" + id + ")";
20595        }
20596        Object tag = getTag();
20597        if (tag != null) {
20598            output += " (tag=" + tag + ")";
20599        }
20600        Log.d(VIEW_LOG_TAG, output);
20601
20602        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
20603            output = debugIndent(depth) + " FOCUSED";
20604            Log.d(VIEW_LOG_TAG, output);
20605        }
20606
20607        output = debugIndent(depth);
20608        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
20609                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
20610                + "} ";
20611        Log.d(VIEW_LOG_TAG, output);
20612
20613        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
20614                || mPaddingBottom != 0) {
20615            output = debugIndent(depth);
20616            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
20617                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
20618            Log.d(VIEW_LOG_TAG, output);
20619        }
20620
20621        output = debugIndent(depth);
20622        output += "mMeasureWidth=" + mMeasuredWidth +
20623                " mMeasureHeight=" + mMeasuredHeight;
20624        Log.d(VIEW_LOG_TAG, output);
20625
20626        output = debugIndent(depth);
20627        if (mLayoutParams == null) {
20628            output += "BAD! no layout params";
20629        } else {
20630            output = mLayoutParams.debug(output);
20631        }
20632        Log.d(VIEW_LOG_TAG, output);
20633
20634        output = debugIndent(depth);
20635        output += "flags={";
20636        output += View.printFlags(mViewFlags);
20637        output += "}";
20638        Log.d(VIEW_LOG_TAG, output);
20639
20640        output = debugIndent(depth);
20641        output += "privateFlags={";
20642        output += View.printPrivateFlags(mPrivateFlags);
20643        output += "}";
20644        Log.d(VIEW_LOG_TAG, output);
20645    }
20646
20647    /**
20648     * Creates a string of whitespaces used for indentation.
20649     *
20650     * @param depth the indentation level
20651     * @return a String containing (depth * 2 + 3) * 2 white spaces
20652     *
20653     * @hide
20654     */
20655    protected static String debugIndent(int depth) {
20656        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
20657        for (int i = 0; i < (depth * 2) + 3; i++) {
20658            spaces.append(' ').append(' ');
20659        }
20660        return spaces.toString();
20661    }
20662
20663    /**
20664     * <p>Return the offset of the widget's text baseline from the widget's top
20665     * boundary. If this widget does not support baseline alignment, this
20666     * method returns -1. </p>
20667     *
20668     * @return the offset of the baseline within the widget's bounds or -1
20669     *         if baseline alignment is not supported
20670     */
20671    @ViewDebug.ExportedProperty(category = "layout")
20672    public int getBaseline() {
20673        return -1;
20674    }
20675
20676    /**
20677     * Returns whether the view hierarchy is currently undergoing a layout pass. This
20678     * information is useful to avoid situations such as calling {@link #requestLayout()} during
20679     * a layout pass.
20680     *
20681     * @return whether the view hierarchy is currently undergoing a layout pass
20682     */
20683    public boolean isInLayout() {
20684        ViewRootImpl viewRoot = getViewRootImpl();
20685        return (viewRoot != null && viewRoot.isInLayout());
20686    }
20687
20688    /**
20689     * Call this when something has changed which has invalidated the
20690     * layout of this view. This will schedule a layout pass of the view
20691     * tree. This should not be called while the view hierarchy is currently in a layout
20692     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
20693     * end of the current layout pass (and then layout will run again) or after the current
20694     * frame is drawn and the next layout occurs.
20695     *
20696     * <p>Subclasses which override this method should call the superclass method to
20697     * handle possible request-during-layout errors correctly.</p>
20698     */
20699    @CallSuper
20700    public void requestLayout() {
20701        if (mMeasureCache != null) mMeasureCache.clear();
20702
20703        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
20704            // Only trigger request-during-layout logic if this is the view requesting it,
20705            // not the views in its parent hierarchy
20706            ViewRootImpl viewRoot = getViewRootImpl();
20707            if (viewRoot != null && viewRoot.isInLayout()) {
20708                if (!viewRoot.requestLayoutDuringLayout(this)) {
20709                    return;
20710                }
20711            }
20712            mAttachInfo.mViewRequestingLayout = this;
20713        }
20714
20715        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20716        mPrivateFlags |= PFLAG_INVALIDATED;
20717
20718        if (mParent != null && !mParent.isLayoutRequested()) {
20719            mParent.requestLayout();
20720        }
20721        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
20722            mAttachInfo.mViewRequestingLayout = null;
20723        }
20724    }
20725
20726    /**
20727     * Forces this view to be laid out during the next layout pass.
20728     * This method does not call requestLayout() or forceLayout()
20729     * on the parent.
20730     */
20731    public void forceLayout() {
20732        if (mMeasureCache != null) mMeasureCache.clear();
20733
20734        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20735        mPrivateFlags |= PFLAG_INVALIDATED;
20736    }
20737
20738    /**
20739     * <p>
20740     * This is called to find out how big a view should be. The parent
20741     * supplies constraint information in the width and height parameters.
20742     * </p>
20743     *
20744     * <p>
20745     * The actual measurement work of a view is performed in
20746     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
20747     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
20748     * </p>
20749     *
20750     *
20751     * @param widthMeasureSpec Horizontal space requirements as imposed by the
20752     *        parent
20753     * @param heightMeasureSpec Vertical space requirements as imposed by the
20754     *        parent
20755     *
20756     * @see #onMeasure(int, int)
20757     */
20758    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
20759        boolean optical = isLayoutModeOptical(this);
20760        if (optical != isLayoutModeOptical(mParent)) {
20761            Insets insets = getOpticalInsets();
20762            int oWidth  = insets.left + insets.right;
20763            int oHeight = insets.top  + insets.bottom;
20764            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
20765            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
20766        }
20767
20768        // Suppress sign extension for the low bytes
20769        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
20770        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
20771
20772        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20773
20774        // Optimize layout by avoiding an extra EXACTLY pass when the view is
20775        // already measured as the correct size. In API 23 and below, this
20776        // extra pass is required to make LinearLayout re-distribute weight.
20777        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
20778                || heightMeasureSpec != mOldHeightMeasureSpec;
20779        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
20780                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
20781        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
20782                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
20783        final boolean needsLayout = specChanged
20784                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
20785
20786        if (forceLayout || needsLayout) {
20787            // first clears the measured dimension flag
20788            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
20789
20790            resolveRtlPropertiesIfNeeded();
20791
20792            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
20793            if (cacheIndex < 0 || sIgnoreMeasureCache) {
20794                // measure ourselves, this should set the measured dimension flag back
20795                onMeasure(widthMeasureSpec, heightMeasureSpec);
20796                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20797            } else {
20798                long value = mMeasureCache.valueAt(cacheIndex);
20799                // Casting a long to int drops the high 32 bits, no mask needed
20800                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
20801                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20802            }
20803
20804            // flag not set, setMeasuredDimension() was not invoked, we raise
20805            // an exception to warn the developer
20806            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
20807                throw new IllegalStateException("View with id " + getId() + ": "
20808                        + getClass().getName() + "#onMeasure() did not set the"
20809                        + " measured dimension by calling"
20810                        + " setMeasuredDimension()");
20811            }
20812
20813            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
20814        }
20815
20816        mOldWidthMeasureSpec = widthMeasureSpec;
20817        mOldHeightMeasureSpec = heightMeasureSpec;
20818
20819        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
20820                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
20821    }
20822
20823    /**
20824     * <p>
20825     * Measure the view and its content to determine the measured width and the
20826     * measured height. This method is invoked by {@link #measure(int, int)} and
20827     * should be overridden by subclasses to provide accurate and efficient
20828     * measurement of their contents.
20829     * </p>
20830     *
20831     * <p>
20832     * <strong>CONTRACT:</strong> When overriding this method, you
20833     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
20834     * measured width and height of this view. Failure to do so will trigger an
20835     * <code>IllegalStateException</code>, thrown by
20836     * {@link #measure(int, int)}. Calling the superclass'
20837     * {@link #onMeasure(int, int)} is a valid use.
20838     * </p>
20839     *
20840     * <p>
20841     * The base class implementation of measure defaults to the background size,
20842     * unless a larger size is allowed by the MeasureSpec. Subclasses should
20843     * override {@link #onMeasure(int, int)} to provide better measurements of
20844     * their content.
20845     * </p>
20846     *
20847     * <p>
20848     * If this method is overridden, it is the subclass's responsibility to make
20849     * sure the measured height and width are at least the view's minimum height
20850     * and width ({@link #getSuggestedMinimumHeight()} and
20851     * {@link #getSuggestedMinimumWidth()}).
20852     * </p>
20853     *
20854     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
20855     *                         The requirements are encoded with
20856     *                         {@link android.view.View.MeasureSpec}.
20857     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
20858     *                         The requirements are encoded with
20859     *                         {@link android.view.View.MeasureSpec}.
20860     *
20861     * @see #getMeasuredWidth()
20862     * @see #getMeasuredHeight()
20863     * @see #setMeasuredDimension(int, int)
20864     * @see #getSuggestedMinimumHeight()
20865     * @see #getSuggestedMinimumWidth()
20866     * @see android.view.View.MeasureSpec#getMode(int)
20867     * @see android.view.View.MeasureSpec#getSize(int)
20868     */
20869    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
20870        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
20871                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
20872    }
20873
20874    /**
20875     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
20876     * measured width and measured height. Failing to do so will trigger an
20877     * exception at measurement time.</p>
20878     *
20879     * @param measuredWidth The measured width of this view.  May be a complex
20880     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20881     * {@link #MEASURED_STATE_TOO_SMALL}.
20882     * @param measuredHeight The measured height of this view.  May be a complex
20883     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20884     * {@link #MEASURED_STATE_TOO_SMALL}.
20885     */
20886    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
20887        boolean optical = isLayoutModeOptical(this);
20888        if (optical != isLayoutModeOptical(mParent)) {
20889            Insets insets = getOpticalInsets();
20890            int opticalWidth  = insets.left + insets.right;
20891            int opticalHeight = insets.top  + insets.bottom;
20892
20893            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
20894            measuredHeight += optical ? opticalHeight : -opticalHeight;
20895        }
20896        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
20897    }
20898
20899    /**
20900     * Sets the measured dimension without extra processing for things like optical bounds.
20901     * Useful for reapplying consistent values that have already been cooked with adjustments
20902     * for optical bounds, etc. such as those from the measurement cache.
20903     *
20904     * @param measuredWidth The measured width of this view.  May be a complex
20905     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20906     * {@link #MEASURED_STATE_TOO_SMALL}.
20907     * @param measuredHeight The measured height of this view.  May be a complex
20908     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20909     * {@link #MEASURED_STATE_TOO_SMALL}.
20910     */
20911    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
20912        mMeasuredWidth = measuredWidth;
20913        mMeasuredHeight = measuredHeight;
20914
20915        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
20916    }
20917
20918    /**
20919     * Merge two states as returned by {@link #getMeasuredState()}.
20920     * @param curState The current state as returned from a view or the result
20921     * of combining multiple views.
20922     * @param newState The new view state to combine.
20923     * @return Returns a new integer reflecting the combination of the two
20924     * states.
20925     */
20926    public static int combineMeasuredStates(int curState, int newState) {
20927        return curState | newState;
20928    }
20929
20930    /**
20931     * Version of {@link #resolveSizeAndState(int, int, int)}
20932     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
20933     */
20934    public static int resolveSize(int size, int measureSpec) {
20935        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
20936    }
20937
20938    /**
20939     * Utility to reconcile a desired size and state, with constraints imposed
20940     * by a MeasureSpec. Will take the desired size, unless a different size
20941     * is imposed by the constraints. The returned value is a compound integer,
20942     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20943     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20944     * resulting size is smaller than the size the view wants to be.
20945     *
20946     * @param size How big the view wants to be.
20947     * @param measureSpec Constraints imposed by the parent.
20948     * @param childMeasuredState Size information bit mask for the view's
20949     *                           children.
20950     * @return Size information bit mask as defined by
20951     *         {@link #MEASURED_SIZE_MASK} and
20952     *         {@link #MEASURED_STATE_TOO_SMALL}.
20953     */
20954    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20955        final int specMode = MeasureSpec.getMode(measureSpec);
20956        final int specSize = MeasureSpec.getSize(measureSpec);
20957        final int result;
20958        switch (specMode) {
20959            case MeasureSpec.AT_MOST:
20960                if (specSize < size) {
20961                    result = specSize | MEASURED_STATE_TOO_SMALL;
20962                } else {
20963                    result = size;
20964                }
20965                break;
20966            case MeasureSpec.EXACTLY:
20967                result = specSize;
20968                break;
20969            case MeasureSpec.UNSPECIFIED:
20970            default:
20971                result = size;
20972        }
20973        return result | (childMeasuredState & MEASURED_STATE_MASK);
20974    }
20975
20976    /**
20977     * Utility to return a default size. Uses the supplied size if the
20978     * MeasureSpec imposed no constraints. Will get larger if allowed
20979     * by the MeasureSpec.
20980     *
20981     * @param size Default size for this view
20982     * @param measureSpec Constraints imposed by the parent
20983     * @return The size this view should be.
20984     */
20985    public static int getDefaultSize(int size, int measureSpec) {
20986        int result = size;
20987        int specMode = MeasureSpec.getMode(measureSpec);
20988        int specSize = MeasureSpec.getSize(measureSpec);
20989
20990        switch (specMode) {
20991        case MeasureSpec.UNSPECIFIED:
20992            result = size;
20993            break;
20994        case MeasureSpec.AT_MOST:
20995        case MeasureSpec.EXACTLY:
20996            result = specSize;
20997            break;
20998        }
20999        return result;
21000    }
21001
21002    /**
21003     * Returns the suggested minimum height that the view should use. This
21004     * returns the maximum of the view's minimum height
21005     * and the background's minimum height
21006     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
21007     * <p>
21008     * When being used in {@link #onMeasure(int, int)}, the caller should still
21009     * ensure the returned height is within the requirements of the parent.
21010     *
21011     * @return The suggested minimum height of the view.
21012     */
21013    protected int getSuggestedMinimumHeight() {
21014        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
21015
21016    }
21017
21018    /**
21019     * Returns the suggested minimum width that the view should use. This
21020     * returns the maximum of the view's minimum width
21021     * and the background's minimum width
21022     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
21023     * <p>
21024     * When being used in {@link #onMeasure(int, int)}, the caller should still
21025     * ensure the returned width is within the requirements of the parent.
21026     *
21027     * @return The suggested minimum width of the view.
21028     */
21029    protected int getSuggestedMinimumWidth() {
21030        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
21031    }
21032
21033    /**
21034     * Returns the minimum height of the view.
21035     *
21036     * @return the minimum height the view will try to be, in pixels
21037     *
21038     * @see #setMinimumHeight(int)
21039     *
21040     * @attr ref android.R.styleable#View_minHeight
21041     */
21042    public int getMinimumHeight() {
21043        return mMinHeight;
21044    }
21045
21046    /**
21047     * Sets the minimum height of the view. It is not guaranteed the view will
21048     * be able to achieve this minimum height (for example, if its parent layout
21049     * constrains it with less available height).
21050     *
21051     * @param minHeight The minimum height the view will try to be, in pixels
21052     *
21053     * @see #getMinimumHeight()
21054     *
21055     * @attr ref android.R.styleable#View_minHeight
21056     */
21057    @RemotableViewMethod
21058    public void setMinimumHeight(int minHeight) {
21059        mMinHeight = minHeight;
21060        requestLayout();
21061    }
21062
21063    /**
21064     * Returns the minimum width of the view.
21065     *
21066     * @return the minimum width the view will try to be, in pixels
21067     *
21068     * @see #setMinimumWidth(int)
21069     *
21070     * @attr ref android.R.styleable#View_minWidth
21071     */
21072    public int getMinimumWidth() {
21073        return mMinWidth;
21074    }
21075
21076    /**
21077     * Sets the minimum width of the view. It is not guaranteed the view will
21078     * be able to achieve this minimum width (for example, if its parent layout
21079     * constrains it with less available width).
21080     *
21081     * @param minWidth The minimum width the view will try to be, in pixels
21082     *
21083     * @see #getMinimumWidth()
21084     *
21085     * @attr ref android.R.styleable#View_minWidth
21086     */
21087    public void setMinimumWidth(int minWidth) {
21088        mMinWidth = minWidth;
21089        requestLayout();
21090
21091    }
21092
21093    /**
21094     * Get the animation currently associated with this view.
21095     *
21096     * @return The animation that is currently playing or
21097     *         scheduled to play for this view.
21098     */
21099    public Animation getAnimation() {
21100        return mCurrentAnimation;
21101    }
21102
21103    /**
21104     * Start the specified animation now.
21105     *
21106     * @param animation the animation to start now
21107     */
21108    public void startAnimation(Animation animation) {
21109        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
21110        setAnimation(animation);
21111        invalidateParentCaches();
21112        invalidate(true);
21113    }
21114
21115    /**
21116     * Cancels any animations for this view.
21117     */
21118    public void clearAnimation() {
21119        if (mCurrentAnimation != null) {
21120            mCurrentAnimation.detach();
21121        }
21122        mCurrentAnimation = null;
21123        invalidateParentIfNeeded();
21124    }
21125
21126    /**
21127     * Sets the next animation to play for this view.
21128     * If you want the animation to play immediately, use
21129     * {@link #startAnimation(android.view.animation.Animation)} instead.
21130     * This method provides allows fine-grained
21131     * control over the start time and invalidation, but you
21132     * must make sure that 1) the animation has a start time set, and
21133     * 2) the view's parent (which controls animations on its children)
21134     * will be invalidated when the animation is supposed to
21135     * start.
21136     *
21137     * @param animation The next animation, or null.
21138     */
21139    public void setAnimation(Animation animation) {
21140        mCurrentAnimation = animation;
21141
21142        if (animation != null) {
21143            // If the screen is off assume the animation start time is now instead of
21144            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
21145            // would cause the animation to start when the screen turns back on
21146            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
21147                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
21148                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
21149            }
21150            animation.reset();
21151        }
21152    }
21153
21154    /**
21155     * Invoked by a parent ViewGroup to notify the start of the animation
21156     * currently associated with this view. If you override this method,
21157     * always call super.onAnimationStart();
21158     *
21159     * @see #setAnimation(android.view.animation.Animation)
21160     * @see #getAnimation()
21161     */
21162    @CallSuper
21163    protected void onAnimationStart() {
21164        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
21165    }
21166
21167    /**
21168     * Invoked by a parent ViewGroup to notify the end of the animation
21169     * currently associated with this view. If you override this method,
21170     * always call super.onAnimationEnd();
21171     *
21172     * @see #setAnimation(android.view.animation.Animation)
21173     * @see #getAnimation()
21174     */
21175    @CallSuper
21176    protected void onAnimationEnd() {
21177        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
21178    }
21179
21180    /**
21181     * Invoked if there is a Transform that involves alpha. Subclass that can
21182     * draw themselves with the specified alpha should return true, and then
21183     * respect that alpha when their onDraw() is called. If this returns false
21184     * then the view may be redirected to draw into an offscreen buffer to
21185     * fulfill the request, which will look fine, but may be slower than if the
21186     * subclass handles it internally. The default implementation returns false.
21187     *
21188     * @param alpha The alpha (0..255) to apply to the view's drawing
21189     * @return true if the view can draw with the specified alpha.
21190     */
21191    protected boolean onSetAlpha(int alpha) {
21192        return false;
21193    }
21194
21195    /**
21196     * This is used by the RootView to perform an optimization when
21197     * the view hierarchy contains one or several SurfaceView.
21198     * SurfaceView is always considered transparent, but its children are not,
21199     * therefore all View objects remove themselves from the global transparent
21200     * region (passed as a parameter to this function).
21201     *
21202     * @param region The transparent region for this ViewAncestor (window).
21203     *
21204     * @return Returns true if the effective visibility of the view at this
21205     * point is opaque, regardless of the transparent region; returns false
21206     * if it is possible for underlying windows to be seen behind the view.
21207     *
21208     * {@hide}
21209     */
21210    public boolean gatherTransparentRegion(Region region) {
21211        final AttachInfo attachInfo = mAttachInfo;
21212        if (region != null && attachInfo != null) {
21213            final int pflags = mPrivateFlags;
21214            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
21215                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
21216                // remove it from the transparent region.
21217                final int[] location = attachInfo.mTransparentLocation;
21218                getLocationInWindow(location);
21219                // When a view has Z value, then it will be better to leave some area below the view
21220                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
21221                // the bottom part needs more offset than the left, top and right parts due to the
21222                // spot light effects.
21223                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
21224                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
21225                        location[0] + mRight - mLeft + shadowOffset,
21226                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
21227            } else {
21228                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
21229                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
21230                    // the background drawable's non-transparent parts from this transparent region.
21231                    applyDrawableToTransparentRegion(mBackground, region);
21232                }
21233                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
21234                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
21235                    // Similarly, we remove the foreground drawable's non-transparent parts.
21236                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
21237                }
21238            }
21239        }
21240        return true;
21241    }
21242
21243    /**
21244     * Play a sound effect for this view.
21245     *
21246     * <p>The framework will play sound effects for some built in actions, such as
21247     * clicking, but you may wish to play these effects in your widget,
21248     * for instance, for internal navigation.
21249     *
21250     * <p>The sound effect will only be played if sound effects are enabled by the user, and
21251     * {@link #isSoundEffectsEnabled()} is true.
21252     *
21253     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
21254     */
21255    public void playSoundEffect(int soundConstant) {
21256        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
21257            return;
21258        }
21259        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
21260    }
21261
21262    /**
21263     * BZZZTT!!1!
21264     *
21265     * <p>Provide haptic feedback to the user for this view.
21266     *
21267     * <p>The framework will provide haptic feedback for some built in actions,
21268     * such as long presses, but you may wish to provide feedback for your
21269     * own widget.
21270     *
21271     * <p>The feedback will only be performed if
21272     * {@link #isHapticFeedbackEnabled()} is true.
21273     *
21274     * @param feedbackConstant One of the constants defined in
21275     * {@link HapticFeedbackConstants}
21276     */
21277    public boolean performHapticFeedback(int feedbackConstant) {
21278        return performHapticFeedback(feedbackConstant, 0);
21279    }
21280
21281    /**
21282     * BZZZTT!!1!
21283     *
21284     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
21285     *
21286     * @param feedbackConstant One of the constants defined in
21287     * {@link HapticFeedbackConstants}
21288     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
21289     */
21290    public boolean performHapticFeedback(int feedbackConstant, int flags) {
21291        if (mAttachInfo == null) {
21292            return false;
21293        }
21294        //noinspection SimplifiableIfStatement
21295        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
21296                && !isHapticFeedbackEnabled()) {
21297            return false;
21298        }
21299        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
21300                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
21301    }
21302
21303    /**
21304     * Request that the visibility of the status bar or other screen/window
21305     * decorations be changed.
21306     *
21307     * <p>This method is used to put the over device UI into temporary modes
21308     * where the user's attention is focused more on the application content,
21309     * by dimming or hiding surrounding system affordances.  This is typically
21310     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
21311     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
21312     * to be placed behind the action bar (and with these flags other system
21313     * affordances) so that smooth transitions between hiding and showing them
21314     * can be done.
21315     *
21316     * <p>Two representative examples of the use of system UI visibility is
21317     * implementing a content browsing application (like a magazine reader)
21318     * and a video playing application.
21319     *
21320     * <p>The first code shows a typical implementation of a View in a content
21321     * browsing application.  In this implementation, the application goes
21322     * into a content-oriented mode by hiding the status bar and action bar,
21323     * and putting the navigation elements into lights out mode.  The user can
21324     * then interact with content while in this mode.  Such an application should
21325     * provide an easy way for the user to toggle out of the mode (such as to
21326     * check information in the status bar or access notifications).  In the
21327     * implementation here, this is done simply by tapping on the content.
21328     *
21329     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
21330     *      content}
21331     *
21332     * <p>This second code sample shows a typical implementation of a View
21333     * in a video playing application.  In this situation, while the video is
21334     * playing the application would like to go into a complete full-screen mode,
21335     * to use as much of the display as possible for the video.  When in this state
21336     * the user can not interact with the application; the system intercepts
21337     * touching on the screen to pop the UI out of full screen mode.  See
21338     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
21339     *
21340     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
21341     *      content}
21342     *
21343     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21344     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21345     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21346     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21347     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21348     */
21349    public void setSystemUiVisibility(int visibility) {
21350        if (visibility != mSystemUiVisibility) {
21351            mSystemUiVisibility = visibility;
21352            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21353                mParent.recomputeViewAttributes(this);
21354            }
21355        }
21356    }
21357
21358    /**
21359     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
21360     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21361     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21362     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21363     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21364     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21365     */
21366    public int getSystemUiVisibility() {
21367        return mSystemUiVisibility;
21368    }
21369
21370    /**
21371     * Returns the current system UI visibility that is currently set for
21372     * the entire window.  This is the combination of the
21373     * {@link #setSystemUiVisibility(int)} values supplied by all of the
21374     * views in the window.
21375     */
21376    public int getWindowSystemUiVisibility() {
21377        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
21378    }
21379
21380    /**
21381     * Override to find out when the window's requested system UI visibility
21382     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
21383     * This is different from the callbacks received through
21384     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
21385     * in that this is only telling you about the local request of the window,
21386     * not the actual values applied by the system.
21387     */
21388    public void onWindowSystemUiVisibilityChanged(int visible) {
21389    }
21390
21391    /**
21392     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
21393     * the view hierarchy.
21394     */
21395    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
21396        onWindowSystemUiVisibilityChanged(visible);
21397    }
21398
21399    /**
21400     * Set a listener to receive callbacks when the visibility of the system bar changes.
21401     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
21402     */
21403    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
21404        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
21405        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21406            mParent.recomputeViewAttributes(this);
21407        }
21408    }
21409
21410    /**
21411     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
21412     * the view hierarchy.
21413     */
21414    public void dispatchSystemUiVisibilityChanged(int visibility) {
21415        ListenerInfo li = mListenerInfo;
21416        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
21417            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
21418                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
21419        }
21420    }
21421
21422    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
21423        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
21424        if (val != mSystemUiVisibility) {
21425            setSystemUiVisibility(val);
21426            return true;
21427        }
21428        return false;
21429    }
21430
21431    /** @hide */
21432    public void setDisabledSystemUiVisibility(int flags) {
21433        if (mAttachInfo != null) {
21434            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
21435                mAttachInfo.mDisabledSystemUiVisibility = flags;
21436                if (mParent != null) {
21437                    mParent.recomputeViewAttributes(this);
21438                }
21439            }
21440        }
21441    }
21442
21443    /**
21444     * Creates an image that the system displays during the drag and drop
21445     * operation. This is called a &quot;drag shadow&quot;. The default implementation
21446     * for a DragShadowBuilder based on a View returns an image that has exactly the same
21447     * appearance as the given View. The default also positions the center of the drag shadow
21448     * directly under the touch point. If no View is provided (the constructor with no parameters
21449     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
21450     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
21451     * default is an invisible drag shadow.
21452     * <p>
21453     * You are not required to use the View you provide to the constructor as the basis of the
21454     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
21455     * anything you want as the drag shadow.
21456     * </p>
21457     * <p>
21458     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
21459     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
21460     *  size and position of the drag shadow. It uses this data to construct a
21461     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
21462     *  so that your application can draw the shadow image in the Canvas.
21463     * </p>
21464     *
21465     * <div class="special reference">
21466     * <h3>Developer Guides</h3>
21467     * <p>For a guide to implementing drag and drop features, read the
21468     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
21469     * </div>
21470     */
21471    public static class DragShadowBuilder {
21472        private final WeakReference<View> mView;
21473
21474        /**
21475         * Constructs a shadow image builder based on a View. By default, the resulting drag
21476         * shadow will have the same appearance and dimensions as the View, with the touch point
21477         * over the center of the View.
21478         * @param view A View. Any View in scope can be used.
21479         */
21480        public DragShadowBuilder(View view) {
21481            mView = new WeakReference<View>(view);
21482        }
21483
21484        /**
21485         * Construct a shadow builder object with no associated View.  This
21486         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
21487         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
21488         * to supply the drag shadow's dimensions and appearance without
21489         * reference to any View object. If they are not overridden, then the result is an
21490         * invisible drag shadow.
21491         */
21492        public DragShadowBuilder() {
21493            mView = new WeakReference<View>(null);
21494        }
21495
21496        /**
21497         * Returns the View object that had been passed to the
21498         * {@link #View.DragShadowBuilder(View)}
21499         * constructor.  If that View parameter was {@code null} or if the
21500         * {@link #View.DragShadowBuilder()}
21501         * constructor was used to instantiate the builder object, this method will return
21502         * null.
21503         *
21504         * @return The View object associate with this builder object.
21505         */
21506        @SuppressWarnings({"JavadocReference"})
21507        final public View getView() {
21508            return mView.get();
21509        }
21510
21511        /**
21512         * Provides the metrics for the shadow image. These include the dimensions of
21513         * the shadow image, and the point within that shadow that should
21514         * be centered under the touch location while dragging.
21515         * <p>
21516         * The default implementation sets the dimensions of the shadow to be the
21517         * same as the dimensions of the View itself and centers the shadow under
21518         * the touch point.
21519         * </p>
21520         *
21521         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
21522         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
21523         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
21524         * image.
21525         *
21526         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
21527         * shadow image that should be underneath the touch point during the drag and drop
21528         * operation. Your application must set {@link android.graphics.Point#x} to the
21529         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
21530         */
21531        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
21532            final View view = mView.get();
21533            if (view != null) {
21534                outShadowSize.set(view.getWidth(), view.getHeight());
21535                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
21536            } else {
21537                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
21538            }
21539        }
21540
21541        /**
21542         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
21543         * based on the dimensions it received from the
21544         * {@link #onProvideShadowMetrics(Point, Point)} callback.
21545         *
21546         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
21547         */
21548        public void onDrawShadow(Canvas canvas) {
21549            final View view = mView.get();
21550            if (view != null) {
21551                view.draw(canvas);
21552            } else {
21553                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
21554            }
21555        }
21556    }
21557
21558    /**
21559     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
21560     * startDragAndDrop()} for newer platform versions.
21561     */
21562    @Deprecated
21563    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
21564                                   Object myLocalState, int flags) {
21565        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
21566    }
21567
21568    /**
21569     * Starts a drag and drop operation. When your application calls this method, it passes a
21570     * {@link android.view.View.DragShadowBuilder} object to the system. The
21571     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
21572     * to get metrics for the drag shadow, and then calls the object's
21573     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
21574     * <p>
21575     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
21576     *  drag events to all the View objects in your application that are currently visible. It does
21577     *  this either by calling the View object's drag listener (an implementation of
21578     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
21579     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
21580     *  Both are passed a {@link android.view.DragEvent} object that has a
21581     *  {@link android.view.DragEvent#getAction()} value of
21582     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
21583     * </p>
21584     * <p>
21585     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
21586     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
21587     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
21588     * to the View the user selected for dragging.
21589     * </p>
21590     * @param data A {@link android.content.ClipData} object pointing to the data to be
21591     * transferred by the drag and drop operation.
21592     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21593     * drag shadow.
21594     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
21595     * drop operation. When dispatching drag events to views in the same activity this object
21596     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
21597     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
21598     * will return null).
21599     * <p>
21600     * myLocalState is a lightweight mechanism for the sending information from the dragged View
21601     * to the target Views. For example, it can contain flags that differentiate between a
21602     * a copy operation and a move operation.
21603     * </p>
21604     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
21605     * flags, or any combination of the following:
21606     *     <ul>
21607     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
21608     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
21609     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
21610     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
21611     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
21612     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
21613     *     </ul>
21614     * @return {@code true} if the method completes successfully, or
21615     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
21616     * do a drag, and so no drag operation is in progress.
21617     */
21618    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
21619            Object myLocalState, int flags) {
21620        if (ViewDebug.DEBUG_DRAG) {
21621            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
21622        }
21623        if (mAttachInfo == null) {
21624            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
21625            return false;
21626        }
21627
21628        if (data != null) {
21629            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
21630        }
21631
21632        boolean okay = false;
21633
21634        Point shadowSize = new Point();
21635        Point shadowTouchPoint = new Point();
21636        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
21637
21638        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
21639                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
21640            throw new IllegalStateException("Drag shadow dimensions must not be negative");
21641        }
21642
21643        if (ViewDebug.DEBUG_DRAG) {
21644            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
21645                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
21646        }
21647        if (mAttachInfo.mDragSurface != null) {
21648            mAttachInfo.mDragSurface.release();
21649        }
21650        mAttachInfo.mDragSurface = new Surface();
21651        try {
21652            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
21653                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
21654            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
21655                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
21656            if (mAttachInfo.mDragToken != null) {
21657                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21658                try {
21659                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21660                    shadowBuilder.onDrawShadow(canvas);
21661                } finally {
21662                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21663                }
21664
21665                final ViewRootImpl root = getViewRootImpl();
21666
21667                // Cache the local state object for delivery with DragEvents
21668                root.setLocalDragState(myLocalState);
21669
21670                // repurpose 'shadowSize' for the last touch point
21671                root.getLastTouchPoint(shadowSize);
21672
21673                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
21674                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
21675                        shadowTouchPoint.x, shadowTouchPoint.y, data);
21676                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
21677            }
21678        } catch (Exception e) {
21679            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
21680            mAttachInfo.mDragSurface.destroy();
21681            mAttachInfo.mDragSurface = null;
21682        }
21683
21684        return okay;
21685    }
21686
21687    /**
21688     * Cancels an ongoing drag and drop operation.
21689     * <p>
21690     * A {@link android.view.DragEvent} object with
21691     * {@link android.view.DragEvent#getAction()} value of
21692     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
21693     * {@link android.view.DragEvent#getResult()} value of {@code false}
21694     * will be sent to every
21695     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
21696     * even if they are not currently visible.
21697     * </p>
21698     * <p>
21699     * This method can be called on any View in the same window as the View on which
21700     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
21701     * was called.
21702     * </p>
21703     */
21704    public final void cancelDragAndDrop() {
21705        if (ViewDebug.DEBUG_DRAG) {
21706            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
21707        }
21708        if (mAttachInfo == null) {
21709            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
21710            return;
21711        }
21712        if (mAttachInfo.mDragToken != null) {
21713            try {
21714                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
21715            } catch (Exception e) {
21716                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
21717            }
21718            mAttachInfo.mDragToken = null;
21719        } else {
21720            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
21721        }
21722    }
21723
21724    /**
21725     * Updates the drag shadow for the ongoing drag and drop operation.
21726     *
21727     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21728     * new drag shadow.
21729     */
21730    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
21731        if (ViewDebug.DEBUG_DRAG) {
21732            Log.d(VIEW_LOG_TAG, "updateDragShadow");
21733        }
21734        if (mAttachInfo == null) {
21735            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
21736            return;
21737        }
21738        if (mAttachInfo.mDragToken != null) {
21739            try {
21740                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21741                try {
21742                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21743                    shadowBuilder.onDrawShadow(canvas);
21744                } finally {
21745                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21746                }
21747            } catch (Exception e) {
21748                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
21749            }
21750        } else {
21751            Log.e(VIEW_LOG_TAG, "No active drag");
21752        }
21753    }
21754
21755    /**
21756     * Starts a move from {startX, startY}, the amount of the movement will be the offset
21757     * between {startX, startY} and the new cursor positon.
21758     * @param startX horizontal coordinate where the move started.
21759     * @param startY vertical coordinate where the move started.
21760     * @return whether moving was started successfully.
21761     * @hide
21762     */
21763    public final boolean startMovingTask(float startX, float startY) {
21764        if (ViewDebug.DEBUG_POSITIONING) {
21765            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
21766        }
21767        try {
21768            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
21769        } catch (RemoteException e) {
21770            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
21771        }
21772        return false;
21773    }
21774
21775    /**
21776     * Handles drag events sent by the system following a call to
21777     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
21778     * startDragAndDrop()}.
21779     *<p>
21780     * When the system calls this method, it passes a
21781     * {@link android.view.DragEvent} object. A call to
21782     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
21783     * in DragEvent. The method uses these to determine what is happening in the drag and drop
21784     * operation.
21785     * @param event The {@link android.view.DragEvent} sent by the system.
21786     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
21787     * in DragEvent, indicating the type of drag event represented by this object.
21788     * @return {@code true} if the method was successful, otherwise {@code false}.
21789     * <p>
21790     *  The method should return {@code true} in response to an action type of
21791     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
21792     *  operation.
21793     * </p>
21794     * <p>
21795     *  The method should also return {@code true} in response to an action type of
21796     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
21797     *  {@code false} if it didn't.
21798     * </p>
21799     * <p>
21800     *  For all other events, the return value is ignored.
21801     * </p>
21802     */
21803    public boolean onDragEvent(DragEvent event) {
21804        return false;
21805    }
21806
21807    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
21808    boolean dispatchDragEnterExitInPreN(DragEvent event) {
21809        return callDragEventHandler(event);
21810    }
21811
21812    /**
21813     * Detects if this View is enabled and has a drag event listener.
21814     * If both are true, then it calls the drag event listener with the
21815     * {@link android.view.DragEvent} it received. If the drag event listener returns
21816     * {@code true}, then dispatchDragEvent() returns {@code true}.
21817     * <p>
21818     * For all other cases, the method calls the
21819     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
21820     * method and returns its result.
21821     * </p>
21822     * <p>
21823     * This ensures that a drag event is always consumed, even if the View does not have a drag
21824     * event listener. However, if the View has a listener and the listener returns true, then
21825     * onDragEvent() is not called.
21826     * </p>
21827     */
21828    public boolean dispatchDragEvent(DragEvent event) {
21829        event.mEventHandlerWasCalled = true;
21830        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
21831            event.mAction == DragEvent.ACTION_DROP) {
21832            // About to deliver an event with coordinates to this view. Notify that now this view
21833            // has drag focus. This will send exit/enter events as needed.
21834            getViewRootImpl().setDragFocus(this, event);
21835        }
21836        return callDragEventHandler(event);
21837    }
21838
21839    final boolean callDragEventHandler(DragEvent event) {
21840        final boolean result;
21841
21842        ListenerInfo li = mListenerInfo;
21843        //noinspection SimplifiableIfStatement
21844        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
21845                && li.mOnDragListener.onDrag(this, event)) {
21846            result = true;
21847        } else {
21848            result = onDragEvent(event);
21849        }
21850
21851        switch (event.mAction) {
21852            case DragEvent.ACTION_DRAG_ENTERED: {
21853                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
21854                refreshDrawableState();
21855            } break;
21856            case DragEvent.ACTION_DRAG_EXITED: {
21857                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
21858                refreshDrawableState();
21859            } break;
21860            case DragEvent.ACTION_DRAG_ENDED: {
21861                mPrivateFlags2 &= ~View.DRAG_MASK;
21862                refreshDrawableState();
21863            } break;
21864        }
21865
21866        return result;
21867    }
21868
21869    boolean canAcceptDrag() {
21870        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
21871    }
21872
21873    /**
21874     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
21875     * it is ever exposed at all.
21876     * @hide
21877     */
21878    public void onCloseSystemDialogs(String reason) {
21879    }
21880
21881    /**
21882     * Given a Drawable whose bounds have been set to draw into this view,
21883     * update a Region being computed for
21884     * {@link #gatherTransparentRegion(android.graphics.Region)} so
21885     * that any non-transparent parts of the Drawable are removed from the
21886     * given transparent region.
21887     *
21888     * @param dr The Drawable whose transparency is to be applied to the region.
21889     * @param region A Region holding the current transparency information,
21890     * where any parts of the region that are set are considered to be
21891     * transparent.  On return, this region will be modified to have the
21892     * transparency information reduced by the corresponding parts of the
21893     * Drawable that are not transparent.
21894     * {@hide}
21895     */
21896    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
21897        if (DBG) {
21898            Log.i("View", "Getting transparent region for: " + this);
21899        }
21900        final Region r = dr.getTransparentRegion();
21901        final Rect db = dr.getBounds();
21902        final AttachInfo attachInfo = mAttachInfo;
21903        if (r != null && attachInfo != null) {
21904            final int w = getRight()-getLeft();
21905            final int h = getBottom()-getTop();
21906            if (db.left > 0) {
21907                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
21908                r.op(0, 0, db.left, h, Region.Op.UNION);
21909            }
21910            if (db.right < w) {
21911                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
21912                r.op(db.right, 0, w, h, Region.Op.UNION);
21913            }
21914            if (db.top > 0) {
21915                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
21916                r.op(0, 0, w, db.top, Region.Op.UNION);
21917            }
21918            if (db.bottom < h) {
21919                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
21920                r.op(0, db.bottom, w, h, Region.Op.UNION);
21921            }
21922            final int[] location = attachInfo.mTransparentLocation;
21923            getLocationInWindow(location);
21924            r.translate(location[0], location[1]);
21925            region.op(r, Region.Op.INTERSECT);
21926        } else {
21927            region.op(db, Region.Op.DIFFERENCE);
21928        }
21929    }
21930
21931    private void checkForLongClick(int delayOffset, float x, float y) {
21932        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
21933            mHasPerformedLongPress = false;
21934
21935            if (mPendingCheckForLongPress == null) {
21936                mPendingCheckForLongPress = new CheckForLongPress();
21937            }
21938            mPendingCheckForLongPress.setAnchor(x, y);
21939            mPendingCheckForLongPress.rememberWindowAttachCount();
21940            mPendingCheckForLongPress.rememberPressedState();
21941            postDelayed(mPendingCheckForLongPress,
21942                    ViewConfiguration.getLongPressTimeout() - delayOffset);
21943        }
21944    }
21945
21946    /**
21947     * Inflate a view from an XML resource.  This convenience method wraps the {@link
21948     * LayoutInflater} class, which provides a full range of options for view inflation.
21949     *
21950     * @param context The Context object for your activity or application.
21951     * @param resource The resource ID to inflate
21952     * @param root A view group that will be the parent.  Used to properly inflate the
21953     * layout_* parameters.
21954     * @see LayoutInflater
21955     */
21956    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
21957        LayoutInflater factory = LayoutInflater.from(context);
21958        return factory.inflate(resource, root);
21959    }
21960
21961    /**
21962     * Scroll the view with standard behavior for scrolling beyond the normal
21963     * content boundaries. Views that call this method should override
21964     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
21965     * results of an over-scroll operation.
21966     *
21967     * Views can use this method to handle any touch or fling-based scrolling.
21968     *
21969     * @param deltaX Change in X in pixels
21970     * @param deltaY Change in Y in pixels
21971     * @param scrollX Current X scroll value in pixels before applying deltaX
21972     * @param scrollY Current Y scroll value in pixels before applying deltaY
21973     * @param scrollRangeX Maximum content scroll range along the X axis
21974     * @param scrollRangeY Maximum content scroll range along the Y axis
21975     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21976     *          along the X axis.
21977     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21978     *          along the Y axis.
21979     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21980     * @return true if scrolling was clamped to an over-scroll boundary along either
21981     *          axis, false otherwise.
21982     */
21983    @SuppressWarnings({"UnusedParameters"})
21984    protected boolean overScrollBy(int deltaX, int deltaY,
21985            int scrollX, int scrollY,
21986            int scrollRangeX, int scrollRangeY,
21987            int maxOverScrollX, int maxOverScrollY,
21988            boolean isTouchEvent) {
21989        final int overScrollMode = mOverScrollMode;
21990        final boolean canScrollHorizontal =
21991                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21992        final boolean canScrollVertical =
21993                computeVerticalScrollRange() > computeVerticalScrollExtent();
21994        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21995                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21996        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21997                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21998
21999        int newScrollX = scrollX + deltaX;
22000        if (!overScrollHorizontal) {
22001            maxOverScrollX = 0;
22002        }
22003
22004        int newScrollY = scrollY + deltaY;
22005        if (!overScrollVertical) {
22006            maxOverScrollY = 0;
22007        }
22008
22009        // Clamp values if at the limits and record
22010        final int left = -maxOverScrollX;
22011        final int right = maxOverScrollX + scrollRangeX;
22012        final int top = -maxOverScrollY;
22013        final int bottom = maxOverScrollY + scrollRangeY;
22014
22015        boolean clampedX = false;
22016        if (newScrollX > right) {
22017            newScrollX = right;
22018            clampedX = true;
22019        } else if (newScrollX < left) {
22020            newScrollX = left;
22021            clampedX = true;
22022        }
22023
22024        boolean clampedY = false;
22025        if (newScrollY > bottom) {
22026            newScrollY = bottom;
22027            clampedY = true;
22028        } else if (newScrollY < top) {
22029            newScrollY = top;
22030            clampedY = true;
22031        }
22032
22033        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
22034
22035        return clampedX || clampedY;
22036    }
22037
22038    /**
22039     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
22040     * respond to the results of an over-scroll operation.
22041     *
22042     * @param scrollX New X scroll value in pixels
22043     * @param scrollY New Y scroll value in pixels
22044     * @param clampedX True if scrollX was clamped to an over-scroll boundary
22045     * @param clampedY True if scrollY was clamped to an over-scroll boundary
22046     */
22047    protected void onOverScrolled(int scrollX, int scrollY,
22048            boolean clampedX, boolean clampedY) {
22049        // Intentionally empty.
22050    }
22051
22052    /**
22053     * Returns the over-scroll mode for this view. The result will be
22054     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22055     * (allow over-scrolling only if the view content is larger than the container),
22056     * or {@link #OVER_SCROLL_NEVER}.
22057     *
22058     * @return This view's over-scroll mode.
22059     */
22060    public int getOverScrollMode() {
22061        return mOverScrollMode;
22062    }
22063
22064    /**
22065     * Set the over-scroll mode for this view. Valid over-scroll modes are
22066     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22067     * (allow over-scrolling only if the view content is larger than the container),
22068     * or {@link #OVER_SCROLL_NEVER}.
22069     *
22070     * Setting the over-scroll mode of a view will have an effect only if the
22071     * view is capable of scrolling.
22072     *
22073     * @param overScrollMode The new over-scroll mode for this view.
22074     */
22075    public void setOverScrollMode(int overScrollMode) {
22076        if (overScrollMode != OVER_SCROLL_ALWAYS &&
22077                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
22078                overScrollMode != OVER_SCROLL_NEVER) {
22079            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
22080        }
22081        mOverScrollMode = overScrollMode;
22082    }
22083
22084    /**
22085     * Enable or disable nested scrolling for this view.
22086     *
22087     * <p>If this property is set to true the view will be permitted to initiate nested
22088     * scrolling operations with a compatible parent view in the current hierarchy. If this
22089     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
22090     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
22091     * the nested scroll.</p>
22092     *
22093     * @param enabled true to enable nested scrolling, false to disable
22094     *
22095     * @see #isNestedScrollingEnabled()
22096     */
22097    public void setNestedScrollingEnabled(boolean enabled) {
22098        if (enabled) {
22099            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
22100        } else {
22101            stopNestedScroll();
22102            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
22103        }
22104    }
22105
22106    /**
22107     * Returns true if nested scrolling is enabled for this view.
22108     *
22109     * <p>If nested scrolling is enabled and this View class implementation supports it,
22110     * this view will act as a nested scrolling child view when applicable, forwarding data
22111     * about the scroll operation in progress to a compatible and cooperating nested scrolling
22112     * parent.</p>
22113     *
22114     * @return true if nested scrolling is enabled
22115     *
22116     * @see #setNestedScrollingEnabled(boolean)
22117     */
22118    public boolean isNestedScrollingEnabled() {
22119        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
22120                PFLAG3_NESTED_SCROLLING_ENABLED;
22121    }
22122
22123    /**
22124     * Begin a nestable scroll operation along the given axes.
22125     *
22126     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
22127     *
22128     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
22129     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
22130     * In the case of touch scrolling the nested scroll will be terminated automatically in
22131     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
22132     * In the event of programmatic scrolling the caller must explicitly call
22133     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
22134     *
22135     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
22136     * If it returns false the caller may ignore the rest of this contract until the next scroll.
22137     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
22138     *
22139     * <p>At each incremental step of the scroll the caller should invoke
22140     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
22141     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
22142     * parent at least partially consumed the scroll and the caller should adjust the amount it
22143     * scrolls by.</p>
22144     *
22145     * <p>After applying the remainder of the scroll delta the caller should invoke
22146     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
22147     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
22148     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
22149     * </p>
22150     *
22151     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
22152     *             {@link #SCROLL_AXIS_VERTICAL}.
22153     * @return true if a cooperative parent was found and nested scrolling has been enabled for
22154     *         the current gesture.
22155     *
22156     * @see #stopNestedScroll()
22157     * @see #dispatchNestedPreScroll(int, int, int[], int[])
22158     * @see #dispatchNestedScroll(int, int, int, int, int[])
22159     */
22160    public boolean startNestedScroll(int axes) {
22161        if (hasNestedScrollingParent()) {
22162            // Already in progress
22163            return true;
22164        }
22165        if (isNestedScrollingEnabled()) {
22166            ViewParent p = getParent();
22167            View child = this;
22168            while (p != null) {
22169                try {
22170                    if (p.onStartNestedScroll(child, this, axes)) {
22171                        mNestedScrollingParent = p;
22172                        p.onNestedScrollAccepted(child, this, axes);
22173                        return true;
22174                    }
22175                } catch (AbstractMethodError e) {
22176                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
22177                            "method onStartNestedScroll", e);
22178                    // Allow the search upward to continue
22179                }
22180                if (p instanceof View) {
22181                    child = (View) p;
22182                }
22183                p = p.getParent();
22184            }
22185        }
22186        return false;
22187    }
22188
22189    /**
22190     * Stop a nested scroll in progress.
22191     *
22192     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
22193     *
22194     * @see #startNestedScroll(int)
22195     */
22196    public void stopNestedScroll() {
22197        if (mNestedScrollingParent != null) {
22198            mNestedScrollingParent.onStopNestedScroll(this);
22199            mNestedScrollingParent = null;
22200        }
22201    }
22202
22203    /**
22204     * Returns true if this view has a nested scrolling parent.
22205     *
22206     * <p>The presence of a nested scrolling parent indicates that this view has initiated
22207     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
22208     *
22209     * @return whether this view has a nested scrolling parent
22210     */
22211    public boolean hasNestedScrollingParent() {
22212        return mNestedScrollingParent != null;
22213    }
22214
22215    /**
22216     * Dispatch one step of a nested scroll in progress.
22217     *
22218     * <p>Implementations of views that support nested scrolling should call this to report
22219     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
22220     * is not currently in progress or nested scrolling is not
22221     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
22222     *
22223     * <p>Compatible View implementations should also call
22224     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
22225     * consuming a component of the scroll event themselves.</p>
22226     *
22227     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
22228     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
22229     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
22230     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
22231     * @param offsetInWindow Optional. If not null, on return this will contain the offset
22232     *                       in local view coordinates of this view from before this operation
22233     *                       to after it completes. View implementations may use this to adjust
22234     *                       expected input coordinate tracking.
22235     * @return true if the event was dispatched, false if it could not be dispatched.
22236     * @see #dispatchNestedPreScroll(int, int, int[], int[])
22237     */
22238    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
22239            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
22240        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22241            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
22242                int startX = 0;
22243                int startY = 0;
22244                if (offsetInWindow != null) {
22245                    getLocationInWindow(offsetInWindow);
22246                    startX = offsetInWindow[0];
22247                    startY = offsetInWindow[1];
22248                }
22249
22250                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
22251                        dxUnconsumed, dyUnconsumed);
22252
22253                if (offsetInWindow != null) {
22254                    getLocationInWindow(offsetInWindow);
22255                    offsetInWindow[0] -= startX;
22256                    offsetInWindow[1] -= startY;
22257                }
22258                return true;
22259            } else if (offsetInWindow != null) {
22260                // No motion, no dispatch. Keep offsetInWindow up to date.
22261                offsetInWindow[0] = 0;
22262                offsetInWindow[1] = 0;
22263            }
22264        }
22265        return false;
22266    }
22267
22268    /**
22269     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
22270     *
22271     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
22272     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
22273     * scrolling operation to consume some or all of the scroll operation before the child view
22274     * consumes it.</p>
22275     *
22276     * @param dx Horizontal scroll distance in pixels
22277     * @param dy Vertical scroll distance in pixels
22278     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
22279     *                 and consumed[1] the consumed dy.
22280     * @param offsetInWindow Optional. If not null, on return this will contain the offset
22281     *                       in local view coordinates of this view from before this operation
22282     *                       to after it completes. View implementations may use this to adjust
22283     *                       expected input coordinate tracking.
22284     * @return true if the parent consumed some or all of the scroll delta
22285     * @see #dispatchNestedScroll(int, int, int, int, int[])
22286     */
22287    public boolean dispatchNestedPreScroll(int dx, int dy,
22288            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
22289        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22290            if (dx != 0 || dy != 0) {
22291                int startX = 0;
22292                int startY = 0;
22293                if (offsetInWindow != null) {
22294                    getLocationInWindow(offsetInWindow);
22295                    startX = offsetInWindow[0];
22296                    startY = offsetInWindow[1];
22297                }
22298
22299                if (consumed == null) {
22300                    if (mTempNestedScrollConsumed == null) {
22301                        mTempNestedScrollConsumed = new int[2];
22302                    }
22303                    consumed = mTempNestedScrollConsumed;
22304                }
22305                consumed[0] = 0;
22306                consumed[1] = 0;
22307                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
22308
22309                if (offsetInWindow != null) {
22310                    getLocationInWindow(offsetInWindow);
22311                    offsetInWindow[0] -= startX;
22312                    offsetInWindow[1] -= startY;
22313                }
22314                return consumed[0] != 0 || consumed[1] != 0;
22315            } else if (offsetInWindow != null) {
22316                offsetInWindow[0] = 0;
22317                offsetInWindow[1] = 0;
22318            }
22319        }
22320        return false;
22321    }
22322
22323    /**
22324     * Dispatch a fling to a nested scrolling parent.
22325     *
22326     * <p>This method should be used to indicate that a nested scrolling child has detected
22327     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
22328     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
22329     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
22330     * along a scrollable axis.</p>
22331     *
22332     * <p>If a nested scrolling child view would normally fling but it is at the edge of
22333     * its own content, it can use this method to delegate the fling to its nested scrolling
22334     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
22335     *
22336     * @param velocityX Horizontal fling velocity in pixels per second
22337     * @param velocityY Vertical fling velocity in pixels per second
22338     * @param consumed true if the child consumed the fling, false otherwise
22339     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
22340     */
22341    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
22342        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22343            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
22344        }
22345        return false;
22346    }
22347
22348    /**
22349     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
22350     *
22351     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
22352     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
22353     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
22354     * before the child view consumes it. If this method returns <code>true</code>, a nested
22355     * parent view consumed the fling and this view should not scroll as a result.</p>
22356     *
22357     * <p>For a better user experience, only one view in a nested scrolling chain should consume
22358     * the fling at a time. If a parent view consumed the fling this method will return false.
22359     * Custom view implementations should account for this in two ways:</p>
22360     *
22361     * <ul>
22362     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
22363     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
22364     *     position regardless.</li>
22365     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
22366     *     even to settle back to a valid idle position.</li>
22367     * </ul>
22368     *
22369     * <p>Views should also not offer fling velocities to nested parent views along an axis
22370     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
22371     * should not offer a horizontal fling velocity to its parents since scrolling along that
22372     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
22373     *
22374     * @param velocityX Horizontal fling velocity in pixels per second
22375     * @param velocityY Vertical fling velocity in pixels per second
22376     * @return true if a nested scrolling parent consumed the fling
22377     */
22378    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
22379        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22380            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
22381        }
22382        return false;
22383    }
22384
22385    /**
22386     * Gets a scale factor that determines the distance the view should scroll
22387     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
22388     * @return The vertical scroll scale factor.
22389     * @hide
22390     */
22391    protected float getVerticalScrollFactor() {
22392        if (mVerticalScrollFactor == 0) {
22393            TypedValue outValue = new TypedValue();
22394            if (!mContext.getTheme().resolveAttribute(
22395                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
22396                throw new IllegalStateException(
22397                        "Expected theme to define listPreferredItemHeight.");
22398            }
22399            mVerticalScrollFactor = outValue.getDimension(
22400                    mContext.getResources().getDisplayMetrics());
22401        }
22402        return mVerticalScrollFactor;
22403    }
22404
22405    /**
22406     * Gets a scale factor that determines the distance the view should scroll
22407     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
22408     * @return The horizontal scroll scale factor.
22409     * @hide
22410     */
22411    protected float getHorizontalScrollFactor() {
22412        // TODO: Should use something else.
22413        return getVerticalScrollFactor();
22414    }
22415
22416    /**
22417     * Return the value specifying the text direction or policy that was set with
22418     * {@link #setTextDirection(int)}.
22419     *
22420     * @return the defined text direction. It can be one of:
22421     *
22422     * {@link #TEXT_DIRECTION_INHERIT},
22423     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22424     * {@link #TEXT_DIRECTION_ANY_RTL},
22425     * {@link #TEXT_DIRECTION_LTR},
22426     * {@link #TEXT_DIRECTION_RTL},
22427     * {@link #TEXT_DIRECTION_LOCALE},
22428     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22429     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22430     *
22431     * @attr ref android.R.styleable#View_textDirection
22432     *
22433     * @hide
22434     */
22435    @ViewDebug.ExportedProperty(category = "text", mapping = {
22436            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22437            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22438            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22439            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22440            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22441            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22442            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22443            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22444    })
22445    public int getRawTextDirection() {
22446        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
22447    }
22448
22449    /**
22450     * Set the text direction.
22451     *
22452     * @param textDirection the direction to set. Should be one of:
22453     *
22454     * {@link #TEXT_DIRECTION_INHERIT},
22455     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22456     * {@link #TEXT_DIRECTION_ANY_RTL},
22457     * {@link #TEXT_DIRECTION_LTR},
22458     * {@link #TEXT_DIRECTION_RTL},
22459     * {@link #TEXT_DIRECTION_LOCALE}
22460     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22461     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
22462     *
22463     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
22464     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
22465     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
22466     *
22467     * @attr ref android.R.styleable#View_textDirection
22468     */
22469    public void setTextDirection(int textDirection) {
22470        if (getRawTextDirection() != textDirection) {
22471            // Reset the current text direction and the resolved one
22472            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
22473            resetResolvedTextDirection();
22474            // Set the new text direction
22475            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
22476            // Do resolution
22477            resolveTextDirection();
22478            // Notify change
22479            onRtlPropertiesChanged(getLayoutDirection());
22480            // Refresh
22481            requestLayout();
22482            invalidate(true);
22483        }
22484    }
22485
22486    /**
22487     * Return the resolved text direction.
22488     *
22489     * @return the resolved text direction. Returns one of:
22490     *
22491     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22492     * {@link #TEXT_DIRECTION_ANY_RTL},
22493     * {@link #TEXT_DIRECTION_LTR},
22494     * {@link #TEXT_DIRECTION_RTL},
22495     * {@link #TEXT_DIRECTION_LOCALE},
22496     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22497     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22498     *
22499     * @attr ref android.R.styleable#View_textDirection
22500     */
22501    @ViewDebug.ExportedProperty(category = "text", mapping = {
22502            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22503            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22504            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22505            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22506            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22507            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22508            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22509            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22510    })
22511    public int getTextDirection() {
22512        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
22513    }
22514
22515    /**
22516     * Resolve the text direction.
22517     *
22518     * @return true if resolution has been done, false otherwise.
22519     *
22520     * @hide
22521     */
22522    public boolean resolveTextDirection() {
22523        // Reset any previous text direction resolution
22524        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22525
22526        if (hasRtlSupport()) {
22527            // Set resolved text direction flag depending on text direction flag
22528            final int textDirection = getRawTextDirection();
22529            switch(textDirection) {
22530                case TEXT_DIRECTION_INHERIT:
22531                    if (!canResolveTextDirection()) {
22532                        // We cannot do the resolution if there is no parent, so use the default one
22533                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22534                        // Resolution will need to happen again later
22535                        return false;
22536                    }
22537
22538                    // Parent has not yet resolved, so we still return the default
22539                    try {
22540                        if (!mParent.isTextDirectionResolved()) {
22541                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22542                            // Resolution will need to happen again later
22543                            return false;
22544                        }
22545                    } catch (AbstractMethodError e) {
22546                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22547                                " does not fully implement ViewParent", e);
22548                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
22549                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22550                        return true;
22551                    }
22552
22553                    // Set current resolved direction to the same value as the parent's one
22554                    int parentResolvedDirection;
22555                    try {
22556                        parentResolvedDirection = mParent.getTextDirection();
22557                    } catch (AbstractMethodError e) {
22558                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22559                                " does not fully implement ViewParent", e);
22560                        parentResolvedDirection = TEXT_DIRECTION_LTR;
22561                    }
22562                    switch (parentResolvedDirection) {
22563                        case TEXT_DIRECTION_FIRST_STRONG:
22564                        case TEXT_DIRECTION_ANY_RTL:
22565                        case TEXT_DIRECTION_LTR:
22566                        case TEXT_DIRECTION_RTL:
22567                        case TEXT_DIRECTION_LOCALE:
22568                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
22569                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
22570                            mPrivateFlags2 |=
22571                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22572                            break;
22573                        default:
22574                            // Default resolved direction is "first strong" heuristic
22575                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22576                    }
22577                    break;
22578                case TEXT_DIRECTION_FIRST_STRONG:
22579                case TEXT_DIRECTION_ANY_RTL:
22580                case TEXT_DIRECTION_LTR:
22581                case TEXT_DIRECTION_RTL:
22582                case TEXT_DIRECTION_LOCALE:
22583                case TEXT_DIRECTION_FIRST_STRONG_LTR:
22584                case TEXT_DIRECTION_FIRST_STRONG_RTL:
22585                    // Resolved direction is the same as text direction
22586                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22587                    break;
22588                default:
22589                    // Default resolved direction is "first strong" heuristic
22590                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22591            }
22592        } else {
22593            // Default resolved direction is "first strong" heuristic
22594            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22595        }
22596
22597        // Set to resolved
22598        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
22599        return true;
22600    }
22601
22602    /**
22603     * Check if text direction resolution can be done.
22604     *
22605     * @return true if text direction resolution can be done otherwise return false.
22606     */
22607    public boolean canResolveTextDirection() {
22608        switch (getRawTextDirection()) {
22609            case TEXT_DIRECTION_INHERIT:
22610                if (mParent != null) {
22611                    try {
22612                        return mParent.canResolveTextDirection();
22613                    } catch (AbstractMethodError e) {
22614                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22615                                " does not fully implement ViewParent", e);
22616                    }
22617                }
22618                return false;
22619
22620            default:
22621                return true;
22622        }
22623    }
22624
22625    /**
22626     * Reset resolved text direction. Text direction will be resolved during a call to
22627     * {@link #onMeasure(int, int)}.
22628     *
22629     * @hide
22630     */
22631    public void resetResolvedTextDirection() {
22632        // Reset any previous text direction resolution
22633        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22634        // Set to default value
22635        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22636    }
22637
22638    /**
22639     * @return true if text direction is inherited.
22640     *
22641     * @hide
22642     */
22643    public boolean isTextDirectionInherited() {
22644        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
22645    }
22646
22647    /**
22648     * @return true if text direction is resolved.
22649     */
22650    public boolean isTextDirectionResolved() {
22651        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
22652    }
22653
22654    /**
22655     * Return the value specifying the text alignment or policy that was set with
22656     * {@link #setTextAlignment(int)}.
22657     *
22658     * @return the defined text alignment. It can be one of:
22659     *
22660     * {@link #TEXT_ALIGNMENT_INHERIT},
22661     * {@link #TEXT_ALIGNMENT_GRAVITY},
22662     * {@link #TEXT_ALIGNMENT_CENTER},
22663     * {@link #TEXT_ALIGNMENT_TEXT_START},
22664     * {@link #TEXT_ALIGNMENT_TEXT_END},
22665     * {@link #TEXT_ALIGNMENT_VIEW_START},
22666     * {@link #TEXT_ALIGNMENT_VIEW_END}
22667     *
22668     * @attr ref android.R.styleable#View_textAlignment
22669     *
22670     * @hide
22671     */
22672    @ViewDebug.ExportedProperty(category = "text", mapping = {
22673            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22674            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22675            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22676            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22677            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22678            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22679            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22680    })
22681    @TextAlignment
22682    public int getRawTextAlignment() {
22683        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
22684    }
22685
22686    /**
22687     * Set the text alignment.
22688     *
22689     * @param textAlignment The text alignment to set. Should be one of
22690     *
22691     * {@link #TEXT_ALIGNMENT_INHERIT},
22692     * {@link #TEXT_ALIGNMENT_GRAVITY},
22693     * {@link #TEXT_ALIGNMENT_CENTER},
22694     * {@link #TEXT_ALIGNMENT_TEXT_START},
22695     * {@link #TEXT_ALIGNMENT_TEXT_END},
22696     * {@link #TEXT_ALIGNMENT_VIEW_START},
22697     * {@link #TEXT_ALIGNMENT_VIEW_END}
22698     *
22699     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
22700     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
22701     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
22702     *
22703     * @attr ref android.R.styleable#View_textAlignment
22704     */
22705    public void setTextAlignment(@TextAlignment int textAlignment) {
22706        if (textAlignment != getRawTextAlignment()) {
22707            // Reset the current and resolved text alignment
22708            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
22709            resetResolvedTextAlignment();
22710            // Set the new text alignment
22711            mPrivateFlags2 |=
22712                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
22713            // Do resolution
22714            resolveTextAlignment();
22715            // Notify change
22716            onRtlPropertiesChanged(getLayoutDirection());
22717            // Refresh
22718            requestLayout();
22719            invalidate(true);
22720        }
22721    }
22722
22723    /**
22724     * Return the resolved text alignment.
22725     *
22726     * @return the resolved text alignment. Returns one of:
22727     *
22728     * {@link #TEXT_ALIGNMENT_GRAVITY},
22729     * {@link #TEXT_ALIGNMENT_CENTER},
22730     * {@link #TEXT_ALIGNMENT_TEXT_START},
22731     * {@link #TEXT_ALIGNMENT_TEXT_END},
22732     * {@link #TEXT_ALIGNMENT_VIEW_START},
22733     * {@link #TEXT_ALIGNMENT_VIEW_END}
22734     *
22735     * @attr ref android.R.styleable#View_textAlignment
22736     */
22737    @ViewDebug.ExportedProperty(category = "text", mapping = {
22738            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22739            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22740            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22741            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22742            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22743            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22744            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22745    })
22746    @TextAlignment
22747    public int getTextAlignment() {
22748        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
22749                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
22750    }
22751
22752    /**
22753     * Resolve the text alignment.
22754     *
22755     * @return true if resolution has been done, false otherwise.
22756     *
22757     * @hide
22758     */
22759    public boolean resolveTextAlignment() {
22760        // Reset any previous text alignment resolution
22761        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22762
22763        if (hasRtlSupport()) {
22764            // Set resolved text alignment flag depending on text alignment flag
22765            final int textAlignment = getRawTextAlignment();
22766            switch (textAlignment) {
22767                case TEXT_ALIGNMENT_INHERIT:
22768                    // Check if we can resolve the text alignment
22769                    if (!canResolveTextAlignment()) {
22770                        // We cannot do the resolution if there is no parent so use the default
22771                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22772                        // Resolution will need to happen again later
22773                        return false;
22774                    }
22775
22776                    // Parent has not yet resolved, so we still return the default
22777                    try {
22778                        if (!mParent.isTextAlignmentResolved()) {
22779                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22780                            // Resolution will need to happen again later
22781                            return false;
22782                        }
22783                    } catch (AbstractMethodError e) {
22784                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22785                                " does not fully implement ViewParent", e);
22786                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
22787                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22788                        return true;
22789                    }
22790
22791                    int parentResolvedTextAlignment;
22792                    try {
22793                        parentResolvedTextAlignment = mParent.getTextAlignment();
22794                    } catch (AbstractMethodError e) {
22795                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22796                                " does not fully implement ViewParent", e);
22797                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
22798                    }
22799                    switch (parentResolvedTextAlignment) {
22800                        case TEXT_ALIGNMENT_GRAVITY:
22801                        case TEXT_ALIGNMENT_TEXT_START:
22802                        case TEXT_ALIGNMENT_TEXT_END:
22803                        case TEXT_ALIGNMENT_CENTER:
22804                        case TEXT_ALIGNMENT_VIEW_START:
22805                        case TEXT_ALIGNMENT_VIEW_END:
22806                            // Resolved text alignment is the same as the parent resolved
22807                            // text alignment
22808                            mPrivateFlags2 |=
22809                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22810                            break;
22811                        default:
22812                            // Use default resolved text alignment
22813                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22814                    }
22815                    break;
22816                case TEXT_ALIGNMENT_GRAVITY:
22817                case TEXT_ALIGNMENT_TEXT_START:
22818                case TEXT_ALIGNMENT_TEXT_END:
22819                case TEXT_ALIGNMENT_CENTER:
22820                case TEXT_ALIGNMENT_VIEW_START:
22821                case TEXT_ALIGNMENT_VIEW_END:
22822                    // Resolved text alignment is the same as text alignment
22823                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22824                    break;
22825                default:
22826                    // Use default resolved text alignment
22827                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22828            }
22829        } else {
22830            // Use default resolved text alignment
22831            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22832        }
22833
22834        // Set the resolved
22835        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22836        return true;
22837    }
22838
22839    /**
22840     * Check if text alignment resolution can be done.
22841     *
22842     * @return true if text alignment resolution can be done otherwise return false.
22843     */
22844    public boolean canResolveTextAlignment() {
22845        switch (getRawTextAlignment()) {
22846            case TEXT_DIRECTION_INHERIT:
22847                if (mParent != null) {
22848                    try {
22849                        return mParent.canResolveTextAlignment();
22850                    } catch (AbstractMethodError e) {
22851                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22852                                " does not fully implement ViewParent", e);
22853                    }
22854                }
22855                return false;
22856
22857            default:
22858                return true;
22859        }
22860    }
22861
22862    /**
22863     * Reset resolved text alignment. Text alignment will be resolved during a call to
22864     * {@link #onMeasure(int, int)}.
22865     *
22866     * @hide
22867     */
22868    public void resetResolvedTextAlignment() {
22869        // Reset any previous text alignment resolution
22870        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22871        // Set to default
22872        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22873    }
22874
22875    /**
22876     * @return true if text alignment is inherited.
22877     *
22878     * @hide
22879     */
22880    public boolean isTextAlignmentInherited() {
22881        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
22882    }
22883
22884    /**
22885     * @return true if text alignment is resolved.
22886     */
22887    public boolean isTextAlignmentResolved() {
22888        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22889    }
22890
22891    /**
22892     * Generate a value suitable for use in {@link #setId(int)}.
22893     * This value will not collide with ID values generated at build time by aapt for R.id.
22894     *
22895     * @return a generated ID value
22896     */
22897    public static int generateViewId() {
22898        for (;;) {
22899            final int result = sNextGeneratedId.get();
22900            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
22901            int newValue = result + 1;
22902            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
22903            if (sNextGeneratedId.compareAndSet(result, newValue)) {
22904                return result;
22905            }
22906        }
22907    }
22908
22909    private static boolean isViewIdGenerated(int id) {
22910        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
22911    }
22912
22913    /**
22914     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
22915     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
22916     *                           a normal View or a ViewGroup with
22917     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
22918     * @hide
22919     */
22920    public void captureTransitioningViews(List<View> transitioningViews) {
22921        if (getVisibility() == View.VISIBLE) {
22922            transitioningViews.add(this);
22923        }
22924    }
22925
22926    /**
22927     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
22928     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
22929     * @hide
22930     */
22931    public void findNamedViews(Map<String, View> namedElements) {
22932        if (getVisibility() == VISIBLE || mGhostView != null) {
22933            String transitionName = getTransitionName();
22934            if (transitionName != null) {
22935                namedElements.put(transitionName, this);
22936            }
22937        }
22938    }
22939
22940    /**
22941     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
22942     * The default implementation does not care the location or event types, but some subclasses
22943     * may use it (such as WebViews).
22944     * @param event The MotionEvent from a mouse
22945     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
22946     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
22947     * @see PointerIcon
22948     */
22949    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
22950        final float x = event.getX(pointerIndex);
22951        final float y = event.getY(pointerIndex);
22952        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
22953            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
22954        }
22955        return mPointerIcon;
22956    }
22957
22958    /**
22959     * Set the pointer icon for the current view.
22960     * Passing {@code null} will restore the pointer icon to its default value.
22961     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
22962     */
22963    public void setPointerIcon(PointerIcon pointerIcon) {
22964        mPointerIcon = pointerIcon;
22965        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
22966            return;
22967        }
22968        try {
22969            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
22970        } catch (RemoteException e) {
22971        }
22972    }
22973
22974    /**
22975     * Gets the pointer icon for the current view.
22976     */
22977    public PointerIcon getPointerIcon() {
22978        return mPointerIcon;
22979    }
22980
22981    /**
22982     * Checks pointer capture status.
22983     *
22984     * @return true if the view has pointer capture.
22985     * @see #requestPointerCapture()
22986     * @see #hasPointerCapture()
22987     */
22988    public boolean hasPointerCapture() {
22989        final ViewRootImpl viewRootImpl = getViewRootImpl();
22990        if (viewRootImpl == null) {
22991            return false;
22992        }
22993        return viewRootImpl.hasPointerCapture();
22994    }
22995
22996    /**
22997     * Requests pointer capture mode.
22998     * <p>
22999     * When the window has pointer capture, the mouse pointer icon will disappear and will not
23000     * change its position. Further mouse will be dispatched with the source
23001     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
23002     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
23003     * (touchscreens, or stylus) will not be affected.
23004     * <p>
23005     * If the window already has pointer capture, this call does nothing.
23006     * <p>
23007     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
23008     * automatically when the window loses focus.
23009     *
23010     * @see #releasePointerCapture()
23011     * @see #hasPointerCapture()
23012     */
23013    public void requestPointerCapture() {
23014        final ViewRootImpl viewRootImpl = getViewRootImpl();
23015        if (viewRootImpl != null) {
23016            viewRootImpl.requestPointerCapture(true);
23017        }
23018    }
23019
23020
23021    /**
23022     * Releases the pointer capture.
23023     * <p>
23024     * If the window does not have pointer capture, this call will do nothing.
23025     * @see #requestPointerCapture()
23026     * @see #hasPointerCapture()
23027     */
23028    public void releasePointerCapture() {
23029        final ViewRootImpl viewRootImpl = getViewRootImpl();
23030        if (viewRootImpl != null) {
23031            viewRootImpl.requestPointerCapture(false);
23032        }
23033    }
23034
23035    /**
23036     * Called when the window has just acquired or lost pointer capture.
23037     *
23038     * @param hasCapture True if the view now has pointerCapture, false otherwise.
23039     */
23040    @CallSuper
23041    public void onPointerCaptureChange(boolean hasCapture) {
23042    }
23043
23044    /**
23045     * @see #onPointerCaptureChange
23046     */
23047    public void dispatchPointerCaptureChanged(boolean hasCapture) {
23048        onPointerCaptureChange(hasCapture);
23049    }
23050
23051    /**
23052     * Implement this method to handle captured pointer events
23053     *
23054     * @param event The captured pointer event.
23055     * @return True if the event was handled, false otherwise.
23056     * @see #requestPointerCapture()
23057     */
23058    public boolean onCapturedPointerEvent(MotionEvent event) {
23059        return false;
23060    }
23061
23062    /**
23063     * Interface definition for a callback to be invoked when a captured pointer event
23064     * is being dispatched this view. The callback will be invoked before the event is
23065     * given to the view.
23066     */
23067    public interface OnCapturedPointerListener {
23068        /**
23069         * Called when a captured pointer event is dispatched to a view.
23070         * @param view The view this event has been dispatched to.
23071         * @param event The captured event.
23072         * @return True if the listener has consumed the event, false otherwise.
23073         */
23074        boolean onCapturedPointer(View view, MotionEvent event);
23075    }
23076
23077    /**
23078     * Set a listener to receive callbacks when the pointer capture state of a view changes.
23079     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
23080     */
23081    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
23082        getListenerInfo().mOnCapturedPointerListener = l;
23083    }
23084
23085    // Properties
23086    //
23087    /**
23088     * A Property wrapper around the <code>alpha</code> functionality handled by the
23089     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
23090     */
23091    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
23092        @Override
23093        public void setValue(View object, float value) {
23094            object.setAlpha(value);
23095        }
23096
23097        @Override
23098        public Float get(View object) {
23099            return object.getAlpha();
23100        }
23101    };
23102
23103    /**
23104     * A Property wrapper around the <code>translationX</code> functionality handled by the
23105     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
23106     */
23107    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
23108        @Override
23109        public void setValue(View object, float value) {
23110            object.setTranslationX(value);
23111        }
23112
23113                @Override
23114        public Float get(View object) {
23115            return object.getTranslationX();
23116        }
23117    };
23118
23119    /**
23120     * A Property wrapper around the <code>translationY</code> functionality handled by the
23121     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
23122     */
23123    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
23124        @Override
23125        public void setValue(View object, float value) {
23126            object.setTranslationY(value);
23127        }
23128
23129        @Override
23130        public Float get(View object) {
23131            return object.getTranslationY();
23132        }
23133    };
23134
23135    /**
23136     * A Property wrapper around the <code>translationZ</code> functionality handled by the
23137     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
23138     */
23139    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
23140        @Override
23141        public void setValue(View object, float value) {
23142            object.setTranslationZ(value);
23143        }
23144
23145        @Override
23146        public Float get(View object) {
23147            return object.getTranslationZ();
23148        }
23149    };
23150
23151    /**
23152     * A Property wrapper around the <code>x</code> functionality handled by the
23153     * {@link View#setX(float)} and {@link View#getX()} methods.
23154     */
23155    public static final Property<View, Float> X = new FloatProperty<View>("x") {
23156        @Override
23157        public void setValue(View object, float value) {
23158            object.setX(value);
23159        }
23160
23161        @Override
23162        public Float get(View object) {
23163            return object.getX();
23164        }
23165    };
23166
23167    /**
23168     * A Property wrapper around the <code>y</code> functionality handled by the
23169     * {@link View#setY(float)} and {@link View#getY()} methods.
23170     */
23171    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
23172        @Override
23173        public void setValue(View object, float value) {
23174            object.setY(value);
23175        }
23176
23177        @Override
23178        public Float get(View object) {
23179            return object.getY();
23180        }
23181    };
23182
23183    /**
23184     * A Property wrapper around the <code>z</code> functionality handled by the
23185     * {@link View#setZ(float)} and {@link View#getZ()} methods.
23186     */
23187    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
23188        @Override
23189        public void setValue(View object, float value) {
23190            object.setZ(value);
23191        }
23192
23193        @Override
23194        public Float get(View object) {
23195            return object.getZ();
23196        }
23197    };
23198
23199    /**
23200     * A Property wrapper around the <code>rotation</code> functionality handled by the
23201     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
23202     */
23203    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
23204        @Override
23205        public void setValue(View object, float value) {
23206            object.setRotation(value);
23207        }
23208
23209        @Override
23210        public Float get(View object) {
23211            return object.getRotation();
23212        }
23213    };
23214
23215    /**
23216     * A Property wrapper around the <code>rotationX</code> functionality handled by the
23217     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
23218     */
23219    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
23220        @Override
23221        public void setValue(View object, float value) {
23222            object.setRotationX(value);
23223        }
23224
23225        @Override
23226        public Float get(View object) {
23227            return object.getRotationX();
23228        }
23229    };
23230
23231    /**
23232     * A Property wrapper around the <code>rotationY</code> functionality handled by the
23233     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
23234     */
23235    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
23236        @Override
23237        public void setValue(View object, float value) {
23238            object.setRotationY(value);
23239        }
23240
23241        @Override
23242        public Float get(View object) {
23243            return object.getRotationY();
23244        }
23245    };
23246
23247    /**
23248     * A Property wrapper around the <code>scaleX</code> functionality handled by the
23249     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
23250     */
23251    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
23252        @Override
23253        public void setValue(View object, float value) {
23254            object.setScaleX(value);
23255        }
23256
23257        @Override
23258        public Float get(View object) {
23259            return object.getScaleX();
23260        }
23261    };
23262
23263    /**
23264     * A Property wrapper around the <code>scaleY</code> functionality handled by the
23265     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
23266     */
23267    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
23268        @Override
23269        public void setValue(View object, float value) {
23270            object.setScaleY(value);
23271        }
23272
23273        @Override
23274        public Float get(View object) {
23275            return object.getScaleY();
23276        }
23277    };
23278
23279    /**
23280     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
23281     * Each MeasureSpec represents a requirement for either the width or the height.
23282     * A MeasureSpec is comprised of a size and a mode. There are three possible
23283     * modes:
23284     * <dl>
23285     * <dt>UNSPECIFIED</dt>
23286     * <dd>
23287     * The parent has not imposed any constraint on the child. It can be whatever size
23288     * it wants.
23289     * </dd>
23290     *
23291     * <dt>EXACTLY</dt>
23292     * <dd>
23293     * The parent has determined an exact size for the child. The child is going to be
23294     * given those bounds regardless of how big it wants to be.
23295     * </dd>
23296     *
23297     * <dt>AT_MOST</dt>
23298     * <dd>
23299     * The child can be as large as it wants up to the specified size.
23300     * </dd>
23301     * </dl>
23302     *
23303     * MeasureSpecs are implemented as ints to reduce object allocation. This class
23304     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
23305     */
23306    public static class MeasureSpec {
23307        private static final int MODE_SHIFT = 30;
23308        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
23309
23310        /** @hide */
23311        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
23312        @Retention(RetentionPolicy.SOURCE)
23313        public @interface MeasureSpecMode {}
23314
23315        /**
23316         * Measure specification mode: The parent has not imposed any constraint
23317         * on the child. It can be whatever size it wants.
23318         */
23319        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
23320
23321        /**
23322         * Measure specification mode: The parent has determined an exact size
23323         * for the child. The child is going to be given those bounds regardless
23324         * of how big it wants to be.
23325         */
23326        public static final int EXACTLY     = 1 << MODE_SHIFT;
23327
23328        /**
23329         * Measure specification mode: The child can be as large as it wants up
23330         * to the specified size.
23331         */
23332        public static final int AT_MOST     = 2 << MODE_SHIFT;
23333
23334        /**
23335         * Creates a measure specification based on the supplied size and mode.
23336         *
23337         * The mode must always be one of the following:
23338         * <ul>
23339         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
23340         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
23341         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
23342         * </ul>
23343         *
23344         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
23345         * implementation was such that the order of arguments did not matter
23346         * and overflow in either value could impact the resulting MeasureSpec.
23347         * {@link android.widget.RelativeLayout} was affected by this bug.
23348         * Apps targeting API levels greater than 17 will get the fixed, more strict
23349         * behavior.</p>
23350         *
23351         * @param size the size of the measure specification
23352         * @param mode the mode of the measure specification
23353         * @return the measure specification based on size and mode
23354         */
23355        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
23356                                          @MeasureSpecMode int mode) {
23357            if (sUseBrokenMakeMeasureSpec) {
23358                return size + mode;
23359            } else {
23360                return (size & ~MODE_MASK) | (mode & MODE_MASK);
23361            }
23362        }
23363
23364        /**
23365         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
23366         * will automatically get a size of 0. Older apps expect this.
23367         *
23368         * @hide internal use only for compatibility with system widgets and older apps
23369         */
23370        public static int makeSafeMeasureSpec(int size, int mode) {
23371            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
23372                return 0;
23373            }
23374            return makeMeasureSpec(size, mode);
23375        }
23376
23377        /**
23378         * Extracts the mode from the supplied measure specification.
23379         *
23380         * @param measureSpec the measure specification to extract the mode from
23381         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
23382         *         {@link android.view.View.MeasureSpec#AT_MOST} or
23383         *         {@link android.view.View.MeasureSpec#EXACTLY}
23384         */
23385        @MeasureSpecMode
23386        public static int getMode(int measureSpec) {
23387            //noinspection ResourceType
23388            return (measureSpec & MODE_MASK);
23389        }
23390
23391        /**
23392         * Extracts the size from the supplied measure specification.
23393         *
23394         * @param measureSpec the measure specification to extract the size from
23395         * @return the size in pixels defined in the supplied measure specification
23396         */
23397        public static int getSize(int measureSpec) {
23398            return (measureSpec & ~MODE_MASK);
23399        }
23400
23401        static int adjust(int measureSpec, int delta) {
23402            final int mode = getMode(measureSpec);
23403            int size = getSize(measureSpec);
23404            if (mode == UNSPECIFIED) {
23405                // No need to adjust size for UNSPECIFIED mode.
23406                return makeMeasureSpec(size, UNSPECIFIED);
23407            }
23408            size += delta;
23409            if (size < 0) {
23410                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
23411                        ") spec: " + toString(measureSpec) + " delta: " + delta);
23412                size = 0;
23413            }
23414            return makeMeasureSpec(size, mode);
23415        }
23416
23417        /**
23418         * Returns a String representation of the specified measure
23419         * specification.
23420         *
23421         * @param measureSpec the measure specification to convert to a String
23422         * @return a String with the following format: "MeasureSpec: MODE SIZE"
23423         */
23424        public static String toString(int measureSpec) {
23425            int mode = getMode(measureSpec);
23426            int size = getSize(measureSpec);
23427
23428            StringBuilder sb = new StringBuilder("MeasureSpec: ");
23429
23430            if (mode == UNSPECIFIED)
23431                sb.append("UNSPECIFIED ");
23432            else if (mode == EXACTLY)
23433                sb.append("EXACTLY ");
23434            else if (mode == AT_MOST)
23435                sb.append("AT_MOST ");
23436            else
23437                sb.append(mode).append(" ");
23438
23439            sb.append(size);
23440            return sb.toString();
23441        }
23442    }
23443
23444    private final class CheckForLongPress implements Runnable {
23445        private int mOriginalWindowAttachCount;
23446        private float mX;
23447        private float mY;
23448        private boolean mOriginalPressedState;
23449
23450        @Override
23451        public void run() {
23452            if ((mOriginalPressedState == isPressed()) && (mParent != null)
23453                    && mOriginalWindowAttachCount == mWindowAttachCount) {
23454                if (performLongClick(mX, mY)) {
23455                    mHasPerformedLongPress = true;
23456                }
23457            }
23458        }
23459
23460        public void setAnchor(float x, float y) {
23461            mX = x;
23462            mY = y;
23463        }
23464
23465        public void rememberWindowAttachCount() {
23466            mOriginalWindowAttachCount = mWindowAttachCount;
23467        }
23468
23469        public void rememberPressedState() {
23470            mOriginalPressedState = isPressed();
23471        }
23472    }
23473
23474    private final class CheckForTap implements Runnable {
23475        public float x;
23476        public float y;
23477
23478        @Override
23479        public void run() {
23480            mPrivateFlags &= ~PFLAG_PREPRESSED;
23481            setPressed(true, x, y);
23482            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
23483        }
23484    }
23485
23486    private final class PerformClick implements Runnable {
23487        @Override
23488        public void run() {
23489            performClick();
23490        }
23491    }
23492
23493    /**
23494     * This method returns a ViewPropertyAnimator object, which can be used to animate
23495     * specific properties on this View.
23496     *
23497     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
23498     */
23499    public ViewPropertyAnimator animate() {
23500        if (mAnimator == null) {
23501            mAnimator = new ViewPropertyAnimator(this);
23502        }
23503        return mAnimator;
23504    }
23505
23506    /**
23507     * Sets the name of the View to be used to identify Views in Transitions.
23508     * Names should be unique in the View hierarchy.
23509     *
23510     * @param transitionName The name of the View to uniquely identify it for Transitions.
23511     */
23512    public final void setTransitionName(String transitionName) {
23513        mTransitionName = transitionName;
23514    }
23515
23516    /**
23517     * Returns the name of the View to be used to identify Views in Transitions.
23518     * Names should be unique in the View hierarchy.
23519     *
23520     * <p>This returns null if the View has not been given a name.</p>
23521     *
23522     * @return The name used of the View to be used to identify Views in Transitions or null
23523     * if no name has been given.
23524     */
23525    @ViewDebug.ExportedProperty
23526    public String getTransitionName() {
23527        return mTransitionName;
23528    }
23529
23530    /**
23531     * @hide
23532     */
23533    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
23534        // Do nothing.
23535    }
23536
23537    /**
23538     * Interface definition for a callback to be invoked when a hardware key event is
23539     * dispatched to this view. The callback will be invoked before the key event is
23540     * given to the view. This is only useful for hardware keyboards; a software input
23541     * method has no obligation to trigger this listener.
23542     */
23543    public interface OnKeyListener {
23544        /**
23545         * Called when a hardware key is dispatched to a view. This allows listeners to
23546         * get a chance to respond before the target view.
23547         * <p>Key presses in software keyboards will generally NOT trigger this method,
23548         * although some may elect to do so in some situations. Do not assume a
23549         * software input method has to be key-based; even if it is, it may use key presses
23550         * in a different way than you expect, so there is no way to reliably catch soft
23551         * input key presses.
23552         *
23553         * @param v The view the key has been dispatched to.
23554         * @param keyCode The code for the physical key that was pressed
23555         * @param event The KeyEvent object containing full information about
23556         *        the event.
23557         * @return True if the listener has consumed the event, false otherwise.
23558         */
23559        boolean onKey(View v, int keyCode, KeyEvent event);
23560    }
23561
23562    /**
23563     * Interface definition for a callback to be invoked when a touch event is
23564     * dispatched to this view. The callback will be invoked before the touch
23565     * event is given to the view.
23566     */
23567    public interface OnTouchListener {
23568        /**
23569         * Called when a touch event is dispatched to a view. This allows listeners to
23570         * get a chance to respond before the target view.
23571         *
23572         * @param v The view the touch event has been dispatched to.
23573         * @param event The MotionEvent object containing full information about
23574         *        the event.
23575         * @return True if the listener has consumed the event, false otherwise.
23576         */
23577        boolean onTouch(View v, MotionEvent event);
23578    }
23579
23580    /**
23581     * Interface definition for a callback to be invoked when a hover event is
23582     * dispatched to this view. The callback will be invoked before the hover
23583     * event is given to the view.
23584     */
23585    public interface OnHoverListener {
23586        /**
23587         * Called when a hover event is dispatched to a view. This allows listeners to
23588         * get a chance to respond before the target view.
23589         *
23590         * @param v The view the hover event has been dispatched to.
23591         * @param event The MotionEvent object containing full information about
23592         *        the event.
23593         * @return True if the listener has consumed the event, false otherwise.
23594         */
23595        boolean onHover(View v, MotionEvent event);
23596    }
23597
23598    /**
23599     * Interface definition for a callback to be invoked when a generic motion event is
23600     * dispatched to this view. The callback will be invoked before the generic motion
23601     * event is given to the view.
23602     */
23603    public interface OnGenericMotionListener {
23604        /**
23605         * Called when a generic motion event is dispatched to a view. This allows listeners to
23606         * get a chance to respond before the target view.
23607         *
23608         * @param v The view the generic motion event has been dispatched to.
23609         * @param event The MotionEvent object containing full information about
23610         *        the event.
23611         * @return True if the listener has consumed the event, false otherwise.
23612         */
23613        boolean onGenericMotion(View v, MotionEvent event);
23614    }
23615
23616    /**
23617     * Interface definition for a callback to be invoked when a view has been clicked and held.
23618     */
23619    public interface OnLongClickListener {
23620        /**
23621         * Called when a view has been clicked and held.
23622         *
23623         * @param v The view that was clicked and held.
23624         *
23625         * @return true if the callback consumed the long click, false otherwise.
23626         */
23627        boolean onLongClick(View v);
23628    }
23629
23630    /**
23631     * Interface definition for a callback to be invoked when a drag is being dispatched
23632     * to this view.  The callback will be invoked before the hosting view's own
23633     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
23634     * onDrag(event) behavior, it should return 'false' from this callback.
23635     *
23636     * <div class="special reference">
23637     * <h3>Developer Guides</h3>
23638     * <p>For a guide to implementing drag and drop features, read the
23639     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23640     * </div>
23641     */
23642    public interface OnDragListener {
23643        /**
23644         * Called when a drag event is dispatched to a view. This allows listeners
23645         * to get a chance to override base View behavior.
23646         *
23647         * @param v The View that received the drag event.
23648         * @param event The {@link android.view.DragEvent} object for the drag event.
23649         * @return {@code true} if the drag event was handled successfully, or {@code false}
23650         * if the drag event was not handled. Note that {@code false} will trigger the View
23651         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
23652         */
23653        boolean onDrag(View v, DragEvent event);
23654    }
23655
23656    /**
23657     * Interface definition for a callback to be invoked when the focus state of
23658     * a view changed.
23659     */
23660    public interface OnFocusChangeListener {
23661        /**
23662         * Called when the focus state of a view has changed.
23663         *
23664         * @param v The view whose state has changed.
23665         * @param hasFocus The new focus state of v.
23666         */
23667        void onFocusChange(View v, boolean hasFocus);
23668    }
23669
23670    /**
23671     * Interface definition for a callback to be invoked when a view is clicked.
23672     */
23673    public interface OnClickListener {
23674        /**
23675         * Called when a view has been clicked.
23676         *
23677         * @param v The view that was clicked.
23678         */
23679        void onClick(View v);
23680    }
23681
23682    /**
23683     * Interface definition for a callback to be invoked when a view is context clicked.
23684     */
23685    public interface OnContextClickListener {
23686        /**
23687         * Called when a view is context clicked.
23688         *
23689         * @param v The view that has been context clicked.
23690         * @return true if the callback consumed the context click, false otherwise.
23691         */
23692        boolean onContextClick(View v);
23693    }
23694
23695    /**
23696     * Interface definition for a callback to be invoked when the context menu
23697     * for this view is being built.
23698     */
23699    public interface OnCreateContextMenuListener {
23700        /**
23701         * Called when the context menu for this view is being built. It is not
23702         * safe to hold onto the menu after this method returns.
23703         *
23704         * @param menu The context menu that is being built
23705         * @param v The view for which the context menu is being built
23706         * @param menuInfo Extra information about the item for which the
23707         *            context menu should be shown. This information will vary
23708         *            depending on the class of v.
23709         */
23710        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
23711    }
23712
23713    /**
23714     * Interface definition for a callback to be invoked when the status bar changes
23715     * visibility.  This reports <strong>global</strong> changes to the system UI
23716     * state, not what the application is requesting.
23717     *
23718     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
23719     */
23720    public interface OnSystemUiVisibilityChangeListener {
23721        /**
23722         * Called when the status bar changes visibility because of a call to
23723         * {@link View#setSystemUiVisibility(int)}.
23724         *
23725         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23726         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
23727         * This tells you the <strong>global</strong> state of these UI visibility
23728         * flags, not what your app is currently applying.
23729         */
23730        public void onSystemUiVisibilityChange(int visibility);
23731    }
23732
23733    /**
23734     * Interface definition for a callback to be invoked when this view is attached
23735     * or detached from its window.
23736     */
23737    public interface OnAttachStateChangeListener {
23738        /**
23739         * Called when the view is attached to a window.
23740         * @param v The view that was attached
23741         */
23742        public void onViewAttachedToWindow(View v);
23743        /**
23744         * Called when the view is detached from a window.
23745         * @param v The view that was detached
23746         */
23747        public void onViewDetachedFromWindow(View v);
23748    }
23749
23750    /**
23751     * Listener for applying window insets on a view in a custom way.
23752     *
23753     * <p>Apps may choose to implement this interface if they want to apply custom policy
23754     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
23755     * is set, its
23756     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
23757     * method will be called instead of the View's own
23758     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
23759     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
23760     * the View's normal behavior as part of its own.</p>
23761     */
23762    public interface OnApplyWindowInsetsListener {
23763        /**
23764         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
23765         * on a View, this listener method will be called instead of the view's own
23766         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
23767         *
23768         * @param v The view applying window insets
23769         * @param insets The insets to apply
23770         * @return The insets supplied, minus any insets that were consumed
23771         */
23772        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
23773    }
23774
23775    private final class UnsetPressedState implements Runnable {
23776        @Override
23777        public void run() {
23778            setPressed(false);
23779        }
23780    }
23781
23782    /**
23783     * Base class for derived classes that want to save and restore their own
23784     * state in {@link android.view.View#onSaveInstanceState()}.
23785     */
23786    public static class BaseSavedState extends AbsSavedState {
23787        String mStartActivityRequestWhoSaved;
23788
23789        /**
23790         * Constructor used when reading from a parcel. Reads the state of the superclass.
23791         *
23792         * @param source parcel to read from
23793         */
23794        public BaseSavedState(Parcel source) {
23795            this(source, null);
23796        }
23797
23798        /**
23799         * Constructor used when reading from a parcel using a given class loader.
23800         * Reads the state of the superclass.
23801         *
23802         * @param source parcel to read from
23803         * @param loader ClassLoader to use for reading
23804         */
23805        public BaseSavedState(Parcel source, ClassLoader loader) {
23806            super(source, loader);
23807            mStartActivityRequestWhoSaved = source.readString();
23808        }
23809
23810        /**
23811         * Constructor called by derived classes when creating their SavedState objects
23812         *
23813         * @param superState The state of the superclass of this view
23814         */
23815        public BaseSavedState(Parcelable superState) {
23816            super(superState);
23817        }
23818
23819        @Override
23820        public void writeToParcel(Parcel out, int flags) {
23821            super.writeToParcel(out, flags);
23822            out.writeString(mStartActivityRequestWhoSaved);
23823        }
23824
23825        public static final Parcelable.Creator<BaseSavedState> CREATOR
23826                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
23827            @Override
23828            public BaseSavedState createFromParcel(Parcel in) {
23829                return new BaseSavedState(in);
23830            }
23831
23832            @Override
23833            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
23834                return new BaseSavedState(in, loader);
23835            }
23836
23837            @Override
23838            public BaseSavedState[] newArray(int size) {
23839                return new BaseSavedState[size];
23840            }
23841        };
23842    }
23843
23844    /**
23845     * A set of information given to a view when it is attached to its parent
23846     * window.
23847     */
23848    final static class AttachInfo {
23849        interface Callbacks {
23850            void playSoundEffect(int effectId);
23851            boolean performHapticFeedback(int effectId, boolean always);
23852        }
23853
23854        /**
23855         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
23856         * to a Handler. This class contains the target (View) to invalidate and
23857         * the coordinates of the dirty rectangle.
23858         *
23859         * For performance purposes, this class also implements a pool of up to
23860         * POOL_LIMIT objects that get reused. This reduces memory allocations
23861         * whenever possible.
23862         */
23863        static class InvalidateInfo {
23864            private static final int POOL_LIMIT = 10;
23865
23866            private static final SynchronizedPool<InvalidateInfo> sPool =
23867                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
23868
23869            View target;
23870
23871            int left;
23872            int top;
23873            int right;
23874            int bottom;
23875
23876            public static InvalidateInfo obtain() {
23877                InvalidateInfo instance = sPool.acquire();
23878                return (instance != null) ? instance : new InvalidateInfo();
23879            }
23880
23881            public void recycle() {
23882                target = null;
23883                sPool.release(this);
23884            }
23885        }
23886
23887        final IWindowSession mSession;
23888
23889        final IWindow mWindow;
23890
23891        final IBinder mWindowToken;
23892
23893        Display mDisplay;
23894
23895        final Callbacks mRootCallbacks;
23896
23897        IWindowId mIWindowId;
23898        WindowId mWindowId;
23899
23900        /**
23901         * The top view of the hierarchy.
23902         */
23903        View mRootView;
23904
23905        IBinder mPanelParentWindowToken;
23906
23907        boolean mHardwareAccelerated;
23908        boolean mHardwareAccelerationRequested;
23909        ThreadedRenderer mThreadedRenderer;
23910        List<RenderNode> mPendingAnimatingRenderNodes;
23911
23912        /**
23913         * The state of the display to which the window is attached, as reported
23914         * by {@link Display#getState()}.  Note that the display state constants
23915         * declared by {@link Display} do not exactly line up with the screen state
23916         * constants declared by {@link View} (there are more display states than
23917         * screen states).
23918         */
23919        int mDisplayState = Display.STATE_UNKNOWN;
23920
23921        /**
23922         * Scale factor used by the compatibility mode
23923         */
23924        float mApplicationScale;
23925
23926        /**
23927         * Indicates whether the application is in compatibility mode
23928         */
23929        boolean mScalingRequired;
23930
23931        /**
23932         * Left position of this view's window
23933         */
23934        int mWindowLeft;
23935
23936        /**
23937         * Top position of this view's window
23938         */
23939        int mWindowTop;
23940
23941        /**
23942         * Indicates whether views need to use 32-bit drawing caches
23943         */
23944        boolean mUse32BitDrawingCache;
23945
23946        /**
23947         * For windows that are full-screen but using insets to layout inside
23948         * of the screen areas, these are the current insets to appear inside
23949         * the overscan area of the display.
23950         */
23951        final Rect mOverscanInsets = new Rect();
23952
23953        /**
23954         * For windows that are full-screen but using insets to layout inside
23955         * of the screen decorations, these are the current insets for the
23956         * content of the window.
23957         */
23958        final Rect mContentInsets = new Rect();
23959
23960        /**
23961         * For windows that are full-screen but using insets to layout inside
23962         * of the screen decorations, these are the current insets for the
23963         * actual visible parts of the window.
23964         */
23965        final Rect mVisibleInsets = new Rect();
23966
23967        /**
23968         * For windows that are full-screen but using insets to layout inside
23969         * of the screen decorations, these are the current insets for the
23970         * stable system windows.
23971         */
23972        final Rect mStableInsets = new Rect();
23973
23974        /**
23975         * For windows that include areas that are not covered by real surface these are the outsets
23976         * for real surface.
23977         */
23978        final Rect mOutsets = new Rect();
23979
23980        /**
23981         * In multi-window we force show the navigation bar. Because we don't want that the surface
23982         * size changes in this mode, we instead have a flag whether the navigation bar size should
23983         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
23984         */
23985        boolean mAlwaysConsumeNavBar;
23986
23987        /**
23988         * The internal insets given by this window.  This value is
23989         * supplied by the client (through
23990         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
23991         * be given to the window manager when changed to be used in laying
23992         * out windows behind it.
23993         */
23994        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
23995                = new ViewTreeObserver.InternalInsetsInfo();
23996
23997        /**
23998         * Set to true when mGivenInternalInsets is non-empty.
23999         */
24000        boolean mHasNonEmptyGivenInternalInsets;
24001
24002        /**
24003         * All views in the window's hierarchy that serve as scroll containers,
24004         * used to determine if the window can be resized or must be panned
24005         * to adjust for a soft input area.
24006         */
24007        final ArrayList<View> mScrollContainers = new ArrayList<View>();
24008
24009        final KeyEvent.DispatcherState mKeyDispatchState
24010                = new KeyEvent.DispatcherState();
24011
24012        /**
24013         * Indicates whether the view's window currently has the focus.
24014         */
24015        boolean mHasWindowFocus;
24016
24017        /**
24018         * The current visibility of the window.
24019         */
24020        int mWindowVisibility;
24021
24022        /**
24023         * Indicates the time at which drawing started to occur.
24024         */
24025        long mDrawingTime;
24026
24027        /**
24028         * Indicates whether or not ignoring the DIRTY_MASK flags.
24029         */
24030        boolean mIgnoreDirtyState;
24031
24032        /**
24033         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
24034         * to avoid clearing that flag prematurely.
24035         */
24036        boolean mSetIgnoreDirtyState = false;
24037
24038        /**
24039         * Indicates whether the view's window is currently in touch mode.
24040         */
24041        boolean mInTouchMode;
24042
24043        /**
24044         * Indicates whether the view has requested unbuffered input dispatching for the current
24045         * event stream.
24046         */
24047        boolean mUnbufferedDispatchRequested;
24048
24049        /**
24050         * Indicates that ViewAncestor should trigger a global layout change
24051         * the next time it performs a traversal
24052         */
24053        boolean mRecomputeGlobalAttributes;
24054
24055        /**
24056         * Always report new attributes at next traversal.
24057         */
24058        boolean mForceReportNewAttributes;
24059
24060        /**
24061         * Set during a traveral if any views want to keep the screen on.
24062         */
24063        boolean mKeepScreenOn;
24064
24065        /**
24066         * Set during a traveral if the light center needs to be updated.
24067         */
24068        boolean mNeedsUpdateLightCenter;
24069
24070        /**
24071         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
24072         */
24073        int mSystemUiVisibility;
24074
24075        /**
24076         * Hack to force certain system UI visibility flags to be cleared.
24077         */
24078        int mDisabledSystemUiVisibility;
24079
24080        /**
24081         * Last global system UI visibility reported by the window manager.
24082         */
24083        int mGlobalSystemUiVisibility = -1;
24084
24085        /**
24086         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
24087         * attached.
24088         */
24089        boolean mHasSystemUiListeners;
24090
24091        /**
24092         * Set if the window has requested to extend into the overscan region
24093         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
24094         */
24095        boolean mOverscanRequested;
24096
24097        /**
24098         * Set if the visibility of any views has changed.
24099         */
24100        boolean mViewVisibilityChanged;
24101
24102        /**
24103         * Set to true if a view has been scrolled.
24104         */
24105        boolean mViewScrollChanged;
24106
24107        /**
24108         * Set to true if high contrast mode enabled
24109         */
24110        boolean mHighContrastText;
24111
24112        /**
24113         * Set to true if a pointer event is currently being handled.
24114         */
24115        boolean mHandlingPointerEvent;
24116
24117        /**
24118         * Global to the view hierarchy used as a temporary for dealing with
24119         * x/y points in the transparent region computations.
24120         */
24121        final int[] mTransparentLocation = new int[2];
24122
24123        /**
24124         * Global to the view hierarchy used as a temporary for dealing with
24125         * x/y points in the ViewGroup.invalidateChild implementation.
24126         */
24127        final int[] mInvalidateChildLocation = new int[2];
24128
24129        /**
24130         * Global to the view hierarchy used as a temporary for dealing with
24131         * computing absolute on-screen location.
24132         */
24133        final int[] mTmpLocation = new int[2];
24134
24135        /**
24136         * Global to the view hierarchy used as a temporary for dealing with
24137         * x/y location when view is transformed.
24138         */
24139        final float[] mTmpTransformLocation = new float[2];
24140
24141        /**
24142         * The view tree observer used to dispatch global events like
24143         * layout, pre-draw, touch mode change, etc.
24144         */
24145        final ViewTreeObserver mTreeObserver;
24146
24147        /**
24148         * A Canvas used by the view hierarchy to perform bitmap caching.
24149         */
24150        Canvas mCanvas;
24151
24152        /**
24153         * The view root impl.
24154         */
24155        final ViewRootImpl mViewRootImpl;
24156
24157        /**
24158         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
24159         * handler can be used to pump events in the UI events queue.
24160         */
24161        final Handler mHandler;
24162
24163        /**
24164         * Temporary for use in computing invalidate rectangles while
24165         * calling up the hierarchy.
24166         */
24167        final Rect mTmpInvalRect = new Rect();
24168
24169        /**
24170         * Temporary for use in computing hit areas with transformed views
24171         */
24172        final RectF mTmpTransformRect = new RectF();
24173
24174        /**
24175         * Temporary for use in computing hit areas with transformed views
24176         */
24177        final RectF mTmpTransformRect1 = new RectF();
24178
24179        /**
24180         * Temporary list of rectanges.
24181         */
24182        final List<RectF> mTmpRectList = new ArrayList<>();
24183
24184        /**
24185         * Temporary for use in transforming invalidation rect
24186         */
24187        final Matrix mTmpMatrix = new Matrix();
24188
24189        /**
24190         * Temporary for use in transforming invalidation rect
24191         */
24192        final Transformation mTmpTransformation = new Transformation();
24193
24194        /**
24195         * Temporary for use in querying outlines from OutlineProviders
24196         */
24197        final Outline mTmpOutline = new Outline();
24198
24199        /**
24200         * Temporary list for use in collecting focusable descendents of a view.
24201         */
24202        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
24203
24204        /**
24205         * The id of the window for accessibility purposes.
24206         */
24207        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
24208
24209        /**
24210         * Flags related to accessibility processing.
24211         *
24212         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
24213         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
24214         */
24215        int mAccessibilityFetchFlags;
24216
24217        /**
24218         * The drawable for highlighting accessibility focus.
24219         */
24220        Drawable mAccessibilityFocusDrawable;
24221
24222        /**
24223         * Show where the margins, bounds and layout bounds are for each view.
24224         */
24225        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
24226
24227        /**
24228         * Point used to compute visible regions.
24229         */
24230        final Point mPoint = new Point();
24231
24232        /**
24233         * Used to track which View originated a requestLayout() call, used when
24234         * requestLayout() is called during layout.
24235         */
24236        View mViewRequestingLayout;
24237
24238        /**
24239         * Used to track views that need (at least) a partial relayout at their current size
24240         * during the next traversal.
24241         */
24242        List<View> mPartialLayoutViews = new ArrayList<>();
24243
24244        /**
24245         * Swapped with mPartialLayoutViews during layout to avoid concurrent
24246         * modification. Lazily assigned during ViewRootImpl layout.
24247         */
24248        List<View> mEmptyPartialLayoutViews;
24249
24250        /**
24251         * Used to track the identity of the current drag operation.
24252         */
24253        IBinder mDragToken;
24254
24255        /**
24256         * The drag shadow surface for the current drag operation.
24257         */
24258        public Surface mDragSurface;
24259
24260
24261        /**
24262         * The view that currently has a tooltip displayed.
24263         */
24264        View mTooltipHost;
24265
24266        /**
24267         * Creates a new set of attachment information with the specified
24268         * events handler and thread.
24269         *
24270         * @param handler the events handler the view must use
24271         */
24272        AttachInfo(IWindowSession session, IWindow window, Display display,
24273                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
24274                Context context) {
24275            mSession = session;
24276            mWindow = window;
24277            mWindowToken = window.asBinder();
24278            mDisplay = display;
24279            mViewRootImpl = viewRootImpl;
24280            mHandler = handler;
24281            mRootCallbacks = effectPlayer;
24282            mTreeObserver = new ViewTreeObserver(context);
24283        }
24284    }
24285
24286    /**
24287     * <p>ScrollabilityCache holds various fields used by a View when scrolling
24288     * is supported. This avoids keeping too many unused fields in most
24289     * instances of View.</p>
24290     */
24291    private static class ScrollabilityCache implements Runnable {
24292
24293        /**
24294         * Scrollbars are not visible
24295         */
24296        public static final int OFF = 0;
24297
24298        /**
24299         * Scrollbars are visible
24300         */
24301        public static final int ON = 1;
24302
24303        /**
24304         * Scrollbars are fading away
24305         */
24306        public static final int FADING = 2;
24307
24308        public boolean fadeScrollBars;
24309
24310        public int fadingEdgeLength;
24311        public int scrollBarDefaultDelayBeforeFade;
24312        public int scrollBarFadeDuration;
24313
24314        public int scrollBarSize;
24315        public int scrollBarMinTouchTarget;
24316        public ScrollBarDrawable scrollBar;
24317        public float[] interpolatorValues;
24318        public View host;
24319
24320        public final Paint paint;
24321        public final Matrix matrix;
24322        public Shader shader;
24323
24324        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
24325
24326        private static final float[] OPAQUE = { 255 };
24327        private static final float[] TRANSPARENT = { 0.0f };
24328
24329        /**
24330         * When fading should start. This time moves into the future every time
24331         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
24332         */
24333        public long fadeStartTime;
24334
24335
24336        /**
24337         * The current state of the scrollbars: ON, OFF, or FADING
24338         */
24339        public int state = OFF;
24340
24341        private int mLastColor;
24342
24343        public final Rect mScrollBarBounds = new Rect();
24344        public final Rect mScrollBarTouchBounds = new Rect();
24345
24346        public static final int NOT_DRAGGING = 0;
24347        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
24348        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
24349        public int mScrollBarDraggingState = NOT_DRAGGING;
24350
24351        public float mScrollBarDraggingPos = 0;
24352
24353        public ScrollabilityCache(ViewConfiguration configuration, View host) {
24354            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
24355            scrollBarSize = configuration.getScaledScrollBarSize();
24356            scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget();
24357            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
24358            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
24359
24360            paint = new Paint();
24361            matrix = new Matrix();
24362            // use use a height of 1, and then wack the matrix each time we
24363            // actually use it.
24364            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
24365            paint.setShader(shader);
24366            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
24367
24368            this.host = host;
24369        }
24370
24371        public void setFadeColor(int color) {
24372            if (color != mLastColor) {
24373                mLastColor = color;
24374
24375                if (color != 0) {
24376                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
24377                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
24378                    paint.setShader(shader);
24379                    // Restore the default transfer mode (src_over)
24380                    paint.setXfermode(null);
24381                } else {
24382                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
24383                    paint.setShader(shader);
24384                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
24385                }
24386            }
24387        }
24388
24389        public void run() {
24390            long now = AnimationUtils.currentAnimationTimeMillis();
24391            if (now >= fadeStartTime) {
24392
24393                // the animation fades the scrollbars out by changing
24394                // the opacity (alpha) from fully opaque to fully
24395                // transparent
24396                int nextFrame = (int) now;
24397                int framesCount = 0;
24398
24399                Interpolator interpolator = scrollBarInterpolator;
24400
24401                // Start opaque
24402                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
24403
24404                // End transparent
24405                nextFrame += scrollBarFadeDuration;
24406                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
24407
24408                state = FADING;
24409
24410                // Kick off the fade animation
24411                host.invalidate(true);
24412            }
24413        }
24414    }
24415
24416    /**
24417     * Resuable callback for sending
24418     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
24419     */
24420    private class SendViewScrolledAccessibilityEvent implements Runnable {
24421        public volatile boolean mIsPending;
24422
24423        public void run() {
24424            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
24425            mIsPending = false;
24426        }
24427    }
24428
24429    /**
24430     * <p>
24431     * This class represents a delegate that can be registered in a {@link View}
24432     * to enhance accessibility support via composition rather via inheritance.
24433     * It is specifically targeted to widget developers that extend basic View
24434     * classes i.e. classes in package android.view, that would like their
24435     * applications to be backwards compatible.
24436     * </p>
24437     * <div class="special reference">
24438     * <h3>Developer Guides</h3>
24439     * <p>For more information about making applications accessible, read the
24440     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
24441     * developer guide.</p>
24442     * </div>
24443     * <p>
24444     * A scenario in which a developer would like to use an accessibility delegate
24445     * is overriding a method introduced in a later API version than the minimal API
24446     * version supported by the application. For example, the method
24447     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
24448     * in API version 4 when the accessibility APIs were first introduced. If a
24449     * developer would like his application to run on API version 4 devices (assuming
24450     * all other APIs used by the application are version 4 or lower) and take advantage
24451     * of this method, instead of overriding the method which would break the application's
24452     * backwards compatibility, he can override the corresponding method in this
24453     * delegate and register the delegate in the target View if the API version of
24454     * the system is high enough, i.e. the API version is the same as or higher than the API
24455     * version that introduced
24456     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
24457     * </p>
24458     * <p>
24459     * Here is an example implementation:
24460     * </p>
24461     * <code><pre><p>
24462     * if (Build.VERSION.SDK_INT >= 14) {
24463     *     // If the API version is equal of higher than the version in
24464     *     // which onInitializeAccessibilityNodeInfo was introduced we
24465     *     // register a delegate with a customized implementation.
24466     *     View view = findViewById(R.id.view_id);
24467     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
24468     *         public void onInitializeAccessibilityNodeInfo(View host,
24469     *                 AccessibilityNodeInfo info) {
24470     *             // Let the default implementation populate the info.
24471     *             super.onInitializeAccessibilityNodeInfo(host, info);
24472     *             // Set some other information.
24473     *             info.setEnabled(host.isEnabled());
24474     *         }
24475     *     });
24476     * }
24477     * </code></pre></p>
24478     * <p>
24479     * This delegate contains methods that correspond to the accessibility methods
24480     * in View. If a delegate has been specified the implementation in View hands
24481     * off handling to the corresponding method in this delegate. The default
24482     * implementation the delegate methods behaves exactly as the corresponding
24483     * method in View for the case of no accessibility delegate been set. Hence,
24484     * to customize the behavior of a View method, clients can override only the
24485     * corresponding delegate method without altering the behavior of the rest
24486     * accessibility related methods of the host view.
24487     * </p>
24488     * <p>
24489     * <strong>Note:</strong> On platform versions prior to
24490     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
24491     * views in the {@code android.widget.*} package are called <i>before</i>
24492     * host methods. This prevents certain properties such as class name from
24493     * being modified by overriding
24494     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
24495     * as any changes will be overwritten by the host class.
24496     * <p>
24497     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
24498     * methods are called <i>after</i> host methods, which all properties to be
24499     * modified without being overwritten by the host class.
24500     */
24501    public static class AccessibilityDelegate {
24502
24503        /**
24504         * Sends an accessibility event of the given type. If accessibility is not
24505         * enabled this method has no effect.
24506         * <p>
24507         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
24508         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
24509         * been set.
24510         * </p>
24511         *
24512         * @param host The View hosting the delegate.
24513         * @param eventType The type of the event to send.
24514         *
24515         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
24516         */
24517        public void sendAccessibilityEvent(View host, int eventType) {
24518            host.sendAccessibilityEventInternal(eventType);
24519        }
24520
24521        /**
24522         * Performs the specified accessibility action on the view. For
24523         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
24524         * <p>
24525         * The default implementation behaves as
24526         * {@link View#performAccessibilityAction(int, Bundle)
24527         *  View#performAccessibilityAction(int, Bundle)} for the case of
24528         *  no accessibility delegate been set.
24529         * </p>
24530         *
24531         * @param action The action to perform.
24532         * @return Whether the action was performed.
24533         *
24534         * @see View#performAccessibilityAction(int, Bundle)
24535         *      View#performAccessibilityAction(int, Bundle)
24536         */
24537        public boolean performAccessibilityAction(View host, int action, Bundle args) {
24538            return host.performAccessibilityActionInternal(action, args);
24539        }
24540
24541        /**
24542         * Sends an accessibility event. This method behaves exactly as
24543         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
24544         * empty {@link AccessibilityEvent} and does not perform a check whether
24545         * accessibility is enabled.
24546         * <p>
24547         * The default implementation behaves as
24548         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24549         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
24550         * the case of no accessibility delegate been set.
24551         * </p>
24552         *
24553         * @param host The View hosting the delegate.
24554         * @param event The event to send.
24555         *
24556         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24557         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24558         */
24559        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
24560            host.sendAccessibilityEventUncheckedInternal(event);
24561        }
24562
24563        /**
24564         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
24565         * to its children for adding their text content to the event.
24566         * <p>
24567         * The default implementation behaves as
24568         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24569         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
24570         * the case of no accessibility delegate been set.
24571         * </p>
24572         *
24573         * @param host The View hosting the delegate.
24574         * @param event The event.
24575         * @return True if the event population was completed.
24576         *
24577         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24578         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24579         */
24580        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24581            return host.dispatchPopulateAccessibilityEventInternal(event);
24582        }
24583
24584        /**
24585         * Gives a chance to the host View to populate the accessibility event with its
24586         * text content.
24587         * <p>
24588         * The default implementation behaves as
24589         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
24590         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
24591         * the case of no accessibility delegate been set.
24592         * </p>
24593         *
24594         * @param host The View hosting the delegate.
24595         * @param event The accessibility event which to populate.
24596         *
24597         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
24598         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
24599         */
24600        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24601            host.onPopulateAccessibilityEventInternal(event);
24602        }
24603
24604        /**
24605         * Initializes an {@link AccessibilityEvent} with information about the
24606         * the host View which is the event source.
24607         * <p>
24608         * The default implementation behaves as
24609         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
24610         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
24611         * the case of no accessibility delegate been set.
24612         * </p>
24613         *
24614         * @param host The View hosting the delegate.
24615         * @param event The event to initialize.
24616         *
24617         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
24618         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
24619         */
24620        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
24621            host.onInitializeAccessibilityEventInternal(event);
24622        }
24623
24624        /**
24625         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
24626         * <p>
24627         * The default implementation behaves as
24628         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24629         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
24630         * the case of no accessibility delegate been set.
24631         * </p>
24632         *
24633         * @param host The View hosting the delegate.
24634         * @param info The instance to initialize.
24635         *
24636         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24637         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24638         */
24639        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
24640            host.onInitializeAccessibilityNodeInfoInternal(info);
24641        }
24642
24643        /**
24644         * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
24645         * additional data.
24646         * <p>
24647         * This method only needs to be implemented if the View offers to provide additional data.
24648         * </p>
24649         * <p>
24650         * The default implementation behaves as
24651         * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, int) for
24652         * the case where no accessibility delegate is set.
24653         * </p>
24654         *
24655         * @param host The View hosting the delegate. Never {@code null}.
24656         * @param info The info to which to add the extra data. Never {@code null}.
24657         * @param extraDataKey A key specifying the type of extra data to add to the info. The
24658         *                     extra data should be added to the {@link Bundle} returned by
24659         *                     the info's {@link AccessibilityNodeInfo#getExtras} method.  Never
24660         *                     {@code null}.
24661         * @param arguments A {@link Bundle} holding any arguments relevant for this request.
24662         *                  May be {@code null} if the if the service provided no arguments.
24663         *
24664         * @see AccessibilityNodeInfo#setExtraAvailableData
24665         */
24666        public void addExtraDataToAccessibilityNodeInfo(@NonNull View host,
24667                @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
24668                @Nullable Bundle arguments) {
24669            host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments);
24670        }
24671
24672        /**
24673         * Called when a child of the host View has requested sending an
24674         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
24675         * to augment the event.
24676         * <p>
24677         * The default implementation behaves as
24678         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24679         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
24680         * the case of no accessibility delegate been set.
24681         * </p>
24682         *
24683         * @param host The View hosting the delegate.
24684         * @param child The child which requests sending the event.
24685         * @param event The event to be sent.
24686         * @return True if the event should be sent
24687         *
24688         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24689         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24690         */
24691        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
24692                AccessibilityEvent event) {
24693            return host.onRequestSendAccessibilityEventInternal(child, event);
24694        }
24695
24696        /**
24697         * Gets the provider for managing a virtual view hierarchy rooted at this View
24698         * and reported to {@link android.accessibilityservice.AccessibilityService}s
24699         * that explore the window content.
24700         * <p>
24701         * The default implementation behaves as
24702         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
24703         * the case of no accessibility delegate been set.
24704         * </p>
24705         *
24706         * @return The provider.
24707         *
24708         * @see AccessibilityNodeProvider
24709         */
24710        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
24711            return null;
24712        }
24713
24714        /**
24715         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
24716         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
24717         * This method is responsible for obtaining an accessibility node info from a
24718         * pool of reusable instances and calling
24719         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
24720         * view to initialize the former.
24721         * <p>
24722         * <strong>Note:</strong> The client is responsible for recycling the obtained
24723         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
24724         * creation.
24725         * </p>
24726         * <p>
24727         * The default implementation behaves as
24728         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
24729         * the case of no accessibility delegate been set.
24730         * </p>
24731         * @return A populated {@link AccessibilityNodeInfo}.
24732         *
24733         * @see AccessibilityNodeInfo
24734         *
24735         * @hide
24736         */
24737        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
24738            return host.createAccessibilityNodeInfoInternal();
24739        }
24740    }
24741
24742    private static class MatchIdPredicate implements Predicate<View> {
24743        public int mId;
24744
24745        @Override
24746        public boolean test(View view) {
24747            return (view.mID == mId);
24748        }
24749    }
24750
24751    private static class MatchLabelForPredicate implements Predicate<View> {
24752        private int mLabeledId;
24753
24754        @Override
24755        public boolean test(View view) {
24756            return (view.mLabelForId == mLabeledId);
24757        }
24758    }
24759
24760    private class SendViewStateChangedAccessibilityEvent implements Runnable {
24761        private int mChangeTypes = 0;
24762        private boolean mPosted;
24763        private boolean mPostedWithDelay;
24764        private long mLastEventTimeMillis;
24765
24766        @Override
24767        public void run() {
24768            mPosted = false;
24769            mPostedWithDelay = false;
24770            mLastEventTimeMillis = SystemClock.uptimeMillis();
24771            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
24772                final AccessibilityEvent event = AccessibilityEvent.obtain();
24773                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
24774                event.setContentChangeTypes(mChangeTypes);
24775                sendAccessibilityEventUnchecked(event);
24776            }
24777            mChangeTypes = 0;
24778        }
24779
24780        public void runOrPost(int changeType) {
24781            mChangeTypes |= changeType;
24782
24783            // If this is a live region or the child of a live region, collect
24784            // all events from this frame and send them on the next frame.
24785            if (inLiveRegion()) {
24786                // If we're already posted with a delay, remove that.
24787                if (mPostedWithDelay) {
24788                    removeCallbacks(this);
24789                    mPostedWithDelay = false;
24790                }
24791                // Only post if we're not already posted.
24792                if (!mPosted) {
24793                    post(this);
24794                    mPosted = true;
24795                }
24796                return;
24797            }
24798
24799            if (mPosted) {
24800                return;
24801            }
24802
24803            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
24804            final long minEventIntevalMillis =
24805                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
24806            if (timeSinceLastMillis >= minEventIntevalMillis) {
24807                removeCallbacks(this);
24808                run();
24809            } else {
24810                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
24811                mPostedWithDelay = true;
24812            }
24813        }
24814    }
24815
24816    private boolean inLiveRegion() {
24817        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24818            return true;
24819        }
24820
24821        ViewParent parent = getParent();
24822        while (parent instanceof View) {
24823            if (((View) parent).getAccessibilityLiveRegion()
24824                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24825                return true;
24826            }
24827            parent = parent.getParent();
24828        }
24829
24830        return false;
24831    }
24832
24833    /**
24834     * Dump all private flags in readable format, useful for documentation and
24835     * sanity checking.
24836     */
24837    private static void dumpFlags() {
24838        final HashMap<String, String> found = Maps.newHashMap();
24839        try {
24840            for (Field field : View.class.getDeclaredFields()) {
24841                final int modifiers = field.getModifiers();
24842                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
24843                    if (field.getType().equals(int.class)) {
24844                        final int value = field.getInt(null);
24845                        dumpFlag(found, field.getName(), value);
24846                    } else if (field.getType().equals(int[].class)) {
24847                        final int[] values = (int[]) field.get(null);
24848                        for (int i = 0; i < values.length; i++) {
24849                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
24850                        }
24851                    }
24852                }
24853            }
24854        } catch (IllegalAccessException e) {
24855            throw new RuntimeException(e);
24856        }
24857
24858        final ArrayList<String> keys = Lists.newArrayList();
24859        keys.addAll(found.keySet());
24860        Collections.sort(keys);
24861        for (String key : keys) {
24862            Log.d(VIEW_LOG_TAG, found.get(key));
24863        }
24864    }
24865
24866    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
24867        // Sort flags by prefix, then by bits, always keeping unique keys
24868        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
24869        final int prefix = name.indexOf('_');
24870        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
24871        final String output = bits + " " + name;
24872        found.put(key, output);
24873    }
24874
24875    /** {@hide} */
24876    public void encode(@NonNull ViewHierarchyEncoder stream) {
24877        stream.beginObject(this);
24878        encodeProperties(stream);
24879        stream.endObject();
24880    }
24881
24882    /** {@hide} */
24883    @CallSuper
24884    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
24885        Object resolveId = ViewDebug.resolveId(getContext(), mID);
24886        if (resolveId instanceof String) {
24887            stream.addProperty("id", (String) resolveId);
24888        } else {
24889            stream.addProperty("id", mID);
24890        }
24891
24892        stream.addProperty("misc:transformation.alpha",
24893                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
24894        stream.addProperty("misc:transitionName", getTransitionName());
24895
24896        // layout
24897        stream.addProperty("layout:left", mLeft);
24898        stream.addProperty("layout:right", mRight);
24899        stream.addProperty("layout:top", mTop);
24900        stream.addProperty("layout:bottom", mBottom);
24901        stream.addProperty("layout:width", getWidth());
24902        stream.addProperty("layout:height", getHeight());
24903        stream.addProperty("layout:layoutDirection", getLayoutDirection());
24904        stream.addProperty("layout:layoutRtl", isLayoutRtl());
24905        stream.addProperty("layout:hasTransientState", hasTransientState());
24906        stream.addProperty("layout:baseline", getBaseline());
24907
24908        // layout params
24909        ViewGroup.LayoutParams layoutParams = getLayoutParams();
24910        if (layoutParams != null) {
24911            stream.addPropertyKey("layoutParams");
24912            layoutParams.encode(stream);
24913        }
24914
24915        // scrolling
24916        stream.addProperty("scrolling:scrollX", mScrollX);
24917        stream.addProperty("scrolling:scrollY", mScrollY);
24918
24919        // padding
24920        stream.addProperty("padding:paddingLeft", mPaddingLeft);
24921        stream.addProperty("padding:paddingRight", mPaddingRight);
24922        stream.addProperty("padding:paddingTop", mPaddingTop);
24923        stream.addProperty("padding:paddingBottom", mPaddingBottom);
24924        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
24925        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
24926        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
24927        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
24928        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
24929
24930        // measurement
24931        stream.addProperty("measurement:minHeight", mMinHeight);
24932        stream.addProperty("measurement:minWidth", mMinWidth);
24933        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
24934        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
24935
24936        // drawing
24937        stream.addProperty("drawing:elevation", getElevation());
24938        stream.addProperty("drawing:translationX", getTranslationX());
24939        stream.addProperty("drawing:translationY", getTranslationY());
24940        stream.addProperty("drawing:translationZ", getTranslationZ());
24941        stream.addProperty("drawing:rotation", getRotation());
24942        stream.addProperty("drawing:rotationX", getRotationX());
24943        stream.addProperty("drawing:rotationY", getRotationY());
24944        stream.addProperty("drawing:scaleX", getScaleX());
24945        stream.addProperty("drawing:scaleY", getScaleY());
24946        stream.addProperty("drawing:pivotX", getPivotX());
24947        stream.addProperty("drawing:pivotY", getPivotY());
24948        stream.addProperty("drawing:opaque", isOpaque());
24949        stream.addProperty("drawing:alpha", getAlpha());
24950        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
24951        stream.addProperty("drawing:shadow", hasShadow());
24952        stream.addProperty("drawing:solidColor", getSolidColor());
24953        stream.addProperty("drawing:layerType", mLayerType);
24954        stream.addProperty("drawing:willNotDraw", willNotDraw());
24955        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
24956        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
24957        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
24958        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
24959
24960        // focus
24961        stream.addProperty("focus:hasFocus", hasFocus());
24962        stream.addProperty("focus:isFocused", isFocused());
24963        stream.addProperty("focus:isFocusable", isFocusable());
24964        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
24965
24966        stream.addProperty("misc:clickable", isClickable());
24967        stream.addProperty("misc:pressed", isPressed());
24968        stream.addProperty("misc:selected", isSelected());
24969        stream.addProperty("misc:touchMode", isInTouchMode());
24970        stream.addProperty("misc:hovered", isHovered());
24971        stream.addProperty("misc:activated", isActivated());
24972
24973        stream.addProperty("misc:visibility", getVisibility());
24974        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
24975        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
24976
24977        stream.addProperty("misc:enabled", isEnabled());
24978        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
24979        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
24980
24981        // theme attributes
24982        Resources.Theme theme = getContext().getTheme();
24983        if (theme != null) {
24984            stream.addPropertyKey("theme");
24985            theme.encode(stream);
24986        }
24987
24988        // view attribute information
24989        int n = mAttributes != null ? mAttributes.length : 0;
24990        stream.addProperty("meta:__attrCount__", n/2);
24991        for (int i = 0; i < n; i += 2) {
24992            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
24993        }
24994
24995        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
24996
24997        // text
24998        stream.addProperty("text:textDirection", getTextDirection());
24999        stream.addProperty("text:textAlignment", getTextAlignment());
25000
25001        // accessibility
25002        CharSequence contentDescription = getContentDescription();
25003        stream.addProperty("accessibility:contentDescription",
25004                contentDescription == null ? "" : contentDescription.toString());
25005        stream.addProperty("accessibility:labelFor", getLabelFor());
25006        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
25007    }
25008
25009    /**
25010     * Determine if this view is rendered on a round wearable device and is the main view
25011     * on the screen.
25012     */
25013    boolean shouldDrawRoundScrollbar() {
25014        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
25015            return false;
25016        }
25017
25018        final View rootView = getRootView();
25019        final WindowInsets insets = getRootWindowInsets();
25020
25021        int height = getHeight();
25022        int width = getWidth();
25023        int displayHeight = rootView.getHeight();
25024        int displayWidth = rootView.getWidth();
25025
25026        if (height != displayHeight || width != displayWidth) {
25027            return false;
25028        }
25029
25030        getLocationInWindow(mAttachInfo.mTmpLocation);
25031        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
25032                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
25033    }
25034
25035    /**
25036     * Sets the tooltip text which will be displayed in a small popup next to the view.
25037     * <p>
25038     * The tooltip will be displayed:
25039     * <ul>
25040     * <li>On long click, unless is not handled otherwise (by OnLongClickListener or a context
25041     * menu). </li>
25042     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
25043     * </ul>
25044     * <p>
25045     * <strong>Note:</strong> Do not override this method, as it will have no
25046     * effect on the text displayed in the tooltip.
25047     *
25048     * @param tooltipText the tooltip text, or null if no tooltip is required
25049     * @see #getTooltipText()
25050     * @attr ref android.R.styleable#View_tooltipText
25051     */
25052    public void setTooltipText(@Nullable CharSequence tooltipText) {
25053        if (TextUtils.isEmpty(tooltipText)) {
25054            setFlags(0, TOOLTIP);
25055            hideTooltip();
25056            mTooltipInfo = null;
25057        } else {
25058            setFlags(TOOLTIP, TOOLTIP);
25059            if (mTooltipInfo == null) {
25060                mTooltipInfo = new TooltipInfo();
25061                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
25062                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
25063            }
25064            mTooltipInfo.mTooltipText = tooltipText;
25065            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
25066                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText);
25067            }
25068        }
25069    }
25070
25071    /**
25072     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
25073     */
25074    public void setTooltip(@Nullable CharSequence tooltipText) {
25075        setTooltipText(tooltipText);
25076    }
25077
25078    /**
25079     * Returns the view's tooltip text.
25080     *
25081     * <strong>Note:</strong> Do not override this method, as it will have no
25082     * effect on the text displayed in the tooltip. You must call
25083     * {@link #setTooltipText(CharSequence)} to modify the tooltip text.
25084     *
25085     * @return the tooltip text
25086     * @see #setTooltipText(CharSequence)
25087     * @attr ref android.R.styleable#View_tooltipText
25088     */
25089    @Nullable
25090    public CharSequence getTooltipText() {
25091        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
25092    }
25093
25094    /**
25095     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
25096     */
25097    @Nullable
25098    public CharSequence getTooltip() {
25099        return getTooltipText();
25100    }
25101
25102    private boolean showTooltip(int x, int y, boolean fromLongClick) {
25103        if (mAttachInfo == null || mTooltipInfo == null) {
25104            return false;
25105        }
25106        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
25107            return false;
25108        }
25109        if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) {
25110            return false;
25111        }
25112        hideTooltip();
25113        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
25114        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
25115        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
25116        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText);
25117        mAttachInfo.mTooltipHost = this;
25118        return true;
25119    }
25120
25121    void hideTooltip() {
25122        if (mTooltipInfo == null) {
25123            return;
25124        }
25125        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25126        if (mTooltipInfo.mTooltipPopup == null) {
25127            return;
25128        }
25129        mTooltipInfo.mTooltipPopup.hide();
25130        mTooltipInfo.mTooltipPopup = null;
25131        mTooltipInfo.mTooltipFromLongClick = false;
25132        if (mAttachInfo != null) {
25133            mAttachInfo.mTooltipHost = null;
25134        }
25135    }
25136
25137    private boolean showLongClickTooltip(int x, int y) {
25138        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25139        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25140        return showTooltip(x, y, true);
25141    }
25142
25143    private void showHoverTooltip() {
25144        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
25145    }
25146
25147    boolean dispatchTooltipHoverEvent(MotionEvent event) {
25148        if (mTooltipInfo == null) {
25149            return false;
25150        }
25151        switch(event.getAction()) {
25152            case MotionEvent.ACTION_HOVER_MOVE:
25153                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
25154                    break;
25155                }
25156                if (!mTooltipInfo.mTooltipFromLongClick) {
25157                    if (mTooltipInfo.mTooltipPopup == null) {
25158                        // Schedule showing the tooltip after a timeout.
25159                        mTooltipInfo.mAnchorX = (int) event.getX();
25160                        mTooltipInfo.mAnchorY = (int) event.getY();
25161                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25162                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
25163                                ViewConfiguration.getHoverTooltipShowTimeout());
25164                    }
25165
25166                    // Hide hover-triggered tooltip after a period of inactivity.
25167                    // Match the timeout used by NativeInputManager to hide the mouse pointer
25168                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
25169                    final int timeout;
25170                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
25171                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
25172                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
25173                    } else {
25174                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
25175                    }
25176                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25177                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
25178                }
25179                return true;
25180
25181            case MotionEvent.ACTION_HOVER_EXIT:
25182                if (!mTooltipInfo.mTooltipFromLongClick) {
25183                    hideTooltip();
25184                }
25185                break;
25186        }
25187        return false;
25188    }
25189
25190    void handleTooltipKey(KeyEvent event) {
25191        switch (event.getAction()) {
25192            case KeyEvent.ACTION_DOWN:
25193                if (event.getRepeatCount() == 0) {
25194                    hideTooltip();
25195                }
25196                break;
25197
25198            case KeyEvent.ACTION_UP:
25199                handleTooltipUp();
25200                break;
25201        }
25202    }
25203
25204    private void handleTooltipUp() {
25205        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
25206            return;
25207        }
25208        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25209        postDelayed(mTooltipInfo.mHideTooltipRunnable,
25210                ViewConfiguration.getLongPressTooltipHideTimeout());
25211    }
25212
25213    private int getFocusableAttribute(TypedArray attributes) {
25214        TypedValue val = new TypedValue();
25215        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
25216            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
25217                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
25218            } else {
25219                return val.data;
25220            }
25221        } else {
25222            return FOCUSABLE_AUTO;
25223        }
25224    }
25225
25226    /**
25227     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
25228     * is not showing.
25229     * @hide
25230     */
25231    @TestApi
25232    public View getTooltipView() {
25233        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
25234            return null;
25235        }
25236        return mTooltipInfo.mTooltipPopup.getContentView();
25237    }
25238}
25239