View.java revision 2874daa4d38bddd3a5f0edb3774d5e5884dd9554
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 android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
20import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
21import static android.os.Build.VERSION_CODES.KITKAT;
22import static android.os.Build.VERSION_CODES.M;
23import static android.os.Build.VERSION_CODES.N;
24
25import static java.lang.Math.max;
26
27import android.animation.AnimatorInflater;
28import android.animation.StateListAnimator;
29import android.annotation.CallSuper;
30import android.annotation.ColorInt;
31import android.annotation.DrawableRes;
32import android.annotation.FloatRange;
33import android.annotation.IdRes;
34import android.annotation.IntDef;
35import android.annotation.IntRange;
36import android.annotation.LayoutRes;
37import android.annotation.NonNull;
38import android.annotation.Nullable;
39import android.annotation.Size;
40import android.annotation.TestApi;
41import android.annotation.UiThread;
42import android.app.Application.OnProvideAssistDataListener;
43import android.content.ClipData;
44import android.content.Context;
45import android.content.ContextWrapper;
46import android.content.Intent;
47import android.content.res.ColorStateList;
48import android.content.res.Configuration;
49import android.content.res.Resources;
50import android.content.res.TypedArray;
51import android.graphics.Bitmap;
52import android.graphics.Canvas;
53import android.graphics.Color;
54import android.graphics.Insets;
55import android.graphics.Interpolator;
56import android.graphics.LinearGradient;
57import android.graphics.Matrix;
58import android.graphics.Outline;
59import android.graphics.Paint;
60import android.graphics.PixelFormat;
61import android.graphics.Point;
62import android.graphics.PorterDuff;
63import android.graphics.PorterDuffXfermode;
64import android.graphics.Rect;
65import android.graphics.RectF;
66import android.graphics.Region;
67import android.graphics.Shader;
68import android.graphics.drawable.ColorDrawable;
69import android.graphics.drawable.Drawable;
70import android.hardware.display.DisplayManagerGlobal;
71import android.os.Build.VERSION_CODES;
72import android.os.Bundle;
73import android.os.Handler;
74import android.os.IBinder;
75import android.os.Parcel;
76import android.os.Parcelable;
77import android.os.RemoteException;
78import android.os.SystemClock;
79import android.os.SystemProperties;
80import android.os.Trace;
81import android.text.TextUtils;
82import android.util.AttributeSet;
83import android.util.FloatProperty;
84import android.util.LayoutDirection;
85import android.util.Log;
86import android.util.LongSparseLongArray;
87import android.util.Pools.SynchronizedPool;
88import android.util.Property;
89import android.util.SparseArray;
90import android.util.StateSet;
91import android.util.SuperNotCalledException;
92import android.util.TypedValue;
93import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
94import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
95import android.view.AccessibilityIterators.TextSegmentIterator;
96import android.view.AccessibilityIterators.WordTextSegmentIterator;
97import android.view.ContextMenu.ContextMenuInfo;
98import android.view.accessibility.AccessibilityEvent;
99import android.view.accessibility.AccessibilityEventSource;
100import android.view.accessibility.AccessibilityManager;
101import android.view.accessibility.AccessibilityNodeInfo;
102import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
103import android.view.accessibility.AccessibilityNodeProvider;
104import android.view.animation.Animation;
105import android.view.animation.AnimationUtils;
106import android.view.animation.Transformation;
107import android.view.autofill.AutoFillType;
108import android.view.autofill.AutoFillValue;
109import android.view.autofill.VirtualViewDelegate;
110import android.view.inputmethod.EditorInfo;
111import android.view.inputmethod.InputConnection;
112import android.view.inputmethod.InputMethodManager;
113import android.widget.Checkable;
114import android.widget.FrameLayout;
115import android.widget.ScrollBarDrawable;
116
117import com.android.internal.R;
118import com.android.internal.util.Predicate;
119import com.android.internal.view.TooltipPopup;
120import com.android.internal.view.menu.MenuBuilder;
121import com.android.internal.widget.ScrollBarUtils;
122
123import com.google.android.collect.Lists;
124import com.google.android.collect.Maps;
125
126import java.lang.annotation.Retention;
127import java.lang.annotation.RetentionPolicy;
128import java.lang.ref.WeakReference;
129import java.lang.reflect.Field;
130import java.lang.reflect.InvocationTargetException;
131import java.lang.reflect.Method;
132import java.lang.reflect.Modifier;
133import java.util.ArrayList;
134import java.util.Arrays;
135import java.util.Collection;
136import java.util.Collections;
137import java.util.HashMap;
138import java.util.List;
139import java.util.Locale;
140import java.util.Map;
141import java.util.concurrent.CopyOnWriteArrayList;
142import java.util.concurrent.atomic.AtomicInteger;
143
144/**
145 * <p>
146 * This class represents the basic building block for user interface components. A View
147 * occupies a rectangular area on the screen and is responsible for drawing and
148 * event handling. View is the base class for <em>widgets</em>, which are
149 * used to create interactive UI components (buttons, text fields, etc.). The
150 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
151 * are invisible containers that hold other Views (or other ViewGroups) and define
152 * their layout properties.
153 * </p>
154 *
155 * <div class="special reference">
156 * <h3>Developer Guides</h3>
157 * <p>For information about using this class to develop your application's user interface,
158 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
159 * </div>
160 *
161 * <a name="Using"></a>
162 * <h3>Using Views</h3>
163 * <p>
164 * All of the views in a window are arranged in a single tree. You can add views
165 * either from code or by specifying a tree of views in one or more XML layout
166 * files. There are many specialized subclasses of views that act as controls or
167 * are capable of displaying text, images, or other content.
168 * </p>
169 * <p>
170 * Once you have created a tree of views, there are typically a few types of
171 * common operations you may wish to perform:
172 * <ul>
173 * <li><strong>Set properties:</strong> for example setting the text of a
174 * {@link android.widget.TextView}. The available properties and the methods
175 * that set them will vary among the different subclasses of views. Note that
176 * properties that are known at build time can be set in the XML layout
177 * files.</li>
178 * <li><strong>Set focus:</strong> The framework will handle moving focus in
179 * response to user input. To force focus to a specific view, call
180 * {@link #requestFocus}.</li>
181 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
182 * that will be notified when something interesting happens to the view. For
183 * example, all views will let you set a listener to be notified when the view
184 * gains or loses focus. You can register such a listener using
185 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
186 * Other view subclasses offer more specialized listeners. For example, a Button
187 * exposes a listener to notify clients when the button is clicked.</li>
188 * <li><strong>Set visibility:</strong> You can hide or show views using
189 * {@link #setVisibility(int)}.</li>
190 * </ul>
191 * </p>
192 * <p><em>
193 * Note: The Android framework is responsible for measuring, laying out and
194 * drawing views. You should not call methods that perform these actions on
195 * views yourself unless you are actually implementing a
196 * {@link android.view.ViewGroup}.
197 * </em></p>
198 *
199 * <a name="Lifecycle"></a>
200 * <h3>Implementing a Custom View</h3>
201 *
202 * <p>
203 * To implement a custom view, you will usually begin by providing overrides for
204 * some of the standard methods that the framework calls on all views. You do
205 * not need to override all of these methods. In fact, you can start by just
206 * overriding {@link #onDraw(android.graphics.Canvas)}.
207 * <table border="2" width="85%" align="center" cellpadding="5">
208 *     <thead>
209 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
210 *     </thead>
211 *
212 *     <tbody>
213 *     <tr>
214 *         <td rowspan="2">Creation</td>
215 *         <td>Constructors</td>
216 *         <td>There is a form of the constructor that are called when the view
217 *         is created from code and a form that is called when the view is
218 *         inflated from a layout file. The second form should parse and apply
219 *         any attributes defined in the layout file.
220 *         </td>
221 *     </tr>
222 *     <tr>
223 *         <td><code>{@link #onFinishInflate()}</code></td>
224 *         <td>Called after a view and all of its children has been inflated
225 *         from XML.</td>
226 *     </tr>
227 *
228 *     <tr>
229 *         <td rowspan="3">Layout</td>
230 *         <td><code>{@link #onMeasure(int, int)}</code></td>
231 *         <td>Called to determine the size requirements for this view and all
232 *         of its children.
233 *         </td>
234 *     </tr>
235 *     <tr>
236 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
237 *         <td>Called when this view should assign a size and position to all
238 *         of its children.
239 *         </td>
240 *     </tr>
241 *     <tr>
242 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
243 *         <td>Called when the size of this view has changed.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td>Drawing</td>
249 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
250 *         <td>Called when the view should render its content.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td rowspan="4">Event processing</td>
256 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
257 *         <td>Called when a new hardware key event occurs.
258 *         </td>
259 *     </tr>
260 *     <tr>
261 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
262 *         <td>Called when a hardware key up event occurs.
263 *         </td>
264 *     </tr>
265 *     <tr>
266 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
267 *         <td>Called when a trackball motion event occurs.
268 *         </td>
269 *     </tr>
270 *     <tr>
271 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
272 *         <td>Called when a touch screen motion event occurs.
273 *         </td>
274 *     </tr>
275 *
276 *     <tr>
277 *         <td rowspan="2">Focus</td>
278 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
279 *         <td>Called when the view gains or loses focus.
280 *         </td>
281 *     </tr>
282 *
283 *     <tr>
284 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
285 *         <td>Called when the window containing the view gains or loses focus.
286 *         </td>
287 *     </tr>
288 *
289 *     <tr>
290 *         <td rowspan="3">Attaching</td>
291 *         <td><code>{@link #onAttachedToWindow()}</code></td>
292 *         <td>Called when the view is attached to a window.
293 *         </td>
294 *     </tr>
295 *
296 *     <tr>
297 *         <td><code>{@link #onDetachedFromWindow}</code></td>
298 *         <td>Called when the view is detached from its window.
299 *         </td>
300 *     </tr>
301 *
302 *     <tr>
303 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
304 *         <td>Called when the visibility of the window containing the view
305 *         has changed.
306 *         </td>
307 *     </tr>
308 *     </tbody>
309 *
310 * </table>
311 * </p>
312 *
313 * <a name="IDs"></a>
314 * <h3>IDs</h3>
315 * Views may have an integer id associated with them. These ids are typically
316 * assigned in the layout XML files, and are used to find specific views within
317 * the view tree. A common pattern is to:
318 * <ul>
319 * <li>Define a Button in the layout file and assign it a unique ID.
320 * <pre>
321 * &lt;Button
322 *     android:id="@+id/my_button"
323 *     android:layout_width="wrap_content"
324 *     android:layout_height="wrap_content"
325 *     android:text="@string/my_button_text"/&gt;
326 * </pre></li>
327 * <li>From the onCreate method of an Activity, find the Button
328 * <pre class="prettyprint">
329 *      Button myButton = (Button) findViewById(R.id.my_button);
330 * </pre></li>
331 * </ul>
332 * <p>
333 * View IDs need not be unique throughout the tree, but it is good practice to
334 * ensure that they are at least unique within the part of the tree you are
335 * searching.
336 * </p>
337 *
338 * <a name="Position"></a>
339 * <h3>Position</h3>
340 * <p>
341 * The geometry of a view is that of a rectangle. A view has a location,
342 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
343 * two dimensions, expressed as a width and a height. The unit for location
344 * and dimensions is the pixel.
345 * </p>
346 *
347 * <p>
348 * It is possible to retrieve the location of a view by invoking the methods
349 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
350 * coordinate of the rectangle representing the view. The latter returns the
351 * top, or Y, coordinate of the rectangle representing the view. These methods
352 * both return the location of the view relative to its parent. For instance,
353 * when getLeft() returns 20, that means the view is located 20 pixels to the
354 * right of the left edge of its direct parent.
355 * </p>
356 *
357 * <p>
358 * In addition, several convenience methods are offered to avoid unnecessary
359 * computations, namely {@link #getRight()} and {@link #getBottom()}.
360 * These methods return the coordinates of the right and bottom edges of the
361 * rectangle representing the view. For instance, calling {@link #getRight()}
362 * is similar to the following computation: <code>getLeft() + getWidth()</code>
363 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
364 * </p>
365 *
366 * <a name="SizePaddingMargins"></a>
367 * <h3>Size, padding and margins</h3>
368 * <p>
369 * The size of a view is expressed with a width and a height. A view actually
370 * possess two pairs of width and height values.
371 * </p>
372 *
373 * <p>
374 * The first pair is known as <em>measured width</em> and
375 * <em>measured height</em>. These dimensions define how big a view wants to be
376 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
377 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
378 * and {@link #getMeasuredHeight()}.
379 * </p>
380 *
381 * <p>
382 * The second pair is simply known as <em>width</em> and <em>height</em>, or
383 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
384 * dimensions define the actual size of the view on screen, at drawing time and
385 * after layout. These values may, but do not have to, be different from the
386 * measured width and height. The width and height can be obtained by calling
387 * {@link #getWidth()} and {@link #getHeight()}.
388 * </p>
389 *
390 * <p>
391 * To measure its dimensions, a view takes into account its padding. The padding
392 * is expressed in pixels for the left, top, right and bottom parts of the view.
393 * Padding can be used to offset the content of the view by a specific amount of
394 * pixels. For instance, a left padding of 2 will push the view's content by
395 * 2 pixels to the right of the left edge. Padding can be set using the
396 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
397 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
398 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
399 * {@link #getPaddingEnd()}.
400 * </p>
401 *
402 * <p>
403 * Even though a view can define a padding, it does not provide any support for
404 * margins. However, view groups provide such a support. Refer to
405 * {@link android.view.ViewGroup} and
406 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
407 * </p>
408 *
409 * <a name="Layout"></a>
410 * <h3>Layout</h3>
411 * <p>
412 * Layout is a two pass process: a measure pass and a layout pass. The measuring
413 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
414 * of the view tree. Each view pushes dimension specifications down the tree
415 * during the recursion. At the end of the measure pass, every view has stored
416 * its measurements. The second pass happens in
417 * {@link #layout(int,int,int,int)} and is also top-down. During
418 * this pass each parent is responsible for positioning all of its children
419 * using the sizes computed in the measure pass.
420 * </p>
421 *
422 * <p>
423 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
424 * {@link #getMeasuredHeight()} values must be set, along with those for all of
425 * that view's descendants. A view's measured width and measured height values
426 * must respect the constraints imposed by the view's parents. This guarantees
427 * that at the end of the measure pass, all parents accept all of their
428 * children's measurements. A parent view may call measure() more than once on
429 * its children. For example, the parent may measure each child once with
430 * unspecified dimensions to find out how big they want to be, then call
431 * measure() on them again with actual numbers if the sum of all the children's
432 * unconstrained sizes is too big or too small.
433 * </p>
434 *
435 * <p>
436 * The measure pass uses two classes to communicate dimensions. The
437 * {@link MeasureSpec} class is used by views to tell their parents how they
438 * want to be measured and positioned. The base LayoutParams class just
439 * describes how big the view wants to be for both width and height. For each
440 * dimension, it can specify one of:
441 * <ul>
442 * <li> an exact number
443 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
444 * (minus padding)
445 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
446 * enclose its content (plus padding).
447 * </ul>
448 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
449 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
450 * an X and Y value.
451 * </p>
452 *
453 * <p>
454 * MeasureSpecs are used to push requirements down the tree from parent to
455 * child. A MeasureSpec can be in one of three modes:
456 * <ul>
457 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
458 * of a child view. For example, a LinearLayout may call measure() on its child
459 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
460 * tall the child view wants to be given a width of 240 pixels.
461 * <li>EXACTLY: This is used by the parent to impose an exact size on the
462 * child. The child must use this size, and guarantee that all of its
463 * descendants will fit within this size.
464 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
465 * child. The child must guarantee that it and all of its descendants will fit
466 * within this size.
467 * </ul>
468 * </p>
469 *
470 * <p>
471 * To initiate a layout, call {@link #requestLayout}. This method is typically
472 * called by a view on itself when it believes that is can no longer fit within
473 * its current bounds.
474 * </p>
475 *
476 * <a name="Drawing"></a>
477 * <h3>Drawing</h3>
478 * <p>
479 * Drawing is handled by walking the tree and recording the drawing commands of
480 * any View that needs to update. After this, the drawing commands of the
481 * entire tree are issued to screen, clipped to the newly damaged area.
482 * </p>
483 *
484 * <p>
485 * The tree is largely recorded and drawn in order, with parents drawn before
486 * (i.e., behind) their children, with siblings drawn in the order they appear
487 * in the tree. If you set a background drawable for a View, then the View will
488 * draw it before calling back to its <code>onDraw()</code> method. The child
489 * drawing order can be overridden with
490 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
491 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
492 * </p>
493 *
494 * <p>
495 * To force a view to draw, call {@link #invalidate()}.
496 * </p>
497 *
498 * <a name="EventHandlingThreading"></a>
499 * <h3>Event Handling and Threading</h3>
500 * <p>
501 * The basic cycle of a view is as follows:
502 * <ol>
503 * <li>An event comes in and is dispatched to the appropriate view. The view
504 * handles the event and notifies any listeners.</li>
505 * <li>If in the course of processing the event, the view's bounds may need
506 * to be changed, the view will call {@link #requestLayout()}.</li>
507 * <li>Similarly, if in the course of processing the event the view's appearance
508 * may need to be changed, the view will call {@link #invalidate()}.</li>
509 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
510 * the framework will take care of measuring, laying out, and drawing the tree
511 * as appropriate.</li>
512 * </ol>
513 * </p>
514 *
515 * <p><em>Note: The entire view tree is single threaded. You must always be on
516 * the UI thread when calling any method on any view.</em>
517 * If you are doing work on other threads and want to update the state of a view
518 * from that thread, you should use a {@link Handler}.
519 * </p>
520 *
521 * <a name="FocusHandling"></a>
522 * <h3>Focus Handling</h3>
523 * <p>
524 * The framework will handle routine focus movement in response to user input.
525 * This includes changing the focus as views are removed or hidden, or as new
526 * views become available. Views indicate their willingness to take focus
527 * through the {@link #isFocusable} method. To change whether a view can take
528 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
529 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
530 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
531 * </p>
532 * <p>
533 * Focus movement is based on an algorithm which finds the nearest neighbor in a
534 * given direction. In rare cases, the default algorithm may not match the
535 * intended behavior of the developer. In these situations, you can provide
536 * explicit overrides by using these XML attributes in the layout file:
537 * <pre>
538 * nextFocusDown
539 * nextFocusLeft
540 * nextFocusRight
541 * nextFocusUp
542 * </pre>
543 * </p>
544 *
545 *
546 * <p>
547 * To get a particular view to take focus, call {@link #requestFocus()}.
548 * </p>
549 *
550 * <a name="TouchMode"></a>
551 * <h3>Touch Mode</h3>
552 * <p>
553 * When a user is navigating a user interface via directional keys such as a D-pad, it is
554 * necessary to give focus to actionable items such as buttons so the user can see
555 * what will take input.  If the device has touch capabilities, however, and the user
556 * begins interacting with the interface by touching it, it is no longer necessary to
557 * always highlight, or give focus to, a particular view.  This motivates a mode
558 * for interaction named 'touch mode'.
559 * </p>
560 * <p>
561 * For a touch capable device, once the user touches the screen, the device
562 * will enter touch mode.  From this point onward, only views for which
563 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
564 * Other views that are touchable, like buttons, will not take focus when touched; they will
565 * only fire the on click listeners.
566 * </p>
567 * <p>
568 * Any time a user hits a directional key, such as a D-pad direction, the view device will
569 * exit touch mode, and find a view to take focus, so that the user may resume interacting
570 * with the user interface without touching the screen again.
571 * </p>
572 * <p>
573 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
574 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
575 * </p>
576 *
577 * <a name="Scrolling"></a>
578 * <h3>Scrolling</h3>
579 * <p>
580 * The framework provides basic support for views that wish to internally
581 * scroll their content. This includes keeping track of the X and Y scroll
582 * offset as well as mechanisms for drawing scrollbars. See
583 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
584 * {@link #awakenScrollBars()} for more details.
585 * </p>
586 *
587 * <a name="Tags"></a>
588 * <h3>Tags</h3>
589 * <p>
590 * Unlike IDs, tags are not used to identify views. Tags are essentially an
591 * extra piece of information that can be associated with a view. They are most
592 * often used as a convenience to store data related to views in the views
593 * themselves rather than by putting them in a separate structure.
594 * </p>
595 * <p>
596 * Tags may be specified with character sequence values in layout XML as either
597 * a single tag using the {@link android.R.styleable#View_tag android:tag}
598 * attribute or multiple tags using the {@code <tag>} child element:
599 * <pre>
600 *     &ltView ...
601 *           android:tag="@string/mytag_value" /&gt;
602 *     &ltView ...&gt;
603 *         &lttag android:id="@+id/mytag"
604 *              android:value="@string/mytag_value" /&gt;
605 *     &lt/View>
606 * </pre>
607 * </p>
608 * <p>
609 * Tags may also be specified with arbitrary objects from code using
610 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
611 * </p>
612 *
613 * <a name="Themes"></a>
614 * <h3>Themes</h3>
615 * <p>
616 * By default, Views are created using the theme of the Context object supplied
617 * to their constructor; however, a different theme may be specified by using
618 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
619 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
620 * code.
621 * </p>
622 * <p>
623 * When the {@link android.R.styleable#View_theme android:theme} attribute is
624 * used in XML, the specified theme is applied on top of the inflation
625 * context's theme (see {@link LayoutInflater}) and used for the view itself as
626 * well as any child elements.
627 * </p>
628 * <p>
629 * In the following example, both views will be created using the Material dark
630 * color scheme; however, because an overlay theme is used which only defines a
631 * subset of attributes, the value of
632 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
633 * the inflation context's theme (e.g. the Activity theme) will be preserved.
634 * <pre>
635 *     &ltLinearLayout
636 *             ...
637 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
638 *         &ltView ...&gt;
639 *     &lt/LinearLayout&gt;
640 * </pre>
641 * </p>
642 *
643 * <a name="Properties"></a>
644 * <h3>Properties</h3>
645 * <p>
646 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
647 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
648 * available both in the {@link Property} form as well as in similarly-named setter/getter
649 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
650 * be used to set persistent state associated with these rendering-related properties on the view.
651 * The properties and methods can also be used in conjunction with
652 * {@link android.animation.Animator Animator}-based animations, described more in the
653 * <a href="#Animation">Animation</a> section.
654 * </p>
655 *
656 * <a name="Animation"></a>
657 * <h3>Animation</h3>
658 * <p>
659 * Starting with Android 3.0, the preferred way of animating views is to use the
660 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
661 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
662 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
663 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
664 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
665 * makes animating these View properties particularly easy and efficient.
666 * </p>
667 * <p>
668 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
669 * You can attach an {@link Animation} object to a view using
670 * {@link #setAnimation(Animation)} or
671 * {@link #startAnimation(Animation)}. The animation can alter the scale,
672 * rotation, translation and alpha of a view over time. If the animation is
673 * attached to a view that has children, the animation will affect the entire
674 * subtree rooted by that node. When an animation is started, the framework will
675 * take care of redrawing the appropriate views until the animation completes.
676 * </p>
677 *
678 * <a name="Security"></a>
679 * <h3>Security</h3>
680 * <p>
681 * Sometimes it is essential that an application be able to verify that an action
682 * is being performed with the full knowledge and consent of the user, such as
683 * granting a permission request, making a purchase or clicking on an advertisement.
684 * Unfortunately, a malicious application could try to spoof the user into
685 * performing these actions, unaware, by concealing the intended purpose of the view.
686 * As a remedy, the framework offers a touch filtering mechanism that can be used to
687 * improve the security of views that provide access to sensitive functionality.
688 * </p><p>
689 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
690 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
691 * will discard touches that are received whenever the view's window is obscured by
692 * another visible window.  As a result, the view will not receive touches whenever a
693 * toast, dialog or other window appears above the view's window.
694 * </p><p>
695 * For more fine-grained control over security, consider overriding the
696 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
697 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
698 * </p>
699 *
700 * @attr ref android.R.styleable#View_alpha
701 * @attr ref android.R.styleable#View_background
702 * @attr ref android.R.styleable#View_clickable
703 * @attr ref android.R.styleable#View_contentDescription
704 * @attr ref android.R.styleable#View_drawingCacheQuality
705 * @attr ref android.R.styleable#View_duplicateParentState
706 * @attr ref android.R.styleable#View_id
707 * @attr ref android.R.styleable#View_requiresFadingEdge
708 * @attr ref android.R.styleable#View_fadeScrollbars
709 * @attr ref android.R.styleable#View_fadingEdgeLength
710 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
711 * @attr ref android.R.styleable#View_fitsSystemWindows
712 * @attr ref android.R.styleable#View_isScrollContainer
713 * @attr ref android.R.styleable#View_focusable
714 * @attr ref android.R.styleable#View_focusableInTouchMode
715 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
716 * @attr ref android.R.styleable#View_keepScreenOn
717 * @attr ref android.R.styleable#View_layerType
718 * @attr ref android.R.styleable#View_layoutDirection
719 * @attr ref android.R.styleable#View_longClickable
720 * @attr ref android.R.styleable#View_minHeight
721 * @attr ref android.R.styleable#View_minWidth
722 * @attr ref android.R.styleable#View_nextFocusDown
723 * @attr ref android.R.styleable#View_nextFocusLeft
724 * @attr ref android.R.styleable#View_nextFocusRight
725 * @attr ref android.R.styleable#View_nextFocusUp
726 * @attr ref android.R.styleable#View_onClick
727 * @attr ref android.R.styleable#View_padding
728 * @attr ref android.R.styleable#View_paddingBottom
729 * @attr ref android.R.styleable#View_paddingLeft
730 * @attr ref android.R.styleable#View_paddingRight
731 * @attr ref android.R.styleable#View_paddingTop
732 * @attr ref android.R.styleable#View_paddingStart
733 * @attr ref android.R.styleable#View_paddingEnd
734 * @attr ref android.R.styleable#View_saveEnabled
735 * @attr ref android.R.styleable#View_rotation
736 * @attr ref android.R.styleable#View_rotationX
737 * @attr ref android.R.styleable#View_rotationY
738 * @attr ref android.R.styleable#View_scaleX
739 * @attr ref android.R.styleable#View_scaleY
740 * @attr ref android.R.styleable#View_scrollX
741 * @attr ref android.R.styleable#View_scrollY
742 * @attr ref android.R.styleable#View_scrollbarSize
743 * @attr ref android.R.styleable#View_scrollbarStyle
744 * @attr ref android.R.styleable#View_scrollbars
745 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
746 * @attr ref android.R.styleable#View_scrollbarFadeDuration
747 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
748 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
749 * @attr ref android.R.styleable#View_scrollbarThumbVertical
750 * @attr ref android.R.styleable#View_scrollbarTrackVertical
751 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
752 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
753 * @attr ref android.R.styleable#View_stateListAnimator
754 * @attr ref android.R.styleable#View_transitionName
755 * @attr ref android.R.styleable#View_soundEffectsEnabled
756 * @attr ref android.R.styleable#View_tag
757 * @attr ref android.R.styleable#View_textAlignment
758 * @attr ref android.R.styleable#View_textDirection
759 * @attr ref android.R.styleable#View_transformPivotX
760 * @attr ref android.R.styleable#View_transformPivotY
761 * @attr ref android.R.styleable#View_translationX
762 * @attr ref android.R.styleable#View_translationY
763 * @attr ref android.R.styleable#View_translationZ
764 * @attr ref android.R.styleable#View_visibility
765 * @attr ref android.R.styleable#View_theme
766 *
767 * @see android.view.ViewGroup
768 */
769@UiThread
770public class View implements Drawable.Callback, KeyEvent.Callback,
771        AccessibilityEventSource {
772    private static final boolean DBG = false;
773
774    /** @hide */
775    public static boolean DEBUG_DRAW = false;
776
777    /**
778     * The logging tag used by this class with android.util.Log.
779     */
780    protected static final String VIEW_LOG_TAG = "View";
781
782    /**
783     * When set to true, apps will draw debugging information about their layouts.
784     *
785     * @hide
786     */
787    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
788
789    /**
790     * When set to true, this view will save its attribute data.
791     *
792     * @hide
793     */
794    public static boolean mDebugViewAttributes = false;
795
796    /**
797     * Used to mark a View that has no ID.
798     */
799    public static final int NO_ID = -1;
800
801    /**
802     * Signals that compatibility booleans have been initialized according to
803     * target SDK versions.
804     */
805    private static boolean sCompatibilityDone = false;
806
807    /**
808     * Use the old (broken) way of building MeasureSpecs.
809     */
810    private static boolean sUseBrokenMakeMeasureSpec = false;
811
812    /**
813     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
814     */
815    static boolean sUseZeroUnspecifiedMeasureSpec = false;
816
817    /**
818     * Ignore any optimizations using the measure cache.
819     */
820    private static boolean sIgnoreMeasureCache = false;
821
822    /**
823     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
824     */
825    private static boolean sAlwaysRemeasureExactly = false;
826
827    /**
828     * Relax constraints around whether setLayoutParams() must be called after
829     * modifying the layout params.
830     */
831    private static boolean sLayoutParamsAlwaysChanged = false;
832
833    /**
834     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
835     * without throwing
836     */
837    static boolean sTextureViewIgnoresDrawableSetters = false;
838
839    /**
840     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
841     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
842     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
843     * check is implemented for backwards compatibility.
844     *
845     * {@hide}
846     */
847    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
848
849    /**
850     * Prior to N, when drag enters into child of a view that has already received an
851     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
852     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
853     * false from its event handler for these events.
854     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
855     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
856     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
857     */
858    static boolean sCascadedDragDrop;
859
860    /**
861     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
862     * calling setFlags.
863     */
864    private static final int NOT_FOCUSABLE = 0x00000000;
865
866    /**
867     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
868     * setFlags.
869     */
870    private static final int FOCUSABLE = 0x00000001;
871
872    /**
873     * Mask for use with setFlags indicating bits used for focus.
874     */
875    private static final int FOCUSABLE_MASK = 0x00000001;
876
877    /**
878     * This view will adjust its padding to fit sytem windows (e.g. status bar)
879     */
880    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
881
882    /** @hide */
883    @IntDef({VISIBLE, INVISIBLE, GONE})
884    @Retention(RetentionPolicy.SOURCE)
885    public @interface Visibility {}
886
887    /**
888     * This view is visible.
889     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
890     * android:visibility}.
891     */
892    public static final int VISIBLE = 0x00000000;
893
894    /**
895     * This view is invisible, but it still takes up space for layout purposes.
896     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
897     * android:visibility}.
898     */
899    public static final int INVISIBLE = 0x00000004;
900
901    /**
902     * This view is invisible, and it doesn't take any space for layout
903     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
904     * android:visibility}.
905     */
906    public static final int GONE = 0x00000008;
907
908    /**
909     * Mask for use with setFlags indicating bits used for visibility.
910     * {@hide}
911     */
912    static final int VISIBILITY_MASK = 0x0000000C;
913
914    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
915
916    /**
917     * This view is enabled. Interpretation varies by subclass.
918     * Use with ENABLED_MASK when calling setFlags.
919     * {@hide}
920     */
921    static final int ENABLED = 0x00000000;
922
923    /**
924     * This view is disabled. Interpretation varies by subclass.
925     * Use with ENABLED_MASK when calling setFlags.
926     * {@hide}
927     */
928    static final int DISABLED = 0x00000020;
929
930   /**
931    * Mask for use with setFlags indicating bits used for indicating whether
932    * this view is enabled
933    * {@hide}
934    */
935    static final int ENABLED_MASK = 0x00000020;
936
937    /**
938     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
939     * called and further optimizations will be performed. It is okay to have
940     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
941     * {@hide}
942     */
943    static final int WILL_NOT_DRAW = 0x00000080;
944
945    /**
946     * Mask for use with setFlags indicating bits used for indicating whether
947     * this view is will draw
948     * {@hide}
949     */
950    static final int DRAW_MASK = 0x00000080;
951
952    /**
953     * <p>This view doesn't show scrollbars.</p>
954     * {@hide}
955     */
956    static final int SCROLLBARS_NONE = 0x00000000;
957
958    /**
959     * <p>This view shows horizontal scrollbars.</p>
960     * {@hide}
961     */
962    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
963
964    /**
965     * <p>This view shows vertical scrollbars.</p>
966     * {@hide}
967     */
968    static final int SCROLLBARS_VERTICAL = 0x00000200;
969
970    /**
971     * <p>Mask for use with setFlags indicating bits used for indicating which
972     * scrollbars are enabled.</p>
973     * {@hide}
974     */
975    static final int SCROLLBARS_MASK = 0x00000300;
976
977    /**
978     * Indicates that the view should filter touches when its window is obscured.
979     * Refer to the class comments for more information about this security feature.
980     * {@hide}
981     */
982    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
983
984    /**
985     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
986     * that they are optional and should be skipped if the window has
987     * requested system UI flags that ignore those insets for layout.
988     */
989    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
990
991    /**
992     * <p>This view doesn't show fading edges.</p>
993     * {@hide}
994     */
995    static final int FADING_EDGE_NONE = 0x00000000;
996
997    /**
998     * <p>This view shows horizontal fading edges.</p>
999     * {@hide}
1000     */
1001    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1002
1003    /**
1004     * <p>This view shows vertical fading edges.</p>
1005     * {@hide}
1006     */
1007    static final int FADING_EDGE_VERTICAL = 0x00002000;
1008
1009    /**
1010     * <p>Mask for use with setFlags indicating bits used for indicating which
1011     * fading edges are enabled.</p>
1012     * {@hide}
1013     */
1014    static final int FADING_EDGE_MASK = 0x00003000;
1015
1016    /**
1017     * <p>Indicates this view can be clicked. When clickable, a View reacts
1018     * to clicks by notifying the OnClickListener.<p>
1019     * {@hide}
1020     */
1021    static final int CLICKABLE = 0x00004000;
1022
1023    /**
1024     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1025     * {@hide}
1026     */
1027    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1028
1029    /**
1030     * <p>Indicates that no icicle should be saved for this view.<p>
1031     * {@hide}
1032     */
1033    static final int SAVE_DISABLED = 0x000010000;
1034
1035    /**
1036     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1037     * property.</p>
1038     * {@hide}
1039     */
1040    static final int SAVE_DISABLED_MASK = 0x000010000;
1041
1042    /**
1043     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1044     * {@hide}
1045     */
1046    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1047
1048    /**
1049     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1050     * {@hide}
1051     */
1052    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1053
1054    /** @hide */
1055    @Retention(RetentionPolicy.SOURCE)
1056    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1057    public @interface DrawingCacheQuality {}
1058
1059    /**
1060     * <p>Enables low quality mode for the drawing cache.</p>
1061     */
1062    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1063
1064    /**
1065     * <p>Enables high quality mode for the drawing cache.</p>
1066     */
1067    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1068
1069    /**
1070     * <p>Enables automatic quality mode for the drawing cache.</p>
1071     */
1072    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1073
1074    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1075            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1076    };
1077
1078    /**
1079     * <p>Mask for use with setFlags indicating bits used for the cache
1080     * quality property.</p>
1081     * {@hide}
1082     */
1083    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1084
1085    /**
1086     * <p>
1087     * Indicates this view can be long clicked. When long clickable, a View
1088     * reacts to long clicks by notifying the OnLongClickListener or showing a
1089     * context menu.
1090     * </p>
1091     * {@hide}
1092     */
1093    static final int LONG_CLICKABLE = 0x00200000;
1094
1095    /**
1096     * <p>Indicates that this view gets its drawable states from its direct parent
1097     * and ignores its original internal states.</p>
1098     *
1099     * @hide
1100     */
1101    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1102
1103    /**
1104     * <p>
1105     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1106     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1107     * OnContextClickListener.
1108     * </p>
1109     * {@hide}
1110     */
1111    static final int CONTEXT_CLICKABLE = 0x00800000;
1112
1113
1114    /** @hide */
1115    @IntDef({
1116        SCROLLBARS_INSIDE_OVERLAY,
1117        SCROLLBARS_INSIDE_INSET,
1118        SCROLLBARS_OUTSIDE_OVERLAY,
1119        SCROLLBARS_OUTSIDE_INSET
1120    })
1121    @Retention(RetentionPolicy.SOURCE)
1122    public @interface ScrollBarStyle {}
1123
1124    /**
1125     * The scrollbar style to display the scrollbars inside the content area,
1126     * without increasing the padding. The scrollbars will be overlaid with
1127     * translucency on the view's content.
1128     */
1129    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1130
1131    /**
1132     * The scrollbar style to display the scrollbars inside the padded area,
1133     * increasing the padding of the view. The scrollbars will not overlap the
1134     * content area of the view.
1135     */
1136    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1137
1138    /**
1139     * The scrollbar style to display the scrollbars at the edge of the view,
1140     * without increasing the padding. The scrollbars will be overlaid with
1141     * translucency.
1142     */
1143    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1144
1145    /**
1146     * The scrollbar style to display the scrollbars at the edge of the view,
1147     * increasing the padding of the view. The scrollbars will only overlap the
1148     * background, if any.
1149     */
1150    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1151
1152    /**
1153     * Mask to check if the scrollbar style is overlay or inset.
1154     * {@hide}
1155     */
1156    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1157
1158    /**
1159     * Mask to check if the scrollbar style is inside or outside.
1160     * {@hide}
1161     */
1162    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1163
1164    /**
1165     * Mask for scrollbar style.
1166     * {@hide}
1167     */
1168    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1169
1170    /**
1171     * View flag indicating that the screen should remain on while the
1172     * window containing this view is visible to the user.  This effectively
1173     * takes care of automatically setting the WindowManager's
1174     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1175     */
1176    public static final int KEEP_SCREEN_ON = 0x04000000;
1177
1178    /**
1179     * View flag indicating whether this view should have sound effects enabled
1180     * for events such as clicking and touching.
1181     */
1182    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1183
1184    /**
1185     * View flag indicating whether this view should have haptic feedback
1186     * enabled for events such as long presses.
1187     */
1188    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1189
1190    /**
1191     * <p>Indicates that the view hierarchy should stop saving state when
1192     * it reaches this view.  If state saving is initiated immediately at
1193     * the view, it will be allowed.
1194     * {@hide}
1195     */
1196    static final int PARENT_SAVE_DISABLED = 0x20000000;
1197
1198    /**
1199     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1200     * {@hide}
1201     */
1202    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1203
1204    private static Paint sDebugPaint;
1205
1206    /**
1207     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1208     * {@hide}
1209     */
1210    static final int TOOLTIP = 0x40000000;
1211
1212    /** @hide */
1213    @IntDef(flag = true,
1214            value = {
1215                FOCUSABLES_ALL,
1216                FOCUSABLES_TOUCH_MODE
1217            })
1218    @Retention(RetentionPolicy.SOURCE)
1219    public @interface FocusableMode {}
1220
1221    /**
1222     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1223     * should add all focusable Views regardless if they are focusable in touch mode.
1224     */
1225    public static final int FOCUSABLES_ALL = 0x00000000;
1226
1227    /**
1228     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1229     * should add only Views focusable in touch mode.
1230     */
1231    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1232
1233    /** @hide */
1234    @IntDef({
1235            FOCUS_BACKWARD,
1236            FOCUS_FORWARD,
1237            FOCUS_LEFT,
1238            FOCUS_UP,
1239            FOCUS_RIGHT,
1240            FOCUS_DOWN
1241    })
1242    @Retention(RetentionPolicy.SOURCE)
1243    public @interface FocusDirection {}
1244
1245    /** @hide */
1246    @IntDef({
1247            FOCUS_LEFT,
1248            FOCUS_UP,
1249            FOCUS_RIGHT,
1250            FOCUS_DOWN
1251    })
1252    @Retention(RetentionPolicy.SOURCE)
1253    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1254
1255    /** @hide */
1256    @IntDef({
1257            KEYBOARD_NAVIGATION_GROUP_CLUSTER,
1258            KEYBOARD_NAVIGATION_GROUP_SECTION
1259    })
1260    @Retention(RetentionPolicy.SOURCE)
1261    public @interface KeyboardNavigationGroupType {}
1262
1263    /**
1264     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1265     * item.
1266     */
1267    public static final int FOCUS_BACKWARD = 0x00000001;
1268
1269    /**
1270     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1271     * item.
1272     */
1273    public static final int FOCUS_FORWARD = 0x00000002;
1274
1275    /**
1276     * Use with {@link #focusSearch(int)}. Move focus to the left.
1277     */
1278    public static final int FOCUS_LEFT = 0x00000011;
1279
1280    /**
1281     * Use with {@link #focusSearch(int)}. Move focus up.
1282     */
1283    public static final int FOCUS_UP = 0x00000021;
1284
1285    /**
1286     * Use with {@link #focusSearch(int)}. Move focus to the right.
1287     */
1288    public static final int FOCUS_RIGHT = 0x00000042;
1289
1290    /**
1291     * Use with {@link #focusSearch(int)}. Move focus down.
1292     */
1293    public static final int FOCUS_DOWN = 0x00000082;
1294
1295    /**
1296     * Use with {@link #keyboardNavigationGroupSearch(int, View, int)}. Search for a keyboard
1297     * navigation cluster.
1298     */
1299    public static final int KEYBOARD_NAVIGATION_GROUP_CLUSTER = 1;
1300
1301    /**
1302     * Use with {@link #keyboardNavigationGroupSearch(int, View, int)}. Search for a keyboard
1303     * navigation section.
1304     */
1305    public static final int KEYBOARD_NAVIGATION_GROUP_SECTION = 2;
1306
1307    /**
1308     * Bits of {@link #getMeasuredWidthAndState()} and
1309     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1310     */
1311    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1312
1313    /**
1314     * Bits of {@link #getMeasuredWidthAndState()} and
1315     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1316     */
1317    public static final int MEASURED_STATE_MASK = 0xff000000;
1318
1319    /**
1320     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1321     * for functions that combine both width and height into a single int,
1322     * such as {@link #getMeasuredState()} and the childState argument of
1323     * {@link #resolveSizeAndState(int, int, int)}.
1324     */
1325    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1326
1327    /**
1328     * Bit of {@link #getMeasuredWidthAndState()} and
1329     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1330     * is smaller that the space the view would like to have.
1331     */
1332    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1333
1334    /**
1335     * Base View state sets
1336     */
1337    // Singles
1338    /**
1339     * Indicates the view has no states set. States are used with
1340     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1341     * view depending on its state.
1342     *
1343     * @see android.graphics.drawable.Drawable
1344     * @see #getDrawableState()
1345     */
1346    protected static final int[] EMPTY_STATE_SET;
1347    /**
1348     * Indicates the view is enabled. States are used with
1349     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1350     * view depending on its state.
1351     *
1352     * @see android.graphics.drawable.Drawable
1353     * @see #getDrawableState()
1354     */
1355    protected static final int[] ENABLED_STATE_SET;
1356    /**
1357     * Indicates the view is focused. States are used with
1358     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1359     * view depending on its state.
1360     *
1361     * @see android.graphics.drawable.Drawable
1362     * @see #getDrawableState()
1363     */
1364    protected static final int[] FOCUSED_STATE_SET;
1365    /**
1366     * Indicates the view is selected. States are used with
1367     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1368     * view depending on its state.
1369     *
1370     * @see android.graphics.drawable.Drawable
1371     * @see #getDrawableState()
1372     */
1373    protected static final int[] SELECTED_STATE_SET;
1374    /**
1375     * Indicates the view is pressed. States are used with
1376     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1377     * view depending on its state.
1378     *
1379     * @see android.graphics.drawable.Drawable
1380     * @see #getDrawableState()
1381     */
1382    protected static final int[] PRESSED_STATE_SET;
1383    /**
1384     * Indicates the view's window has focus. States are used with
1385     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1386     * view depending on its state.
1387     *
1388     * @see android.graphics.drawable.Drawable
1389     * @see #getDrawableState()
1390     */
1391    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1392    // Doubles
1393    /**
1394     * Indicates the view is enabled and has the focus.
1395     *
1396     * @see #ENABLED_STATE_SET
1397     * @see #FOCUSED_STATE_SET
1398     */
1399    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1400    /**
1401     * Indicates the view is enabled and selected.
1402     *
1403     * @see #ENABLED_STATE_SET
1404     * @see #SELECTED_STATE_SET
1405     */
1406    protected static final int[] ENABLED_SELECTED_STATE_SET;
1407    /**
1408     * Indicates the view is enabled and that its window has focus.
1409     *
1410     * @see #ENABLED_STATE_SET
1411     * @see #WINDOW_FOCUSED_STATE_SET
1412     */
1413    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1414    /**
1415     * Indicates the view is focused and selected.
1416     *
1417     * @see #FOCUSED_STATE_SET
1418     * @see #SELECTED_STATE_SET
1419     */
1420    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1421    /**
1422     * Indicates the view has the focus and that its window has the focus.
1423     *
1424     * @see #FOCUSED_STATE_SET
1425     * @see #WINDOW_FOCUSED_STATE_SET
1426     */
1427    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1428    /**
1429     * Indicates the view is selected and that its window has the focus.
1430     *
1431     * @see #SELECTED_STATE_SET
1432     * @see #WINDOW_FOCUSED_STATE_SET
1433     */
1434    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1435    // Triples
1436    /**
1437     * Indicates the view is enabled, focused and selected.
1438     *
1439     * @see #ENABLED_STATE_SET
1440     * @see #FOCUSED_STATE_SET
1441     * @see #SELECTED_STATE_SET
1442     */
1443    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1444    /**
1445     * Indicates the view is enabled, focused and its window has the focus.
1446     *
1447     * @see #ENABLED_STATE_SET
1448     * @see #FOCUSED_STATE_SET
1449     * @see #WINDOW_FOCUSED_STATE_SET
1450     */
1451    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1452    /**
1453     * Indicates the view is enabled, selected and its window has the focus.
1454     *
1455     * @see #ENABLED_STATE_SET
1456     * @see #SELECTED_STATE_SET
1457     * @see #WINDOW_FOCUSED_STATE_SET
1458     */
1459    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1460    /**
1461     * Indicates the view is focused, selected and its window has the focus.
1462     *
1463     * @see #FOCUSED_STATE_SET
1464     * @see #SELECTED_STATE_SET
1465     * @see #WINDOW_FOCUSED_STATE_SET
1466     */
1467    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1468    /**
1469     * Indicates the view is enabled, focused, selected and its window
1470     * has the focus.
1471     *
1472     * @see #ENABLED_STATE_SET
1473     * @see #FOCUSED_STATE_SET
1474     * @see #SELECTED_STATE_SET
1475     * @see #WINDOW_FOCUSED_STATE_SET
1476     */
1477    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1478    /**
1479     * Indicates the view is pressed and its window has the focus.
1480     *
1481     * @see #PRESSED_STATE_SET
1482     * @see #WINDOW_FOCUSED_STATE_SET
1483     */
1484    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1485    /**
1486     * Indicates the view is pressed and selected.
1487     *
1488     * @see #PRESSED_STATE_SET
1489     * @see #SELECTED_STATE_SET
1490     */
1491    protected static final int[] PRESSED_SELECTED_STATE_SET;
1492    /**
1493     * Indicates the view is pressed, selected and its window has the focus.
1494     *
1495     * @see #PRESSED_STATE_SET
1496     * @see #SELECTED_STATE_SET
1497     * @see #WINDOW_FOCUSED_STATE_SET
1498     */
1499    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1500    /**
1501     * Indicates the view is pressed and focused.
1502     *
1503     * @see #PRESSED_STATE_SET
1504     * @see #FOCUSED_STATE_SET
1505     */
1506    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1507    /**
1508     * Indicates the view is pressed, focused and its window has the focus.
1509     *
1510     * @see #PRESSED_STATE_SET
1511     * @see #FOCUSED_STATE_SET
1512     * @see #WINDOW_FOCUSED_STATE_SET
1513     */
1514    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1515    /**
1516     * Indicates the view is pressed, focused and selected.
1517     *
1518     * @see #PRESSED_STATE_SET
1519     * @see #SELECTED_STATE_SET
1520     * @see #FOCUSED_STATE_SET
1521     */
1522    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1523    /**
1524     * Indicates the view is pressed, focused, selected and its window has the focus.
1525     *
1526     * @see #PRESSED_STATE_SET
1527     * @see #FOCUSED_STATE_SET
1528     * @see #SELECTED_STATE_SET
1529     * @see #WINDOW_FOCUSED_STATE_SET
1530     */
1531    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1532    /**
1533     * Indicates the view is pressed and enabled.
1534     *
1535     * @see #PRESSED_STATE_SET
1536     * @see #ENABLED_STATE_SET
1537     */
1538    protected static final int[] PRESSED_ENABLED_STATE_SET;
1539    /**
1540     * Indicates the view is pressed, enabled and its window has the focus.
1541     *
1542     * @see #PRESSED_STATE_SET
1543     * @see #ENABLED_STATE_SET
1544     * @see #WINDOW_FOCUSED_STATE_SET
1545     */
1546    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1547    /**
1548     * Indicates the view is pressed, enabled and selected.
1549     *
1550     * @see #PRESSED_STATE_SET
1551     * @see #ENABLED_STATE_SET
1552     * @see #SELECTED_STATE_SET
1553     */
1554    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1555    /**
1556     * Indicates the view is pressed, enabled, selected and its window has the
1557     * focus.
1558     *
1559     * @see #PRESSED_STATE_SET
1560     * @see #ENABLED_STATE_SET
1561     * @see #SELECTED_STATE_SET
1562     * @see #WINDOW_FOCUSED_STATE_SET
1563     */
1564    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1565    /**
1566     * Indicates the view is pressed, enabled and focused.
1567     *
1568     * @see #PRESSED_STATE_SET
1569     * @see #ENABLED_STATE_SET
1570     * @see #FOCUSED_STATE_SET
1571     */
1572    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1573    /**
1574     * Indicates the view is pressed, enabled, focused and its window has the
1575     * focus.
1576     *
1577     * @see #PRESSED_STATE_SET
1578     * @see #ENABLED_STATE_SET
1579     * @see #FOCUSED_STATE_SET
1580     * @see #WINDOW_FOCUSED_STATE_SET
1581     */
1582    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1583    /**
1584     * Indicates the view is pressed, enabled, focused and selected.
1585     *
1586     * @see #PRESSED_STATE_SET
1587     * @see #ENABLED_STATE_SET
1588     * @see #SELECTED_STATE_SET
1589     * @see #FOCUSED_STATE_SET
1590     */
1591    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1592    /**
1593     * Indicates the view is pressed, enabled, focused, selected and its window
1594     * has the focus.
1595     *
1596     * @see #PRESSED_STATE_SET
1597     * @see #ENABLED_STATE_SET
1598     * @see #SELECTED_STATE_SET
1599     * @see #FOCUSED_STATE_SET
1600     * @see #WINDOW_FOCUSED_STATE_SET
1601     */
1602    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1603
1604    static {
1605        EMPTY_STATE_SET = StateSet.get(0);
1606
1607        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1608
1609        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1610        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1611                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1612
1613        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1614        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1615                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1616        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1617                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1618        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1619                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1620                        | StateSet.VIEW_STATE_FOCUSED);
1621
1622        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1623        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1624                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1625        ENABLED_SELECTED_STATE_SET = StateSet.get(
1626                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1627        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1628                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1629                        | StateSet.VIEW_STATE_ENABLED);
1630        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1631                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1632        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1633                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1634                        | StateSet.VIEW_STATE_ENABLED);
1635        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1636                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1637                        | StateSet.VIEW_STATE_ENABLED);
1638        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1639                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1640                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1641
1642        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1643        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1644                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1645        PRESSED_SELECTED_STATE_SET = StateSet.get(
1646                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1647        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1648                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1649                        | StateSet.VIEW_STATE_PRESSED);
1650        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1651                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1652        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1653                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1654                        | StateSet.VIEW_STATE_PRESSED);
1655        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1656                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1657                        | StateSet.VIEW_STATE_PRESSED);
1658        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1659                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1660                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1661        PRESSED_ENABLED_STATE_SET = StateSet.get(
1662                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1663        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1664                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1665                        | StateSet.VIEW_STATE_PRESSED);
1666        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1667                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1668                        | StateSet.VIEW_STATE_PRESSED);
1669        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1670                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1671                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1672        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1673                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1674                        | StateSet.VIEW_STATE_PRESSED);
1675        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1676                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1677                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1678        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1679                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1680                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1681        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1682                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1683                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1684                        | StateSet.VIEW_STATE_PRESSED);
1685    }
1686
1687    /**
1688     * Accessibility event types that are dispatched for text population.
1689     */
1690    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1691            AccessibilityEvent.TYPE_VIEW_CLICKED
1692            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1693            | AccessibilityEvent.TYPE_VIEW_SELECTED
1694            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1695            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1696            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1697            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1698            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1699            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1700            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1701            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1702
1703    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
1704
1705    static final int DEBUG_CORNERS_SIZE_DIP = 8;
1706
1707    /**
1708     * Temporary Rect currently for use in setBackground().  This will probably
1709     * be extended in the future to hold our own class with more than just
1710     * a Rect. :)
1711     */
1712    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1713
1714    /**
1715     * Map used to store views' tags.
1716     */
1717    private SparseArray<Object> mKeyedTags;
1718
1719    /**
1720     * The next available accessibility id.
1721     */
1722    private static int sNextAccessibilityViewId;
1723
1724    /**
1725     * The animation currently associated with this view.
1726     * @hide
1727     */
1728    protected Animation mCurrentAnimation = null;
1729
1730    /**
1731     * Width as measured during measure pass.
1732     * {@hide}
1733     */
1734    @ViewDebug.ExportedProperty(category = "measurement")
1735    int mMeasuredWidth;
1736
1737    /**
1738     * Height as measured during measure pass.
1739     * {@hide}
1740     */
1741    @ViewDebug.ExportedProperty(category = "measurement")
1742    int mMeasuredHeight;
1743
1744    /**
1745     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1746     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1747     * its display list. This flag, used only when hw accelerated, allows us to clear the
1748     * flag while retaining this information until it's needed (at getDisplayList() time and
1749     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1750     *
1751     * {@hide}
1752     */
1753    boolean mRecreateDisplayList = false;
1754
1755    /**
1756     * The view's identifier.
1757     * {@hide}
1758     *
1759     * @see #setId(int)
1760     * @see #getId()
1761     */
1762    @IdRes
1763    @ViewDebug.ExportedProperty(resolveId = true)
1764    int mID = NO_ID;
1765
1766    /**
1767     * The stable ID of this view for accessibility purposes.
1768     */
1769    int mAccessibilityViewId = NO_ID;
1770
1771    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1772
1773    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1774
1775    /**
1776     * The view's tag.
1777     * {@hide}
1778     *
1779     * @see #setTag(Object)
1780     * @see #getTag()
1781     */
1782    protected Object mTag = null;
1783
1784    // for mPrivateFlags:
1785    /** {@hide} */
1786    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1787    /** {@hide} */
1788    static final int PFLAG_FOCUSED                     = 0x00000002;
1789    /** {@hide} */
1790    static final int PFLAG_SELECTED                    = 0x00000004;
1791    /** {@hide} */
1792    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1793    /** {@hide} */
1794    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1795    /** {@hide} */
1796    static final int PFLAG_DRAWN                       = 0x00000020;
1797    /**
1798     * When this flag is set, this view is running an animation on behalf of its
1799     * children and should therefore not cancel invalidate requests, even if they
1800     * lie outside of this view's bounds.
1801     *
1802     * {@hide}
1803     */
1804    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1805    /** {@hide} */
1806    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1807    /** {@hide} */
1808    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1809    /** {@hide} */
1810    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1811    /** {@hide} */
1812    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1813    /** {@hide} */
1814    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1815    /** {@hide} */
1816    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1817
1818    private static final int PFLAG_PRESSED             = 0x00004000;
1819
1820    /** {@hide} */
1821    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1822    /**
1823     * Flag used to indicate that this view should be drawn once more (and only once
1824     * more) after its animation has completed.
1825     * {@hide}
1826     */
1827    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1828
1829    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1830
1831    /**
1832     * Indicates that the View returned true when onSetAlpha() was called and that
1833     * the alpha must be restored.
1834     * {@hide}
1835     */
1836    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1837
1838    /**
1839     * Set by {@link #setScrollContainer(boolean)}.
1840     */
1841    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1842
1843    /**
1844     * Set by {@link #setScrollContainer(boolean)}.
1845     */
1846    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1847
1848    /**
1849     * View flag indicating whether this view was invalidated (fully or partially.)
1850     *
1851     * @hide
1852     */
1853    static final int PFLAG_DIRTY                       = 0x00200000;
1854
1855    /**
1856     * View flag indicating whether this view was invalidated by an opaque
1857     * invalidate request.
1858     *
1859     * @hide
1860     */
1861    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1862
1863    /**
1864     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1865     *
1866     * @hide
1867     */
1868    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1869
1870    /**
1871     * Indicates whether the background is opaque.
1872     *
1873     * @hide
1874     */
1875    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1876
1877    /**
1878     * Indicates whether the scrollbars are opaque.
1879     *
1880     * @hide
1881     */
1882    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1883
1884    /**
1885     * Indicates whether the view is opaque.
1886     *
1887     * @hide
1888     */
1889    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1890
1891    /**
1892     * Indicates a prepressed state;
1893     * the short time between ACTION_DOWN and recognizing
1894     * a 'real' press. Prepressed is used to recognize quick taps
1895     * even when they are shorter than ViewConfiguration.getTapTimeout().
1896     *
1897     * @hide
1898     */
1899    private static final int PFLAG_PREPRESSED          = 0x02000000;
1900
1901    /**
1902     * Indicates whether the view is temporarily detached.
1903     *
1904     * @hide
1905     */
1906    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1907
1908    /**
1909     * Indicates that we should awaken scroll bars once attached
1910     *
1911     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1912     * during window attachment and it is no longer needed. Feel free to repurpose it.
1913     *
1914     * @hide
1915     */
1916    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1917
1918    /**
1919     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1920     * @hide
1921     */
1922    private static final int PFLAG_HOVERED             = 0x10000000;
1923
1924    /**
1925     * no longer needed, should be reused
1926     */
1927    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1928
1929    /** {@hide} */
1930    static final int PFLAG_ACTIVATED                   = 0x40000000;
1931
1932    /**
1933     * Indicates that this view was specifically invalidated, not just dirtied because some
1934     * child view was invalidated. The flag is used to determine when we need to recreate
1935     * a view's display list (as opposed to just returning a reference to its existing
1936     * display list).
1937     *
1938     * @hide
1939     */
1940    static final int PFLAG_INVALIDATED                 = 0x80000000;
1941
1942    /**
1943     * Masks for mPrivateFlags2, as generated by dumpFlags():
1944     *
1945     * |-------|-------|-------|-------|
1946     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1947     *                                1  PFLAG2_DRAG_HOVERED
1948     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1949     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1950     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1951     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1952     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1953     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1954     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1955     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1956     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1957     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1958     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1959     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1960     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1961     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1962     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1963     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1964     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1965     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1966     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1967     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1968     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1969     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1970     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1971     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1972     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1973     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1974     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1975     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1976     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1977     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1978     *    1                              PFLAG2_PADDING_RESOLVED
1979     *   1                               PFLAG2_DRAWABLE_RESOLVED
1980     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1981     * |-------|-------|-------|-------|
1982     */
1983
1984    /**
1985     * Indicates that this view has reported that it can accept the current drag's content.
1986     * Cleared when the drag operation concludes.
1987     * @hide
1988     */
1989    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1990
1991    /**
1992     * Indicates that this view is currently directly under the drag location in a
1993     * drag-and-drop operation involving content that it can accept.  Cleared when
1994     * the drag exits the view, or when the drag operation concludes.
1995     * @hide
1996     */
1997    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1998
1999    /** @hide */
2000    @IntDef({
2001        LAYOUT_DIRECTION_LTR,
2002        LAYOUT_DIRECTION_RTL,
2003        LAYOUT_DIRECTION_INHERIT,
2004        LAYOUT_DIRECTION_LOCALE
2005    })
2006    @Retention(RetentionPolicy.SOURCE)
2007    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2008    public @interface LayoutDir {}
2009
2010    /** @hide */
2011    @IntDef({
2012        LAYOUT_DIRECTION_LTR,
2013        LAYOUT_DIRECTION_RTL
2014    })
2015    @Retention(RetentionPolicy.SOURCE)
2016    public @interface ResolvedLayoutDir {}
2017
2018    /**
2019     * A flag to indicate that the layout direction of this view has not been defined yet.
2020     * @hide
2021     */
2022    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2023
2024    /**
2025     * Horizontal layout direction of this view is from Left to Right.
2026     * Use with {@link #setLayoutDirection}.
2027     */
2028    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2029
2030    /**
2031     * Horizontal layout direction of this view is from Right to Left.
2032     * Use with {@link #setLayoutDirection}.
2033     */
2034    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2035
2036    /**
2037     * Horizontal layout direction of this view is inherited from its parent.
2038     * Use with {@link #setLayoutDirection}.
2039     */
2040    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2041
2042    /**
2043     * Horizontal layout direction of this view is from deduced from the default language
2044     * script for the locale. Use with {@link #setLayoutDirection}.
2045     */
2046    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2047
2048    /**
2049     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2050     * @hide
2051     */
2052    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2053
2054    /**
2055     * Mask for use with private flags indicating bits used for horizontal layout direction.
2056     * @hide
2057     */
2058    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2059
2060    /**
2061     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2062     * right-to-left direction.
2063     * @hide
2064     */
2065    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2066
2067    /**
2068     * Indicates whether the view horizontal layout direction has been resolved.
2069     * @hide
2070     */
2071    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2072
2073    /**
2074     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2075     * @hide
2076     */
2077    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2078            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2079
2080    /*
2081     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2082     * flag value.
2083     * @hide
2084     */
2085    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2086            LAYOUT_DIRECTION_LTR,
2087            LAYOUT_DIRECTION_RTL,
2088            LAYOUT_DIRECTION_INHERIT,
2089            LAYOUT_DIRECTION_LOCALE
2090    };
2091
2092    /**
2093     * Default horizontal layout direction.
2094     */
2095    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2096
2097    /**
2098     * Default horizontal layout direction.
2099     * @hide
2100     */
2101    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2102
2103    /**
2104     * Text direction is inherited through {@link ViewGroup}
2105     */
2106    public static final int TEXT_DIRECTION_INHERIT = 0;
2107
2108    /**
2109     * Text direction is using "first strong algorithm". The first strong directional character
2110     * determines the paragraph direction. If there is no strong directional character, the
2111     * paragraph direction is the view's resolved layout direction.
2112     */
2113    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2114
2115    /**
2116     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2117     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2118     * If there are neither, the paragraph direction is the view's resolved layout direction.
2119     */
2120    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2121
2122    /**
2123     * Text direction is forced to LTR.
2124     */
2125    public static final int TEXT_DIRECTION_LTR = 3;
2126
2127    /**
2128     * Text direction is forced to RTL.
2129     */
2130    public static final int TEXT_DIRECTION_RTL = 4;
2131
2132    /**
2133     * Text direction is coming from the system Locale.
2134     */
2135    public static final int TEXT_DIRECTION_LOCALE = 5;
2136
2137    /**
2138     * Text direction is using "first strong algorithm". The first strong directional character
2139     * determines the paragraph direction. If there is no strong directional character, the
2140     * paragraph direction is LTR.
2141     */
2142    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2143
2144    /**
2145     * Text direction is using "first strong algorithm". The first strong directional character
2146     * determines the paragraph direction. If there is no strong directional character, the
2147     * paragraph direction is RTL.
2148     */
2149    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2150
2151    /**
2152     * Default text direction is inherited
2153     */
2154    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2155
2156    /**
2157     * Default resolved text direction
2158     * @hide
2159     */
2160    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2161
2162    /**
2163     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2164     * @hide
2165     */
2166    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2167
2168    /**
2169     * Mask for use with private flags indicating bits used for text direction.
2170     * @hide
2171     */
2172    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2173            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2174
2175    /**
2176     * Array of text direction flags for mapping attribute "textDirection" to correct
2177     * flag value.
2178     * @hide
2179     */
2180    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2181            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2182            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2183            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2184            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2185            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2186            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2187            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2188            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2189    };
2190
2191    /**
2192     * Indicates whether the view text direction has been resolved.
2193     * @hide
2194     */
2195    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2196            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2197
2198    /**
2199     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2200     * @hide
2201     */
2202    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2203
2204    /**
2205     * Mask for use with private flags indicating bits used for resolved text direction.
2206     * @hide
2207     */
2208    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2209            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2210
2211    /**
2212     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2213     * @hide
2214     */
2215    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2216            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2217
2218    /** @hide */
2219    @IntDef({
2220        TEXT_ALIGNMENT_INHERIT,
2221        TEXT_ALIGNMENT_GRAVITY,
2222        TEXT_ALIGNMENT_CENTER,
2223        TEXT_ALIGNMENT_TEXT_START,
2224        TEXT_ALIGNMENT_TEXT_END,
2225        TEXT_ALIGNMENT_VIEW_START,
2226        TEXT_ALIGNMENT_VIEW_END
2227    })
2228    @Retention(RetentionPolicy.SOURCE)
2229    public @interface TextAlignment {}
2230
2231    /**
2232     * Default text alignment. The text alignment of this View is inherited from its parent.
2233     * Use with {@link #setTextAlignment(int)}
2234     */
2235    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2236
2237    /**
2238     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2239     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2240     *
2241     * Use with {@link #setTextAlignment(int)}
2242     */
2243    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2244
2245    /**
2246     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2247     *
2248     * Use with {@link #setTextAlignment(int)}
2249     */
2250    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2251
2252    /**
2253     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2254     *
2255     * Use with {@link #setTextAlignment(int)}
2256     */
2257    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2258
2259    /**
2260     * Center the paragraph, e.g. ALIGN_CENTER.
2261     *
2262     * Use with {@link #setTextAlignment(int)}
2263     */
2264    public static final int TEXT_ALIGNMENT_CENTER = 4;
2265
2266    /**
2267     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2268     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2269     *
2270     * Use with {@link #setTextAlignment(int)}
2271     */
2272    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2273
2274    /**
2275     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2276     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2277     *
2278     * Use with {@link #setTextAlignment(int)}
2279     */
2280    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2281
2282    /**
2283     * Default text alignment is inherited
2284     */
2285    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2286
2287    /**
2288     * Default resolved text alignment
2289     * @hide
2290     */
2291    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2292
2293    /**
2294      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2295      * @hide
2296      */
2297    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2298
2299    /**
2300      * Mask for use with private flags indicating bits used for text alignment.
2301      * @hide
2302      */
2303    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2304
2305    /**
2306     * Array of text direction flags for mapping attribute "textAlignment" to correct
2307     * flag value.
2308     * @hide
2309     */
2310    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2311            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2312            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2313            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2314            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2315            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2316            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2317            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2318    };
2319
2320    /**
2321     * Indicates whether the view text alignment has been resolved.
2322     * @hide
2323     */
2324    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2325
2326    /**
2327     * Bit shift to get the resolved text alignment.
2328     * @hide
2329     */
2330    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2331
2332    /**
2333     * Mask for use with private flags indicating bits used for text alignment.
2334     * @hide
2335     */
2336    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2337            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2338
2339    /**
2340     * Indicates whether if the view text alignment has been resolved to gravity
2341     */
2342    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2343            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2344
2345    // Accessiblity constants for mPrivateFlags2
2346
2347    /**
2348     * Shift for the bits in {@link #mPrivateFlags2} related to the
2349     * "importantForAccessibility" attribute.
2350     */
2351    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2352
2353    /**
2354     * Automatically determine whether a view is important for accessibility.
2355     */
2356    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2357
2358    /**
2359     * The view is important for accessibility.
2360     */
2361    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2362
2363    /**
2364     * The view is not important for accessibility.
2365     */
2366    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2367
2368    /**
2369     * The view is not important for accessibility, nor are any of its
2370     * descendant views.
2371     */
2372    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2373
2374    /**
2375     * The default whether the view is important for accessibility.
2376     */
2377    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2378
2379    /**
2380     * Mask for obtaining the bits which specify how to determine
2381     * whether a view is important for accessibility.
2382     */
2383    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2384        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2385        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2386        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2387
2388    /**
2389     * Shift for the bits in {@link #mPrivateFlags2} related to the
2390     * "accessibilityLiveRegion" attribute.
2391     */
2392    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2393
2394    /**
2395     * Live region mode specifying that accessibility services should not
2396     * automatically announce changes to this view. This is the default live
2397     * region mode for most views.
2398     * <p>
2399     * Use with {@link #setAccessibilityLiveRegion(int)}.
2400     */
2401    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2402
2403    /**
2404     * Live region mode specifying that accessibility services should announce
2405     * changes to this view.
2406     * <p>
2407     * Use with {@link #setAccessibilityLiveRegion(int)}.
2408     */
2409    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2410
2411    /**
2412     * Live region mode specifying that accessibility services should interrupt
2413     * ongoing speech to immediately announce changes to this view.
2414     * <p>
2415     * Use with {@link #setAccessibilityLiveRegion(int)}.
2416     */
2417    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2418
2419    /**
2420     * The default whether the view is important for accessibility.
2421     */
2422    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2423
2424    /**
2425     * Mask for obtaining the bits which specify a view's accessibility live
2426     * region mode.
2427     */
2428    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2429            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2430            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2431
2432    /**
2433     * Flag indicating whether a view has accessibility focus.
2434     */
2435    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2436
2437    /**
2438     * Flag whether the accessibility state of the subtree rooted at this view changed.
2439     */
2440    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2441
2442    /**
2443     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2444     * is used to check whether later changes to the view's transform should invalidate the
2445     * view to force the quickReject test to run again.
2446     */
2447    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2448
2449    /**
2450     * Flag indicating that start/end padding has been resolved into left/right padding
2451     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2452     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2453     * during measurement. In some special cases this is required such as when an adapter-based
2454     * view measures prospective children without attaching them to a window.
2455     */
2456    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2457
2458    /**
2459     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2460     */
2461    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2462
2463    /**
2464     * Indicates that the view is tracking some sort of transient state
2465     * that the app should not need to be aware of, but that the framework
2466     * should take special care to preserve.
2467     */
2468    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2469
2470    /**
2471     * Group of bits indicating that RTL properties resolution is done.
2472     */
2473    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2474            PFLAG2_TEXT_DIRECTION_RESOLVED |
2475            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2476            PFLAG2_PADDING_RESOLVED |
2477            PFLAG2_DRAWABLE_RESOLVED;
2478
2479    // There are a couple of flags left in mPrivateFlags2
2480
2481    /* End of masks for mPrivateFlags2 */
2482
2483    /**
2484     * Masks for mPrivateFlags3, as generated by dumpFlags():
2485     *
2486     * |-------|-------|-------|-------|
2487     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2488     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2489     *                               1   PFLAG3_IS_LAID_OUT
2490     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2491     *                             1     PFLAG3_CALLED_SUPER
2492     *                            1      PFLAG3_APPLYING_INSETS
2493     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2494     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2495     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2496     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2497     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2498     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2499     *                     1             PFLAG3_SCROLL_INDICATOR_START
2500     *                    1              PFLAG3_SCROLL_INDICATOR_END
2501     *                   1               PFLAG3_ASSIST_BLOCKED
2502     *                  1                PFLAG3_CLUSTER
2503     *                 1                 PFLAG3_SECTION
2504     *                1                  PFLAG3_FINGER_DOWN
2505     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2506     *           xxxx                    * NO LONGER NEEDED, SHOULD BE REUSED *
2507     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2508     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2509     *        1                          PFLAG3_TEMPORARY_DETACH
2510     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2511     * |-------|-------|-------|-------|
2512     */
2513
2514    /**
2515     * Flag indicating that view has a transform animation set on it. This is used to track whether
2516     * an animation is cleared between successive frames, in order to tell the associated
2517     * DisplayList to clear its animation matrix.
2518     */
2519    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2520
2521    /**
2522     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2523     * animation is cleared between successive frames, in order to tell the associated
2524     * DisplayList to restore its alpha value.
2525     */
2526    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2527
2528    /**
2529     * Flag indicating that the view has been through at least one layout since it
2530     * was last attached to a window.
2531     */
2532    static final int PFLAG3_IS_LAID_OUT = 0x4;
2533
2534    /**
2535     * Flag indicating that a call to measure() was skipped and should be done
2536     * instead when layout() is invoked.
2537     */
2538    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2539
2540    /**
2541     * Flag indicating that an overridden method correctly called down to
2542     * the superclass implementation as required by the API spec.
2543     */
2544    static final int PFLAG3_CALLED_SUPER = 0x10;
2545
2546    /**
2547     * Flag indicating that we're in the process of applying window insets.
2548     */
2549    static final int PFLAG3_APPLYING_INSETS = 0x20;
2550
2551    /**
2552     * Flag indicating that we're in the process of fitting system windows using the old method.
2553     */
2554    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2555
2556    /**
2557     * Flag indicating that nested scrolling is enabled for this view.
2558     * The view will optionally cooperate with views up its parent chain to allow for
2559     * integrated nested scrolling along the same axis.
2560     */
2561    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2562
2563    /**
2564     * Flag indicating that the bottom scroll indicator should be displayed
2565     * when this view can scroll up.
2566     */
2567    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2568
2569    /**
2570     * Flag indicating that the bottom scroll indicator should be displayed
2571     * when this view can scroll down.
2572     */
2573    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2574
2575    /**
2576     * Flag indicating that the left scroll indicator should be displayed
2577     * when this view can scroll left.
2578     */
2579    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2580
2581    /**
2582     * Flag indicating that the right scroll indicator should be displayed
2583     * when this view can scroll right.
2584     */
2585    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2586
2587    /**
2588     * Flag indicating that the start scroll indicator should be displayed
2589     * when this view can scroll in the start direction.
2590     */
2591    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2592
2593    /**
2594     * Flag indicating that the end scroll indicator should be displayed
2595     * when this view can scroll in the end direction.
2596     */
2597    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2598
2599    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2600
2601    static final int SCROLL_INDICATORS_NONE = 0x0000;
2602
2603    /**
2604     * Mask for use with setFlags indicating bits used for indicating which
2605     * scroll indicators are enabled.
2606     */
2607    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2608            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2609            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2610            | PFLAG3_SCROLL_INDICATOR_END;
2611
2612    /**
2613     * Left-shift required to translate between public scroll indicator flags
2614     * and internal PFLAGS3 flags. When used as a right-shift, translates
2615     * PFLAGS3 flags to public flags.
2616     */
2617    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2618
2619    /** @hide */
2620    @Retention(RetentionPolicy.SOURCE)
2621    @IntDef(flag = true,
2622            value = {
2623                    SCROLL_INDICATOR_TOP,
2624                    SCROLL_INDICATOR_BOTTOM,
2625                    SCROLL_INDICATOR_LEFT,
2626                    SCROLL_INDICATOR_RIGHT,
2627                    SCROLL_INDICATOR_START,
2628                    SCROLL_INDICATOR_END,
2629            })
2630    public @interface ScrollIndicators {}
2631
2632    /**
2633     * Scroll indicator direction for the top edge of the view.
2634     *
2635     * @see #setScrollIndicators(int)
2636     * @see #setScrollIndicators(int, int)
2637     * @see #getScrollIndicators()
2638     */
2639    public static final int SCROLL_INDICATOR_TOP =
2640            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2641
2642    /**
2643     * Scroll indicator direction for the bottom edge of the view.
2644     *
2645     * @see #setScrollIndicators(int)
2646     * @see #setScrollIndicators(int, int)
2647     * @see #getScrollIndicators()
2648     */
2649    public static final int SCROLL_INDICATOR_BOTTOM =
2650            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2651
2652    /**
2653     * Scroll indicator direction for the left edge of the view.
2654     *
2655     * @see #setScrollIndicators(int)
2656     * @see #setScrollIndicators(int, int)
2657     * @see #getScrollIndicators()
2658     */
2659    public static final int SCROLL_INDICATOR_LEFT =
2660            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2661
2662    /**
2663     * Scroll indicator direction for the right edge of the view.
2664     *
2665     * @see #setScrollIndicators(int)
2666     * @see #setScrollIndicators(int, int)
2667     * @see #getScrollIndicators()
2668     */
2669    public static final int SCROLL_INDICATOR_RIGHT =
2670            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2671
2672    /**
2673     * Scroll indicator direction for the starting edge of the view.
2674     * <p>
2675     * Resolved according to the view's layout direction, see
2676     * {@link #getLayoutDirection()} for more information.
2677     *
2678     * @see #setScrollIndicators(int)
2679     * @see #setScrollIndicators(int, int)
2680     * @see #getScrollIndicators()
2681     */
2682    public static final int SCROLL_INDICATOR_START =
2683            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2684
2685    /**
2686     * Scroll indicator direction for the ending edge of the view.
2687     * <p>
2688     * Resolved according to the view's layout direction, see
2689     * {@link #getLayoutDirection()} for more information.
2690     *
2691     * @see #setScrollIndicators(int)
2692     * @see #setScrollIndicators(int, int)
2693     * @see #getScrollIndicators()
2694     */
2695    public static final int SCROLL_INDICATOR_END =
2696            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2697
2698    /**
2699     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2700     * into this view.<p>
2701     */
2702    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2703
2704    /**
2705     * Flag indicating that the view is a root of a keyboard navigation cluster.
2706     *
2707     * @see #isKeyboardNavigationCluster()
2708     * @see #setKeyboardNavigationCluster(boolean)
2709     */
2710    private static final int PFLAG3_CLUSTER = 0x8000;
2711
2712    /**
2713     * Flag indicating that the view is a root of a keyboard navigation section.
2714     *
2715     * @see #isKeyboardNavigationSection()
2716     * @see #setKeyboardNavigationSection(boolean)
2717     */
2718    private static final int PFLAG3_SECTION = 0x10000;
2719
2720    /**
2721     * Indicates that the user is currently touching the screen.
2722     * Currently used for the tooltip positioning only.
2723     */
2724    private static final int PFLAG3_FINGER_DOWN = 0x20000;
2725
2726    /**
2727     * Flag indicating that this view is the default-focus view.
2728     *
2729     * @see #isFocusedByDefault()
2730     * @see #setFocusedByDefault(boolean)
2731     */
2732    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
2733
2734    /**
2735     * Whether this view has rendered elements that overlap (see {@link
2736     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2737     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2738     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2739     * determined by whatever {@link #hasOverlappingRendering()} returns.
2740     */
2741    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2742
2743    /**
2744     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2745     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2746     */
2747    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2748
2749    /**
2750     * Flag indicating that the view is temporarily detached from the parent view.
2751     *
2752     * @see #onStartTemporaryDetach()
2753     * @see #onFinishTemporaryDetach()
2754     */
2755    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2756
2757    /**
2758     * Flag indicating that the view does not wish to be revealed within its parent
2759     * hierarchy when it gains focus. Expressed in the negative since the historical
2760     * default behavior is to reveal on focus; this flag suppresses that behavior.
2761     *
2762     * @see #setRevealOnFocusHint(boolean)
2763     * @see #getRevealOnFocusHint()
2764     */
2765    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
2766
2767    /* End of masks for mPrivateFlags3 */
2768
2769    /**
2770     * Always allow a user to over-scroll this view, provided it is a
2771     * view that can scroll.
2772     *
2773     * @see #getOverScrollMode()
2774     * @see #setOverScrollMode(int)
2775     */
2776    public static final int OVER_SCROLL_ALWAYS = 0;
2777
2778    /**
2779     * Allow a user to over-scroll this view only if the content is large
2780     * enough to meaningfully scroll, provided it is a view that can scroll.
2781     *
2782     * @see #getOverScrollMode()
2783     * @see #setOverScrollMode(int)
2784     */
2785    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2786
2787    /**
2788     * Never allow a user to over-scroll this view.
2789     *
2790     * @see #getOverScrollMode()
2791     * @see #setOverScrollMode(int)
2792     */
2793    public static final int OVER_SCROLL_NEVER = 2;
2794
2795    /**
2796     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2797     * requested the system UI (status bar) to be visible (the default).
2798     *
2799     * @see #setSystemUiVisibility(int)
2800     */
2801    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2802
2803    /**
2804     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2805     * system UI to enter an unobtrusive "low profile" mode.
2806     *
2807     * <p>This is for use in games, book readers, video players, or any other
2808     * "immersive" application where the usual system chrome is deemed too distracting.
2809     *
2810     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2811     *
2812     * @see #setSystemUiVisibility(int)
2813     */
2814    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2815
2816    /**
2817     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2818     * system navigation be temporarily hidden.
2819     *
2820     * <p>This is an even less obtrusive state than that called for by
2821     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2822     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2823     * those to disappear. This is useful (in conjunction with the
2824     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2825     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2826     * window flags) for displaying content using every last pixel on the display.
2827     *
2828     * <p>There is a limitation: because navigation controls are so important, the least user
2829     * interaction will cause them to reappear immediately.  When this happens, both
2830     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2831     * so that both elements reappear at the same time.
2832     *
2833     * @see #setSystemUiVisibility(int)
2834     */
2835    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2836
2837    /**
2838     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2839     * into the normal fullscreen mode so that its content can take over the screen
2840     * while still allowing the user to interact with the application.
2841     *
2842     * <p>This has the same visual effect as
2843     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2844     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2845     * meaning that non-critical screen decorations (such as the status bar) will be
2846     * hidden while the user is in the View's window, focusing the experience on
2847     * that content.  Unlike the window flag, if you are using ActionBar in
2848     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2849     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2850     * hide the action bar.
2851     *
2852     * <p>This approach to going fullscreen is best used over the window flag when
2853     * it is a transient state -- that is, the application does this at certain
2854     * points in its user interaction where it wants to allow the user to focus
2855     * on content, but not as a continuous state.  For situations where the application
2856     * would like to simply stay full screen the entire time (such as a game that
2857     * wants to take over the screen), the
2858     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2859     * is usually a better approach.  The state set here will be removed by the system
2860     * in various situations (such as the user moving to another application) like
2861     * the other system UI states.
2862     *
2863     * <p>When using this flag, the application should provide some easy facility
2864     * for the user to go out of it.  A common example would be in an e-book
2865     * reader, where tapping on the screen brings back whatever screen and UI
2866     * decorations that had been hidden while the user was immersed in reading
2867     * the book.
2868     *
2869     * @see #setSystemUiVisibility(int)
2870     */
2871    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2872
2873    /**
2874     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2875     * flags, we would like a stable view of the content insets given to
2876     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2877     * will always represent the worst case that the application can expect
2878     * as a continuous state.  In the stock Android UI this is the space for
2879     * the system bar, nav bar, and status bar, but not more transient elements
2880     * such as an input method.
2881     *
2882     * The stable layout your UI sees is based on the system UI modes you can
2883     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2884     * then you will get a stable layout for changes of the
2885     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2886     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2887     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2888     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2889     * with a stable layout.  (Note that you should avoid using
2890     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2891     *
2892     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2893     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2894     * then a hidden status bar will be considered a "stable" state for purposes
2895     * here.  This allows your UI to continually hide the status bar, while still
2896     * using the system UI flags to hide the action bar while still retaining
2897     * a stable layout.  Note that changing the window fullscreen flag will never
2898     * provide a stable layout for a clean transition.
2899     *
2900     * <p>If you are using ActionBar in
2901     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2902     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2903     * insets it adds to those given to the application.
2904     */
2905    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2906
2907    /**
2908     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2909     * to be laid out as if it has requested
2910     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2911     * allows it to avoid artifacts when switching in and out of that mode, at
2912     * the expense that some of its user interface may be covered by screen
2913     * decorations when they are shown.  You can perform layout of your inner
2914     * UI elements to account for the navigation system UI through the
2915     * {@link #fitSystemWindows(Rect)} method.
2916     */
2917    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2918
2919    /**
2920     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2921     * to be laid out as if it has requested
2922     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2923     * allows it to avoid artifacts when switching in and out of that mode, at
2924     * the expense that some of its user interface may be covered by screen
2925     * decorations when they are shown.  You can perform layout of your inner
2926     * UI elements to account for non-fullscreen system UI through the
2927     * {@link #fitSystemWindows(Rect)} method.
2928     */
2929    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2930
2931    /**
2932     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2933     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2934     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2935     * user interaction.
2936     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2937     * has an effect when used in combination with that flag.</p>
2938     */
2939    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2940
2941    /**
2942     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2943     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2944     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2945     * experience while also hiding the system bars.  If this flag is not set,
2946     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2947     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2948     * if the user swipes from the top of the screen.
2949     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2950     * system gestures, such as swiping from the top of the screen.  These transient system bars
2951     * will overlay app’s content, may have some degree of transparency, and will automatically
2952     * hide after a short timeout.
2953     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2954     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2955     * with one or both of those flags.</p>
2956     */
2957    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2958
2959    /**
2960     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2961     * is compatible with light status bar backgrounds.
2962     *
2963     * <p>For this to take effect, the window must request
2964     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2965     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2966     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2967     *         FLAG_TRANSLUCENT_STATUS}.
2968     *
2969     * @see android.R.attr#windowLightStatusBar
2970     */
2971    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2972
2973    /**
2974     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2975     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2976     */
2977    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
2978
2979    /**
2980     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
2981     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
2982     */
2983    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
2984
2985    /**
2986     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
2987     * that is compatible with light navigation bar backgrounds.
2988     *
2989     * <p>For this to take effect, the window must request
2990     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2991     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2992     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
2993     *         FLAG_TRANSLUCENT_NAVIGATION}.
2994     */
2995    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
2996
2997    /**
2998     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2999     */
3000    @Deprecated
3001    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
3002
3003    /**
3004     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
3005     */
3006    @Deprecated
3007    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
3008
3009    /**
3010     * @hide
3011     *
3012     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3013     * out of the public fields to keep the undefined bits out of the developer's way.
3014     *
3015     * Flag to make the status bar not expandable.  Unless you also
3016     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3017     */
3018    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3019
3020    /**
3021     * @hide
3022     *
3023     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3024     * out of the public fields to keep the undefined bits out of the developer's way.
3025     *
3026     * Flag to hide notification icons and scrolling ticker text.
3027     */
3028    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3029
3030    /**
3031     * @hide
3032     *
3033     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3034     * out of the public fields to keep the undefined bits out of the developer's way.
3035     *
3036     * Flag to disable incoming notification alerts.  This will not block
3037     * icons, but it will block sound, vibrating and other visual or aural notifications.
3038     */
3039    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3040
3041    /**
3042     * @hide
3043     *
3044     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3045     * out of the public fields to keep the undefined bits out of the developer's way.
3046     *
3047     * Flag to hide only the scrolling ticker.  Note that
3048     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3049     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3050     */
3051    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3052
3053    /**
3054     * @hide
3055     *
3056     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3057     * out of the public fields to keep the undefined bits out of the developer's way.
3058     *
3059     * Flag to hide the center system info area.
3060     */
3061    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3062
3063    /**
3064     * @hide
3065     *
3066     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3067     * out of the public fields to keep the undefined bits out of the developer's way.
3068     *
3069     * Flag to hide only the home button.  Don't use this
3070     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3071     */
3072    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3073
3074    /**
3075     * @hide
3076     *
3077     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3078     * out of the public fields to keep the undefined bits out of the developer's way.
3079     *
3080     * Flag to hide only the back button. Don't use this
3081     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3082     */
3083    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3084
3085    /**
3086     * @hide
3087     *
3088     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3089     * out of the public fields to keep the undefined bits out of the developer's way.
3090     *
3091     * Flag to hide only the clock.  You might use this if your activity has
3092     * its own clock making the status bar's clock redundant.
3093     */
3094    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3095
3096    /**
3097     * @hide
3098     *
3099     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3100     * out of the public fields to keep the undefined bits out of the developer's way.
3101     *
3102     * Flag to hide only the recent apps button. Don't use this
3103     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3104     */
3105    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3106
3107    /**
3108     * @hide
3109     *
3110     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3111     * out of the public fields to keep the undefined bits out of the developer's way.
3112     *
3113     * Flag to disable the global search gesture. Don't use this
3114     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3115     */
3116    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3117
3118    /**
3119     * @hide
3120     *
3121     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3122     * out of the public fields to keep the undefined bits out of the developer's way.
3123     *
3124     * Flag to specify that the status bar is displayed in transient mode.
3125     */
3126    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3127
3128    /**
3129     * @hide
3130     *
3131     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3132     * out of the public fields to keep the undefined bits out of the developer's way.
3133     *
3134     * Flag to specify that the navigation bar is displayed in transient mode.
3135     */
3136    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3137
3138    /**
3139     * @hide
3140     *
3141     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3142     * out of the public fields to keep the undefined bits out of the developer's way.
3143     *
3144     * Flag to specify that the hidden status bar would like to be shown.
3145     */
3146    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3147
3148    /**
3149     * @hide
3150     *
3151     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3152     * out of the public fields to keep the undefined bits out of the developer's way.
3153     *
3154     * Flag to specify that the hidden navigation bar would like to be shown.
3155     */
3156    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
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 specify that the status bar is displayed in translucent mode.
3165     */
3166    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3167
3168    /**
3169     * @hide
3170     *
3171     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3172     * out of the public fields to keep the undefined bits out of the developer's way.
3173     *
3174     * Flag to specify that the navigation bar is displayed in translucent mode.
3175     */
3176    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3177
3178    /**
3179     * @hide
3180     *
3181     * Makes navigation bar transparent (but not the status bar).
3182     */
3183    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3184
3185    /**
3186     * @hide
3187     *
3188     * Makes status bar transparent (but not the navigation bar).
3189     */
3190    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3191
3192    /**
3193     * @hide
3194     *
3195     * Makes both status bar and navigation bar transparent.
3196     */
3197    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3198            | STATUS_BAR_TRANSPARENT;
3199
3200    /**
3201     * @hide
3202     */
3203    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3204
3205    /**
3206     * These are the system UI flags that can be cleared by events outside
3207     * of an application.  Currently this is just the ability to tap on the
3208     * screen while hiding the navigation bar to have it return.
3209     * @hide
3210     */
3211    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3212            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3213            | SYSTEM_UI_FLAG_FULLSCREEN;
3214
3215    /**
3216     * Flags that can impact the layout in relation to system UI.
3217     */
3218    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3219            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3220            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3221
3222    /** @hide */
3223    @IntDef(flag = true,
3224            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3225    @Retention(RetentionPolicy.SOURCE)
3226    public @interface FindViewFlags {}
3227
3228    /**
3229     * Find views that render the specified text.
3230     *
3231     * @see #findViewsWithText(ArrayList, CharSequence, int)
3232     */
3233    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3234
3235    /**
3236     * Find find views that contain the specified content description.
3237     *
3238     * @see #findViewsWithText(ArrayList, CharSequence, int)
3239     */
3240    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3241
3242    /**
3243     * Find views that contain {@link AccessibilityNodeProvider}. Such
3244     * a View is a root of virtual view hierarchy and may contain the searched
3245     * text. If this flag is set Views with providers are automatically
3246     * added and it is a responsibility of the client to call the APIs of
3247     * the provider to determine whether the virtual tree rooted at this View
3248     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3249     * representing the virtual views with this text.
3250     *
3251     * @see #findViewsWithText(ArrayList, CharSequence, int)
3252     *
3253     * @hide
3254     */
3255    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3256
3257    /**
3258     * The undefined cursor position.
3259     *
3260     * @hide
3261     */
3262    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3263
3264    /**
3265     * Indicates that the screen has changed state and is now off.
3266     *
3267     * @see #onScreenStateChanged(int)
3268     */
3269    public static final int SCREEN_STATE_OFF = 0x0;
3270
3271    /**
3272     * Indicates that the screen has changed state and is now on.
3273     *
3274     * @see #onScreenStateChanged(int)
3275     */
3276    public static final int SCREEN_STATE_ON = 0x1;
3277
3278    /**
3279     * Indicates no axis of view scrolling.
3280     */
3281    public static final int SCROLL_AXIS_NONE = 0;
3282
3283    /**
3284     * Indicates scrolling along the horizontal axis.
3285     */
3286    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3287
3288    /**
3289     * Indicates scrolling along the vertical axis.
3290     */
3291    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3292
3293    /**
3294     * Controls the over-scroll mode for this view.
3295     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3296     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3297     * and {@link #OVER_SCROLL_NEVER}.
3298     */
3299    private int mOverScrollMode;
3300
3301    /**
3302     * The parent this view is attached to.
3303     * {@hide}
3304     *
3305     * @see #getParent()
3306     */
3307    protected ViewParent mParent;
3308
3309    /**
3310     * {@hide}
3311     */
3312    AttachInfo mAttachInfo;
3313
3314    /**
3315     * {@hide}
3316     */
3317    @ViewDebug.ExportedProperty(flagMapping = {
3318        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3319                name = "FORCE_LAYOUT"),
3320        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3321                name = "LAYOUT_REQUIRED"),
3322        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3323            name = "DRAWING_CACHE_INVALID", outputIf = false),
3324        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3325        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3326        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3327        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3328    }, formatToHexString = true)
3329
3330    /* @hide */
3331    public int mPrivateFlags;
3332    int mPrivateFlags2;
3333    int mPrivateFlags3;
3334
3335    /**
3336     * This view's request for the visibility of the status bar.
3337     * @hide
3338     */
3339    @ViewDebug.ExportedProperty(flagMapping = {
3340        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3341                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3342                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3343        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3344                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3345                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3346        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3347                                equals = SYSTEM_UI_FLAG_VISIBLE,
3348                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3349    }, formatToHexString = true)
3350    int mSystemUiVisibility;
3351
3352    /**
3353     * Reference count for transient state.
3354     * @see #setHasTransientState(boolean)
3355     */
3356    int mTransientStateCount = 0;
3357
3358    /**
3359     * Count of how many windows this view has been attached to.
3360     */
3361    int mWindowAttachCount;
3362
3363    /**
3364     * The layout parameters associated with this view and used by the parent
3365     * {@link android.view.ViewGroup} to determine how this view should be
3366     * laid out.
3367     * {@hide}
3368     */
3369    protected ViewGroup.LayoutParams mLayoutParams;
3370
3371    /**
3372     * The view flags hold various views states.
3373     * {@hide}
3374     */
3375    @ViewDebug.ExportedProperty(formatToHexString = true)
3376    int mViewFlags;
3377
3378    static class TransformationInfo {
3379        /**
3380         * The transform matrix for the View. This transform is calculated internally
3381         * based on the translation, rotation, and scale properties.
3382         *
3383         * Do *not* use this variable directly; instead call getMatrix(), which will
3384         * load the value from the View's RenderNode.
3385         */
3386        private final Matrix mMatrix = new Matrix();
3387
3388        /**
3389         * The inverse transform matrix for the View. This transform is calculated
3390         * internally based on the translation, rotation, and scale properties.
3391         *
3392         * Do *not* use this variable directly; instead call getInverseMatrix(),
3393         * which will load the value from the View's RenderNode.
3394         */
3395        private Matrix mInverseMatrix;
3396
3397        /**
3398         * The opacity of the View. This is a value from 0 to 1, where 0 means
3399         * completely transparent and 1 means completely opaque.
3400         */
3401        @ViewDebug.ExportedProperty
3402        float mAlpha = 1f;
3403
3404        /**
3405         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3406         * property only used by transitions, which is composited with the other alpha
3407         * values to calculate the final visual alpha value.
3408         */
3409        float mTransitionAlpha = 1f;
3410    }
3411
3412    /** @hide */
3413    public TransformationInfo mTransformationInfo;
3414
3415    /**
3416     * Current clip bounds. to which all drawing of this view are constrained.
3417     */
3418    Rect mClipBounds = null;
3419
3420    private boolean mLastIsOpaque;
3421
3422    /**
3423     * The distance in pixels from the left edge of this view's parent
3424     * to the left edge of this view.
3425     * {@hide}
3426     */
3427    @ViewDebug.ExportedProperty(category = "layout")
3428    protected int mLeft;
3429    /**
3430     * The distance in pixels from the left edge of this view's parent
3431     * to the right edge of this view.
3432     * {@hide}
3433     */
3434    @ViewDebug.ExportedProperty(category = "layout")
3435    protected int mRight;
3436    /**
3437     * The distance in pixels from the top edge of this view's parent
3438     * to the top edge of this view.
3439     * {@hide}
3440     */
3441    @ViewDebug.ExportedProperty(category = "layout")
3442    protected int mTop;
3443    /**
3444     * The distance in pixels from the top edge of this view's parent
3445     * to the bottom edge of this view.
3446     * {@hide}
3447     */
3448    @ViewDebug.ExportedProperty(category = "layout")
3449    protected int mBottom;
3450
3451    /**
3452     * The offset, in pixels, by which the content of this view is scrolled
3453     * horizontally.
3454     * {@hide}
3455     */
3456    @ViewDebug.ExportedProperty(category = "scrolling")
3457    protected int mScrollX;
3458    /**
3459     * The offset, in pixels, by which the content of this view is scrolled
3460     * vertically.
3461     * {@hide}
3462     */
3463    @ViewDebug.ExportedProperty(category = "scrolling")
3464    protected int mScrollY;
3465
3466    /**
3467     * The left padding in pixels, that is the distance in pixels between the
3468     * left edge of this view and the left edge of its content.
3469     * {@hide}
3470     */
3471    @ViewDebug.ExportedProperty(category = "padding")
3472    protected int mPaddingLeft = 0;
3473    /**
3474     * The right padding in pixels, that is the distance in pixels between the
3475     * right edge of this view and the right edge of its content.
3476     * {@hide}
3477     */
3478    @ViewDebug.ExportedProperty(category = "padding")
3479    protected int mPaddingRight = 0;
3480    /**
3481     * The top padding in pixels, that is the distance in pixels between the
3482     * top edge of this view and the top edge of its content.
3483     * {@hide}
3484     */
3485    @ViewDebug.ExportedProperty(category = "padding")
3486    protected int mPaddingTop;
3487    /**
3488     * The bottom padding in pixels, that is the distance in pixels between the
3489     * bottom edge of this view and the bottom edge of its content.
3490     * {@hide}
3491     */
3492    @ViewDebug.ExportedProperty(category = "padding")
3493    protected int mPaddingBottom;
3494
3495    /**
3496     * The layout insets in pixels, that is the distance in pixels between the
3497     * visible edges of this view its bounds.
3498     */
3499    private Insets mLayoutInsets;
3500
3501    /**
3502     * Briefly describes the view and is primarily used for accessibility support.
3503     */
3504    private CharSequence mContentDescription;
3505
3506    /**
3507     * Specifies the id of a view for which this view serves as a label for
3508     * accessibility purposes.
3509     */
3510    private int mLabelForId = View.NO_ID;
3511
3512    /**
3513     * Predicate for matching labeled view id with its label for
3514     * accessibility purposes.
3515     */
3516    private MatchLabelForPredicate mMatchLabelForPredicate;
3517
3518    /**
3519     * Specifies a view before which this one is visited in accessibility traversal.
3520     */
3521    private int mAccessibilityTraversalBeforeId = NO_ID;
3522
3523    /**
3524     * Specifies a view after which this one is visited in accessibility traversal.
3525     */
3526    private int mAccessibilityTraversalAfterId = NO_ID;
3527
3528    /**
3529     * Predicate for matching a view by its id.
3530     */
3531    private MatchIdPredicate mMatchIdPredicate;
3532
3533    /**
3534     * Cache the paddingRight set by the user to append to the scrollbar's size.
3535     *
3536     * @hide
3537     */
3538    @ViewDebug.ExportedProperty(category = "padding")
3539    protected int mUserPaddingRight;
3540
3541    /**
3542     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3543     *
3544     * @hide
3545     */
3546    @ViewDebug.ExportedProperty(category = "padding")
3547    protected int mUserPaddingBottom;
3548
3549    /**
3550     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3551     *
3552     * @hide
3553     */
3554    @ViewDebug.ExportedProperty(category = "padding")
3555    protected int mUserPaddingLeft;
3556
3557    /**
3558     * Cache the paddingStart set by the user to append to the scrollbar's size.
3559     *
3560     */
3561    @ViewDebug.ExportedProperty(category = "padding")
3562    int mUserPaddingStart;
3563
3564    /**
3565     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3566     *
3567     */
3568    @ViewDebug.ExportedProperty(category = "padding")
3569    int mUserPaddingEnd;
3570
3571    /**
3572     * Cache initial left padding.
3573     *
3574     * @hide
3575     */
3576    int mUserPaddingLeftInitial;
3577
3578    /**
3579     * Cache initial right padding.
3580     *
3581     * @hide
3582     */
3583    int mUserPaddingRightInitial;
3584
3585    /**
3586     * Default undefined padding
3587     */
3588    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3589
3590    /**
3591     * Cache if a left padding has been defined
3592     */
3593    private boolean mLeftPaddingDefined = false;
3594
3595    /**
3596     * Cache if a right padding has been defined
3597     */
3598    private boolean mRightPaddingDefined = false;
3599
3600    /**
3601     * @hide
3602     */
3603    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3604    /**
3605     * @hide
3606     */
3607    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3608
3609    private LongSparseLongArray mMeasureCache;
3610
3611    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3612    private Drawable mBackground;
3613    private TintInfo mBackgroundTint;
3614
3615    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3616    private ForegroundInfo mForegroundInfo;
3617
3618    private Drawable mScrollIndicatorDrawable;
3619
3620    /**
3621     * RenderNode used for backgrounds.
3622     * <p>
3623     * When non-null and valid, this is expected to contain an up-to-date copy
3624     * of the background drawable. It is cleared on temporary detach, and reset
3625     * on cleanup.
3626     */
3627    private RenderNode mBackgroundRenderNode;
3628
3629    private int mBackgroundResource;
3630    private boolean mBackgroundSizeChanged;
3631
3632    private String mTransitionName;
3633
3634    static class TintInfo {
3635        ColorStateList mTintList;
3636        PorterDuff.Mode mTintMode;
3637        boolean mHasTintMode;
3638        boolean mHasTintList;
3639    }
3640
3641    private static class ForegroundInfo {
3642        private Drawable mDrawable;
3643        private TintInfo mTintInfo;
3644        private int mGravity = Gravity.FILL;
3645        private boolean mInsidePadding = true;
3646        private boolean mBoundsChanged = true;
3647        private final Rect mSelfBounds = new Rect();
3648        private final Rect mOverlayBounds = new Rect();
3649    }
3650
3651    static class ListenerInfo {
3652        /**
3653         * Listener used to dispatch focus change events.
3654         * This field should be made private, so it is hidden from the SDK.
3655         * {@hide}
3656         */
3657        protected OnFocusChangeListener mOnFocusChangeListener;
3658
3659        /**
3660         * Listeners for layout change events.
3661         */
3662        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3663
3664        protected OnScrollChangeListener mOnScrollChangeListener;
3665
3666        /**
3667         * Listeners for attach events.
3668         */
3669        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3670
3671        /**
3672         * Listener used to dispatch click events.
3673         * This field should be made private, so it is hidden from the SDK.
3674         * {@hide}
3675         */
3676        public OnClickListener mOnClickListener;
3677
3678        /**
3679         * Listener used to dispatch long click events.
3680         * This field should be made private, so it is hidden from the SDK.
3681         * {@hide}
3682         */
3683        protected OnLongClickListener mOnLongClickListener;
3684
3685        /**
3686         * Listener used to dispatch context click events. This field should be made private, so it
3687         * is hidden from the SDK.
3688         * {@hide}
3689         */
3690        protected OnContextClickListener mOnContextClickListener;
3691
3692        /**
3693         * Listener used to build the context menu.
3694         * This field should be made private, so it is hidden from the SDK.
3695         * {@hide}
3696         */
3697        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3698
3699        private OnKeyListener mOnKeyListener;
3700
3701        private OnTouchListener mOnTouchListener;
3702
3703        private OnHoverListener mOnHoverListener;
3704
3705        private OnGenericMotionListener mOnGenericMotionListener;
3706
3707        private OnDragListener mOnDragListener;
3708
3709        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3710
3711        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3712    }
3713
3714    ListenerInfo mListenerInfo;
3715
3716    private static class TooltipInfo {
3717        /**
3718         * Text to be displayed in a tooltip popup.
3719         */
3720        @Nullable
3721        CharSequence mTooltip;
3722
3723        /**
3724         * View-relative position of the tooltip anchor point.
3725         */
3726        int mAnchorX;
3727        int mAnchorY;
3728
3729        /**
3730         * The tooltip popup.
3731         */
3732        @Nullable
3733        TooltipPopup mTooltipPopup;
3734
3735        /**
3736         * Set to true if the tooltip was shown as a result of a long click.
3737         */
3738        boolean mTooltipFromLongClick;
3739
3740        /**
3741         * Keep these Runnables so that they can be used to reschedule.
3742         */
3743        Runnable mShowTooltipRunnable;
3744        Runnable mHideTooltipRunnable;
3745    }
3746
3747    TooltipInfo mTooltipInfo;
3748
3749    // Temporary values used to hold (x,y) coordinates when delegating from the
3750    // two-arg performLongClick() method to the legacy no-arg version.
3751    private float mLongClickX = Float.NaN;
3752    private float mLongClickY = Float.NaN;
3753
3754    /**
3755     * The application environment this view lives in.
3756     * This field should be made private, so it is hidden from the SDK.
3757     * {@hide}
3758     */
3759    @ViewDebug.ExportedProperty(deepExport = true)
3760    protected Context mContext;
3761
3762    private final Resources mResources;
3763
3764    private ScrollabilityCache mScrollCache;
3765
3766    private int[] mDrawableState = null;
3767
3768    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3769
3770    /**
3771     * Animator that automatically runs based on state changes.
3772     */
3773    private StateListAnimator mStateListAnimator;
3774
3775    /**
3776     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3777     * the user may specify which view to go to next.
3778     */
3779    private int mNextFocusLeftId = View.NO_ID;
3780
3781    /**
3782     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3783     * the user may specify which view to go to next.
3784     */
3785    private int mNextFocusRightId = View.NO_ID;
3786
3787    /**
3788     * When this view has focus and the next focus is {@link #FOCUS_UP},
3789     * the user may specify which view to go to next.
3790     */
3791    private int mNextFocusUpId = View.NO_ID;
3792
3793    /**
3794     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3795     * the user may specify which view to go to next.
3796     */
3797    private int mNextFocusDownId = View.NO_ID;
3798
3799    /**
3800     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3801     * the user may specify which view to go to next.
3802     */
3803    int mNextFocusForwardId = View.NO_ID;
3804
3805    /**
3806     * User-specified next keyboard navigation cluster.
3807     */
3808    int mNextClusterForwardId = View.NO_ID;
3809
3810    /**
3811     * User-specified next keyboard navigation section.
3812     */
3813    int mNextSectionForwardId = View.NO_ID;
3814
3815    private CheckForLongPress mPendingCheckForLongPress;
3816    private CheckForTap mPendingCheckForTap = null;
3817    private PerformClick mPerformClick;
3818    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3819
3820    private UnsetPressedState mUnsetPressedState;
3821
3822    /**
3823     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3824     * up event while a long press is invoked as soon as the long press duration is reached, so
3825     * a long press could be performed before the tap is checked, in which case the tap's action
3826     * should not be invoked.
3827     */
3828    private boolean mHasPerformedLongPress;
3829
3830    /**
3831     * Whether a context click button is currently pressed down. This is true when the stylus is
3832     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3833     * pressed. This is false once the button is released or if the stylus has been lifted.
3834     */
3835    private boolean mInContextButtonPress;
3836
3837    /**
3838     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3839     * true after a stylus button press has occured, when the next up event should not be recognized
3840     * as a tap.
3841     */
3842    private boolean mIgnoreNextUpEvent;
3843
3844    /**
3845     * The minimum height of the view. We'll try our best to have the height
3846     * of this view to at least this amount.
3847     */
3848    @ViewDebug.ExportedProperty(category = "measurement")
3849    private int mMinHeight;
3850
3851    /**
3852     * The minimum width of the view. We'll try our best to have the width
3853     * of this view to at least this amount.
3854     */
3855    @ViewDebug.ExportedProperty(category = "measurement")
3856    private int mMinWidth;
3857
3858    /**
3859     * The delegate to handle touch events that are physically in this view
3860     * but should be handled by another view.
3861     */
3862    private TouchDelegate mTouchDelegate = null;
3863
3864    /**
3865     * Solid color to use as a background when creating the drawing cache. Enables
3866     * the cache to use 16 bit bitmaps instead of 32 bit.
3867     */
3868    private int mDrawingCacheBackgroundColor = 0;
3869
3870    /**
3871     * Special tree observer used when mAttachInfo is null.
3872     */
3873    private ViewTreeObserver mFloatingTreeObserver;
3874
3875    /**
3876     * Cache the touch slop from the context that created the view.
3877     */
3878    private int mTouchSlop;
3879
3880    /**
3881     * Object that handles automatic animation of view properties.
3882     */
3883    private ViewPropertyAnimator mAnimator = null;
3884
3885    /**
3886     * List of registered FrameMetricsObservers.
3887     */
3888    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3889
3890    /**
3891     * Flag indicating that a drag can cross window boundaries.  When
3892     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3893     * with this flag set, all visible applications with targetSdkVersion >=
3894     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3895     * in the drag operation and receive the dragged content.
3896     *
3897     * <p>If this is the only flag set, then the drag recipient will only have access to text data
3898     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3899     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
3900     */
3901    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3902
3903    /**
3904     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3905     * request read access to the content URI(s) contained in the {@link ClipData} object.
3906     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3907     */
3908    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3909
3910    /**
3911     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3912     * request write access to the content URI(s) contained in the {@link ClipData} object.
3913     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3914     */
3915    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3916
3917    /**
3918     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3919     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3920     * reboots until explicitly revoked with
3921     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3922     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3923     */
3924    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3925            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3926
3927    /**
3928     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3929     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3930     * match against the original granted URI.
3931     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3932     */
3933    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3934            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3935
3936    /**
3937     * Flag indicating that the drag shadow will be opaque.  When
3938     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3939     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3940     */
3941    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3942
3943    /**
3944     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3945     */
3946    private float mVerticalScrollFactor;
3947
3948    /**
3949     * Position of the vertical scroll bar.
3950     */
3951    private int mVerticalScrollbarPosition;
3952
3953    /**
3954     * Position the scroll bar at the default position as determined by the system.
3955     */
3956    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3957
3958    /**
3959     * Position the scroll bar along the left edge.
3960     */
3961    public static final int SCROLLBAR_POSITION_LEFT = 1;
3962
3963    /**
3964     * Position the scroll bar along the right edge.
3965     */
3966    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3967
3968    /**
3969     * Indicates that the view does not have a layer.
3970     *
3971     * @see #getLayerType()
3972     * @see #setLayerType(int, android.graphics.Paint)
3973     * @see #LAYER_TYPE_SOFTWARE
3974     * @see #LAYER_TYPE_HARDWARE
3975     */
3976    public static final int LAYER_TYPE_NONE = 0;
3977
3978    /**
3979     * <p>Indicates that the view has a software layer. A software layer is backed
3980     * by a bitmap and causes the view to be rendered using Android's software
3981     * rendering pipeline, even if hardware acceleration is enabled.</p>
3982     *
3983     * <p>Software layers have various usages:</p>
3984     * <p>When the application is not using hardware acceleration, a software layer
3985     * is useful to apply a specific color filter and/or blending mode and/or
3986     * translucency to a view and all its children.</p>
3987     * <p>When the application is using hardware acceleration, a software layer
3988     * is useful to render drawing primitives not supported by the hardware
3989     * accelerated pipeline. It can also be used to cache a complex view tree
3990     * into a texture and reduce the complexity of drawing operations. For instance,
3991     * when animating a complex view tree with a translation, a software layer can
3992     * be used to render the view tree only once.</p>
3993     * <p>Software layers should be avoided when the affected view tree updates
3994     * often. Every update will require to re-render the software layer, which can
3995     * potentially be slow (particularly when hardware acceleration is turned on
3996     * since the layer will have to be uploaded into a hardware texture after every
3997     * update.)</p>
3998     *
3999     * @see #getLayerType()
4000     * @see #setLayerType(int, android.graphics.Paint)
4001     * @see #LAYER_TYPE_NONE
4002     * @see #LAYER_TYPE_HARDWARE
4003     */
4004    public static final int LAYER_TYPE_SOFTWARE = 1;
4005
4006    /**
4007     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
4008     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
4009     * OpenGL hardware) and causes the view to be rendered using Android's hardware
4010     * rendering pipeline, but only if hardware acceleration is turned on for the
4011     * view hierarchy. When hardware acceleration is turned off, hardware layers
4012     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
4013     *
4014     * <p>A hardware layer is useful to apply a specific color filter and/or
4015     * blending mode and/or translucency to a view and all its children.</p>
4016     * <p>A hardware layer can be used to cache a complex view tree into a
4017     * texture and reduce the complexity of drawing operations. For instance,
4018     * when animating a complex view tree with a translation, a hardware layer can
4019     * be used to render the view tree only once.</p>
4020     * <p>A hardware layer can also be used to increase the rendering quality when
4021     * rotation transformations are applied on a view. It can also be used to
4022     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4023     *
4024     * @see #getLayerType()
4025     * @see #setLayerType(int, android.graphics.Paint)
4026     * @see #LAYER_TYPE_NONE
4027     * @see #LAYER_TYPE_SOFTWARE
4028     */
4029    public static final int LAYER_TYPE_HARDWARE = 2;
4030
4031    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4032            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4033            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4034            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4035    })
4036    int mLayerType = LAYER_TYPE_NONE;
4037    Paint mLayerPaint;
4038
4039
4040    /**
4041     * Set when a request was made to decide if views in an {@link android.app.Activity} can be
4042     * auto-filled by an {@link android.service.autofill.AutoFillService}.
4043     *
4044     * <p>Since this request is made without a explicit user consent, the resulting
4045     * {@link android.app.assist.AssistStructure} should not contain any PII
4046     * (Personally Identifiable Information).
4047     *
4048     * <p>Examples:
4049     * <ul>
4050     * <li>{@link android.widget.TextView} texts should only be included when they were set by
4051     * static resources.
4052     * <li>{@link android.webkit.WebView} virtual children should be restricted to a subset of
4053     * input fields and tags (like {@code id}).
4054     * </ul>
4055     */
4056    // TODO(b/33197203) (b/34078930): improve documentation: mention all cases, show examples, etc.
4057    // In particular, be more specific about webview restrictions
4058    public static final int AUTO_FILL_FLAG_TYPE_FILL = 0x1;
4059
4060    /**
4061     * Set when the user explicitly asked a {@link android.service.autofill.AutoFillService} to save
4062     * the value of the {@link View}s in an {@link android.app.Activity}.
4063     *
4064     * <p>The resulting {@link android.app.assist.AssistStructure} can contain any kind of PII
4065     * (Personally Identifiable Information). For example, the text of password fields should be
4066     * included since that's what's typically saved.
4067     */
4068    public static final int AUTO_FILL_FLAG_TYPE_SAVE = 0x2;
4069
4070    /**
4071     * Set to true when drawing cache is enabled and cannot be created.
4072     *
4073     * @hide
4074     */
4075    public boolean mCachingFailed;
4076    private Bitmap mDrawingCache;
4077    private Bitmap mUnscaledDrawingCache;
4078
4079    /**
4080     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4081     * <p>
4082     * When non-null and valid, this is expected to contain an up-to-date copy
4083     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4084     * cleanup.
4085     */
4086    final RenderNode mRenderNode;
4087
4088    /**
4089     * Set to true when the view is sending hover accessibility events because it
4090     * is the innermost hovered view.
4091     */
4092    private boolean mSendingHoverAccessibilityEvents;
4093
4094    /**
4095     * Delegate for injecting accessibility functionality.
4096     */
4097    AccessibilityDelegate mAccessibilityDelegate;
4098
4099    /**
4100     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4101     * and add/remove objects to/from the overlay directly through the Overlay methods.
4102     */
4103    ViewOverlay mOverlay;
4104
4105    /**
4106     * The currently active parent view for receiving delegated nested scrolling events.
4107     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4108     * by {@link #stopNestedScroll()} at the same point where we clear
4109     * requestDisallowInterceptTouchEvent.
4110     */
4111    private ViewParent mNestedScrollingParent;
4112
4113    /**
4114     * Consistency verifier for debugging purposes.
4115     * @hide
4116     */
4117    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4118            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4119                    new InputEventConsistencyVerifier(this, 0) : null;
4120
4121    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4122
4123    private int[] mTempNestedScrollConsumed;
4124
4125    /**
4126     * An overlay is going to draw this View instead of being drawn as part of this
4127     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4128     * when this view is invalidated.
4129     */
4130    GhostView mGhostView;
4131
4132    /**
4133     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4134     * @hide
4135     */
4136    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4137    public String[] mAttributes;
4138
4139    /**
4140     * Maps a Resource id to its name.
4141     */
4142    private static SparseArray<String> mAttributeMap;
4143
4144    /**
4145     * Queue of pending runnables. Used to postpone calls to post() until this
4146     * view is attached and has a handler.
4147     */
4148    private HandlerActionQueue mRunQueue;
4149
4150    /**
4151     * The pointer icon when the mouse hovers on this view. The default is null.
4152     */
4153    private PointerIcon mPointerIcon;
4154
4155    /**
4156     * @hide
4157     */
4158    String mStartActivityRequestWho;
4159
4160    @Nullable
4161    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4162
4163    /**
4164     * Simple constructor to use when creating a view from code.
4165     *
4166     * @param context The Context the view is running in, through which it can
4167     *        access the current theme, resources, etc.
4168     */
4169    public View(Context context) {
4170        mContext = context;
4171        mResources = context != null ? context.getResources() : null;
4172        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
4173        // Set some flags defaults
4174        mPrivateFlags2 =
4175                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4176                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4177                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4178                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4179                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4180                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4181        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4182        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4183        mUserPaddingStart = UNDEFINED_PADDING;
4184        mUserPaddingEnd = UNDEFINED_PADDING;
4185        mRenderNode = RenderNode.create(getClass().getName(), this);
4186
4187        if (!sCompatibilityDone && context != null) {
4188            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4189
4190            // Older apps may need this compatibility hack for measurement.
4191            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4192
4193            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4194            // of whether a layout was requested on that View.
4195            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4196
4197            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4198
4199            // In M and newer, our widgets can pass a "hint" value in the size
4200            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4201            // know what the expected parent size is going to be, so e.g. list items can size
4202            // themselves at 1/3 the size of their container. It breaks older apps though,
4203            // specifically apps that use some popular open source libraries.
4204            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4205
4206            // Old versions of the platform would give different results from
4207            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4208            // modes, so we always need to run an additional EXACTLY pass.
4209            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4210
4211            // Prior to N, layout params could change without requiring a
4212            // subsequent call to setLayoutParams() and they would usually
4213            // work. Partial layout breaks this assumption.
4214            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4215
4216            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4217            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4218            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4219
4220            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4221            // in apps so we target check it to avoid breaking existing apps.
4222            sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N;
4223
4224            sCascadedDragDrop = targetSdkVersion < N;
4225
4226            sCompatibilityDone = true;
4227        }
4228    }
4229
4230    /**
4231     * Constructor that is called when inflating a view from XML. This is called
4232     * when a view is being constructed from an XML file, supplying attributes
4233     * that were specified in the XML file. This version uses a default style of
4234     * 0, so the only attribute values applied are those in the Context's Theme
4235     * and the given AttributeSet.
4236     *
4237     * <p>
4238     * The method onFinishInflate() will be called after all children have been
4239     * added.
4240     *
4241     * @param context The Context the view is running in, through which it can
4242     *        access the current theme, resources, etc.
4243     * @param attrs The attributes of the XML tag that is inflating the view.
4244     * @see #View(Context, AttributeSet, int)
4245     */
4246    public View(Context context, @Nullable AttributeSet attrs) {
4247        this(context, attrs, 0);
4248    }
4249
4250    /**
4251     * Perform inflation from XML and apply a class-specific base style from a
4252     * theme attribute. This constructor of View allows subclasses to use their
4253     * own base style when they are inflating. For example, a Button class's
4254     * constructor would call this version of the super class constructor and
4255     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4256     * allows the theme's button style to modify all of the base view attributes
4257     * (in particular its background) as well as the Button class's attributes.
4258     *
4259     * @param context The Context the view is running in, through which it can
4260     *        access the current theme, resources, etc.
4261     * @param attrs The attributes of the XML tag that is inflating the view.
4262     * @param defStyleAttr An attribute in the current theme that contains a
4263     *        reference to a style resource that supplies default values for
4264     *        the view. Can be 0 to not look for defaults.
4265     * @see #View(Context, AttributeSet)
4266     */
4267    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4268        this(context, attrs, defStyleAttr, 0);
4269    }
4270
4271    /**
4272     * Perform inflation from XML and apply a class-specific base style from a
4273     * theme attribute or style resource. This constructor of View allows
4274     * subclasses to use their own base style when they are inflating.
4275     * <p>
4276     * When determining the final value of a particular attribute, there are
4277     * four inputs that come into play:
4278     * <ol>
4279     * <li>Any attribute values in the given AttributeSet.
4280     * <li>The style resource specified in the AttributeSet (named "style").
4281     * <li>The default style specified by <var>defStyleAttr</var>.
4282     * <li>The default style specified by <var>defStyleRes</var>.
4283     * <li>The base values in this theme.
4284     * </ol>
4285     * <p>
4286     * Each of these inputs is considered in-order, with the first listed taking
4287     * precedence over the following ones. In other words, if in the
4288     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4289     * , then the button's text will <em>always</em> be black, regardless of
4290     * what is specified in any of the styles.
4291     *
4292     * @param context The Context the view is running in, through which it can
4293     *        access the current theme, resources, etc.
4294     * @param attrs The attributes of the XML tag that is inflating the view.
4295     * @param defStyleAttr An attribute in the current theme that contains a
4296     *        reference to a style resource that supplies default values for
4297     *        the view. Can be 0 to not look for defaults.
4298     * @param defStyleRes A resource identifier of a style resource that
4299     *        supplies default values for the view, used only if
4300     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4301     *        to not look for defaults.
4302     * @see #View(Context, AttributeSet, int)
4303     */
4304    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4305        this(context);
4306
4307        final TypedArray a = context.obtainStyledAttributes(
4308                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4309
4310        if (mDebugViewAttributes) {
4311            saveAttributeData(attrs, a);
4312        }
4313
4314        Drawable background = null;
4315
4316        int leftPadding = -1;
4317        int topPadding = -1;
4318        int rightPadding = -1;
4319        int bottomPadding = -1;
4320        int startPadding = UNDEFINED_PADDING;
4321        int endPadding = UNDEFINED_PADDING;
4322
4323        int padding = -1;
4324        int paddingHorizontal = -1;
4325        int paddingVertical = -1;
4326
4327        int viewFlagValues = 0;
4328        int viewFlagMasks = 0;
4329
4330        boolean setScrollContainer = false;
4331
4332        int x = 0;
4333        int y = 0;
4334
4335        float tx = 0;
4336        float ty = 0;
4337        float tz = 0;
4338        float elevation = 0;
4339        float rotation = 0;
4340        float rotationX = 0;
4341        float rotationY = 0;
4342        float sx = 1f;
4343        float sy = 1f;
4344        boolean transformSet = false;
4345
4346        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4347        int overScrollMode = mOverScrollMode;
4348        boolean initializeScrollbars = false;
4349        boolean initializeScrollIndicators = false;
4350
4351        boolean startPaddingDefined = false;
4352        boolean endPaddingDefined = false;
4353        boolean leftPaddingDefined = false;
4354        boolean rightPaddingDefined = false;
4355
4356        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4357
4358        final int N = a.getIndexCount();
4359        for (int i = 0; i < N; i++) {
4360            int attr = a.getIndex(i);
4361            switch (attr) {
4362                case com.android.internal.R.styleable.View_background:
4363                    background = a.getDrawable(attr);
4364                    break;
4365                case com.android.internal.R.styleable.View_padding:
4366                    padding = a.getDimensionPixelSize(attr, -1);
4367                    mUserPaddingLeftInitial = padding;
4368                    mUserPaddingRightInitial = padding;
4369                    leftPaddingDefined = true;
4370                    rightPaddingDefined = true;
4371                    break;
4372                case com.android.internal.R.styleable.View_paddingHorizontal:
4373                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
4374                    mUserPaddingLeftInitial = paddingHorizontal;
4375                    mUserPaddingRightInitial = paddingHorizontal;
4376                    leftPaddingDefined = true;
4377                    rightPaddingDefined = true;
4378                    break;
4379                case com.android.internal.R.styleable.View_paddingVertical:
4380                    paddingVertical = a.getDimensionPixelSize(attr, -1);
4381                    break;
4382                 case com.android.internal.R.styleable.View_paddingLeft:
4383                    leftPadding = a.getDimensionPixelSize(attr, -1);
4384                    mUserPaddingLeftInitial = leftPadding;
4385                    leftPaddingDefined = true;
4386                    break;
4387                case com.android.internal.R.styleable.View_paddingTop:
4388                    topPadding = a.getDimensionPixelSize(attr, -1);
4389                    break;
4390                case com.android.internal.R.styleable.View_paddingRight:
4391                    rightPadding = a.getDimensionPixelSize(attr, -1);
4392                    mUserPaddingRightInitial = rightPadding;
4393                    rightPaddingDefined = true;
4394                    break;
4395                case com.android.internal.R.styleable.View_paddingBottom:
4396                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4397                    break;
4398                case com.android.internal.R.styleable.View_paddingStart:
4399                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4400                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4401                    break;
4402                case com.android.internal.R.styleable.View_paddingEnd:
4403                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4404                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4405                    break;
4406                case com.android.internal.R.styleable.View_scrollX:
4407                    x = a.getDimensionPixelOffset(attr, 0);
4408                    break;
4409                case com.android.internal.R.styleable.View_scrollY:
4410                    y = a.getDimensionPixelOffset(attr, 0);
4411                    break;
4412                case com.android.internal.R.styleable.View_alpha:
4413                    setAlpha(a.getFloat(attr, 1f));
4414                    break;
4415                case com.android.internal.R.styleable.View_transformPivotX:
4416                    setPivotX(a.getDimension(attr, 0));
4417                    break;
4418                case com.android.internal.R.styleable.View_transformPivotY:
4419                    setPivotY(a.getDimension(attr, 0));
4420                    break;
4421                case com.android.internal.R.styleable.View_translationX:
4422                    tx = a.getDimension(attr, 0);
4423                    transformSet = true;
4424                    break;
4425                case com.android.internal.R.styleable.View_translationY:
4426                    ty = a.getDimension(attr, 0);
4427                    transformSet = true;
4428                    break;
4429                case com.android.internal.R.styleable.View_translationZ:
4430                    tz = a.getDimension(attr, 0);
4431                    transformSet = true;
4432                    break;
4433                case com.android.internal.R.styleable.View_elevation:
4434                    elevation = a.getDimension(attr, 0);
4435                    transformSet = true;
4436                    break;
4437                case com.android.internal.R.styleable.View_rotation:
4438                    rotation = a.getFloat(attr, 0);
4439                    transformSet = true;
4440                    break;
4441                case com.android.internal.R.styleable.View_rotationX:
4442                    rotationX = a.getFloat(attr, 0);
4443                    transformSet = true;
4444                    break;
4445                case com.android.internal.R.styleable.View_rotationY:
4446                    rotationY = a.getFloat(attr, 0);
4447                    transformSet = true;
4448                    break;
4449                case com.android.internal.R.styleable.View_scaleX:
4450                    sx = a.getFloat(attr, 1f);
4451                    transformSet = true;
4452                    break;
4453                case com.android.internal.R.styleable.View_scaleY:
4454                    sy = a.getFloat(attr, 1f);
4455                    transformSet = true;
4456                    break;
4457                case com.android.internal.R.styleable.View_id:
4458                    mID = a.getResourceId(attr, NO_ID);
4459                    break;
4460                case com.android.internal.R.styleable.View_tag:
4461                    mTag = a.getText(attr);
4462                    break;
4463                case com.android.internal.R.styleable.View_fitsSystemWindows:
4464                    if (a.getBoolean(attr, false)) {
4465                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4466                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4467                    }
4468                    break;
4469                case com.android.internal.R.styleable.View_focusable:
4470                    if (a.getBoolean(attr, false)) {
4471                        viewFlagValues |= FOCUSABLE;
4472                        viewFlagMasks |= FOCUSABLE_MASK;
4473                    }
4474                    break;
4475                case com.android.internal.R.styleable.View_focusableInTouchMode:
4476                    if (a.getBoolean(attr, false)) {
4477                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4478                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4479                    }
4480                    break;
4481                case com.android.internal.R.styleable.View_clickable:
4482                    if (a.getBoolean(attr, false)) {
4483                        viewFlagValues |= CLICKABLE;
4484                        viewFlagMasks |= CLICKABLE;
4485                    }
4486                    break;
4487                case com.android.internal.R.styleable.View_longClickable:
4488                    if (a.getBoolean(attr, false)) {
4489                        viewFlagValues |= LONG_CLICKABLE;
4490                        viewFlagMasks |= LONG_CLICKABLE;
4491                    }
4492                    break;
4493                case com.android.internal.R.styleable.View_contextClickable:
4494                    if (a.getBoolean(attr, false)) {
4495                        viewFlagValues |= CONTEXT_CLICKABLE;
4496                        viewFlagMasks |= CONTEXT_CLICKABLE;
4497                    }
4498                    break;
4499                case com.android.internal.R.styleable.View_saveEnabled:
4500                    if (!a.getBoolean(attr, true)) {
4501                        viewFlagValues |= SAVE_DISABLED;
4502                        viewFlagMasks |= SAVE_DISABLED_MASK;
4503                    }
4504                    break;
4505                case com.android.internal.R.styleable.View_duplicateParentState:
4506                    if (a.getBoolean(attr, false)) {
4507                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4508                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4509                    }
4510                    break;
4511                case com.android.internal.R.styleable.View_visibility:
4512                    final int visibility = a.getInt(attr, 0);
4513                    if (visibility != 0) {
4514                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4515                        viewFlagMasks |= VISIBILITY_MASK;
4516                    }
4517                    break;
4518                case com.android.internal.R.styleable.View_layoutDirection:
4519                    // Clear any layout direction flags (included resolved bits) already set
4520                    mPrivateFlags2 &=
4521                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4522                    // Set the layout direction flags depending on the value of the attribute
4523                    final int layoutDirection = a.getInt(attr, -1);
4524                    final int value = (layoutDirection != -1) ?
4525                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4526                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4527                    break;
4528                case com.android.internal.R.styleable.View_drawingCacheQuality:
4529                    final int cacheQuality = a.getInt(attr, 0);
4530                    if (cacheQuality != 0) {
4531                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4532                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4533                    }
4534                    break;
4535                case com.android.internal.R.styleable.View_contentDescription:
4536                    setContentDescription(a.getString(attr));
4537                    break;
4538                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4539                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4540                    break;
4541                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4542                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4543                    break;
4544                case com.android.internal.R.styleable.View_labelFor:
4545                    setLabelFor(a.getResourceId(attr, NO_ID));
4546                    break;
4547                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4548                    if (!a.getBoolean(attr, true)) {
4549                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4550                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4551                    }
4552                    break;
4553                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4554                    if (!a.getBoolean(attr, true)) {
4555                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4556                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4557                    }
4558                    break;
4559                case R.styleable.View_scrollbars:
4560                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4561                    if (scrollbars != SCROLLBARS_NONE) {
4562                        viewFlagValues |= scrollbars;
4563                        viewFlagMasks |= SCROLLBARS_MASK;
4564                        initializeScrollbars = true;
4565                    }
4566                    break;
4567                //noinspection deprecation
4568                case R.styleable.View_fadingEdge:
4569                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4570                        // Ignore the attribute starting with ICS
4571                        break;
4572                    }
4573                    // With builds < ICS, fall through and apply fading edges
4574                case R.styleable.View_requiresFadingEdge:
4575                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4576                    if (fadingEdge != FADING_EDGE_NONE) {
4577                        viewFlagValues |= fadingEdge;
4578                        viewFlagMasks |= FADING_EDGE_MASK;
4579                        initializeFadingEdgeInternal(a);
4580                    }
4581                    break;
4582                case R.styleable.View_scrollbarStyle:
4583                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4584                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4585                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4586                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4587                    }
4588                    break;
4589                case R.styleable.View_isScrollContainer:
4590                    setScrollContainer = true;
4591                    if (a.getBoolean(attr, false)) {
4592                        setScrollContainer(true);
4593                    }
4594                    break;
4595                case com.android.internal.R.styleable.View_keepScreenOn:
4596                    if (a.getBoolean(attr, false)) {
4597                        viewFlagValues |= KEEP_SCREEN_ON;
4598                        viewFlagMasks |= KEEP_SCREEN_ON;
4599                    }
4600                    break;
4601                case R.styleable.View_filterTouchesWhenObscured:
4602                    if (a.getBoolean(attr, false)) {
4603                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4604                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4605                    }
4606                    break;
4607                case R.styleable.View_nextFocusLeft:
4608                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4609                    break;
4610                case R.styleable.View_nextFocusRight:
4611                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4612                    break;
4613                case R.styleable.View_nextFocusUp:
4614                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4615                    break;
4616                case R.styleable.View_nextFocusDown:
4617                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4618                    break;
4619                case R.styleable.View_nextFocusForward:
4620                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4621                    break;
4622                case R.styleable.View_nextClusterForward:
4623                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
4624                    break;
4625                case R.styleable.View_nextSectionForward:
4626                    mNextSectionForwardId = a.getResourceId(attr, View.NO_ID);
4627                    break;
4628                case R.styleable.View_minWidth:
4629                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4630                    break;
4631                case R.styleable.View_minHeight:
4632                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4633                    break;
4634                case R.styleable.View_onClick:
4635                    if (context.isRestricted()) {
4636                        throw new IllegalStateException("The android:onClick attribute cannot "
4637                                + "be used within a restricted context");
4638                    }
4639
4640                    final String handlerName = a.getString(attr);
4641                    if (handlerName != null) {
4642                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4643                    }
4644                    break;
4645                case R.styleable.View_overScrollMode:
4646                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4647                    break;
4648                case R.styleable.View_verticalScrollbarPosition:
4649                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4650                    break;
4651                case R.styleable.View_layerType:
4652                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4653                    break;
4654                case R.styleable.View_textDirection:
4655                    // Clear any text direction flag already set
4656                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4657                    // Set the text direction flags depending on the value of the attribute
4658                    final int textDirection = a.getInt(attr, -1);
4659                    if (textDirection != -1) {
4660                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4661                    }
4662                    break;
4663                case R.styleable.View_textAlignment:
4664                    // Clear any text alignment flag already set
4665                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4666                    // Set the text alignment flag depending on the value of the attribute
4667                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4668                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4669                    break;
4670                case R.styleable.View_importantForAccessibility:
4671                    setImportantForAccessibility(a.getInt(attr,
4672                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4673                    break;
4674                case R.styleable.View_accessibilityLiveRegion:
4675                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4676                    break;
4677                case R.styleable.View_transitionName:
4678                    setTransitionName(a.getString(attr));
4679                    break;
4680                case R.styleable.View_nestedScrollingEnabled:
4681                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4682                    break;
4683                case R.styleable.View_stateListAnimator:
4684                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4685                            a.getResourceId(attr, 0)));
4686                    break;
4687                case R.styleable.View_backgroundTint:
4688                    // This will get applied later during setBackground().
4689                    if (mBackgroundTint == null) {
4690                        mBackgroundTint = new TintInfo();
4691                    }
4692                    mBackgroundTint.mTintList = a.getColorStateList(
4693                            R.styleable.View_backgroundTint);
4694                    mBackgroundTint.mHasTintList = true;
4695                    break;
4696                case R.styleable.View_backgroundTintMode:
4697                    // This will get applied later during setBackground().
4698                    if (mBackgroundTint == null) {
4699                        mBackgroundTint = new TintInfo();
4700                    }
4701                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4702                            R.styleable.View_backgroundTintMode, -1), null);
4703                    mBackgroundTint.mHasTintMode = true;
4704                    break;
4705                case R.styleable.View_outlineProvider:
4706                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4707                            PROVIDER_BACKGROUND));
4708                    break;
4709                case R.styleable.View_foreground:
4710                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4711                        setForeground(a.getDrawable(attr));
4712                    }
4713                    break;
4714                case R.styleable.View_foregroundGravity:
4715                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4716                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4717                    }
4718                    break;
4719                case R.styleable.View_foregroundTintMode:
4720                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4721                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4722                    }
4723                    break;
4724                case R.styleable.View_foregroundTint:
4725                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4726                        setForegroundTintList(a.getColorStateList(attr));
4727                    }
4728                    break;
4729                case R.styleable.View_foregroundInsidePadding:
4730                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4731                        if (mForegroundInfo == null) {
4732                            mForegroundInfo = new ForegroundInfo();
4733                        }
4734                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4735                                mForegroundInfo.mInsidePadding);
4736                    }
4737                    break;
4738                case R.styleable.View_scrollIndicators:
4739                    final int scrollIndicators =
4740                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4741                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4742                    if (scrollIndicators != 0) {
4743                        mPrivateFlags3 |= scrollIndicators;
4744                        initializeScrollIndicators = true;
4745                    }
4746                    break;
4747                case R.styleable.View_pointerIcon:
4748                    final int resourceId = a.getResourceId(attr, 0);
4749                    if (resourceId != 0) {
4750                        setPointerIcon(PointerIcon.load(
4751                                context.getResources(), resourceId));
4752                    } else {
4753                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4754                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4755                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4756                        }
4757                    }
4758                    break;
4759                case R.styleable.View_forceHasOverlappingRendering:
4760                    if (a.peekValue(attr) != null) {
4761                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4762                    }
4763                    break;
4764                case R.styleable.View_tooltip:
4765                    setTooltip(a.getText(attr));
4766                    break;
4767                case R.styleable.View_keyboardNavigationCluster:
4768                    if (a.peekValue(attr) != null) {
4769                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
4770                    }
4771                    break;
4772                case R.styleable.View_keyboardNavigationSection:
4773                    if (a.peekValue(attr) != null) {
4774                        setKeyboardNavigationSection(a.getBoolean(attr, true));
4775                    }
4776                    break;
4777                case R.styleable.View_focusedByDefault:
4778                    if (a.peekValue(attr) != null) {
4779                        setFocusedByDefault(a.getBoolean(attr, true));
4780                    }
4781                    break;
4782            }
4783        }
4784
4785        setOverScrollMode(overScrollMode);
4786
4787        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4788        // the resolved layout direction). Those cached values will be used later during padding
4789        // resolution.
4790        mUserPaddingStart = startPadding;
4791        mUserPaddingEnd = endPadding;
4792
4793        if (background != null) {
4794            setBackground(background);
4795        }
4796
4797        // setBackground above will record that padding is currently provided by the background.
4798        // If we have padding specified via xml, record that here instead and use it.
4799        mLeftPaddingDefined = leftPaddingDefined;
4800        mRightPaddingDefined = rightPaddingDefined;
4801
4802        if (padding >= 0) {
4803            leftPadding = padding;
4804            topPadding = padding;
4805            rightPadding = padding;
4806            bottomPadding = padding;
4807            mUserPaddingLeftInitial = padding;
4808            mUserPaddingRightInitial = padding;
4809        } else {
4810            if (paddingHorizontal >= 0) {
4811                leftPadding = paddingHorizontal;
4812                rightPadding = paddingHorizontal;
4813                mUserPaddingLeftInitial = paddingHorizontal;
4814                mUserPaddingRightInitial = paddingHorizontal;
4815            }
4816            if (paddingVertical >= 0) {
4817                topPadding = paddingVertical;
4818                bottomPadding = paddingVertical;
4819            }
4820        }
4821
4822        if (isRtlCompatibilityMode()) {
4823            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4824            // left / right padding are used if defined (meaning here nothing to do). If they are not
4825            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4826            // start / end and resolve them as left / right (layout direction is not taken into account).
4827            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4828            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4829            // defined.
4830            if (!mLeftPaddingDefined && startPaddingDefined) {
4831                leftPadding = startPadding;
4832            }
4833            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4834            if (!mRightPaddingDefined && endPaddingDefined) {
4835                rightPadding = endPadding;
4836            }
4837            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4838        } else {
4839            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4840            // values defined. Otherwise, left /right values are used.
4841            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4842            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4843            // defined.
4844            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4845
4846            if (mLeftPaddingDefined && !hasRelativePadding) {
4847                mUserPaddingLeftInitial = leftPadding;
4848            }
4849            if (mRightPaddingDefined && !hasRelativePadding) {
4850                mUserPaddingRightInitial = rightPadding;
4851            }
4852        }
4853
4854        internalSetPadding(
4855                mUserPaddingLeftInitial,
4856                topPadding >= 0 ? topPadding : mPaddingTop,
4857                mUserPaddingRightInitial,
4858                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4859
4860        if (viewFlagMasks != 0) {
4861            setFlags(viewFlagValues, viewFlagMasks);
4862        }
4863
4864        if (initializeScrollbars) {
4865            initializeScrollbarsInternal(a);
4866        }
4867
4868        if (initializeScrollIndicators) {
4869            initializeScrollIndicatorsInternal();
4870        }
4871
4872        a.recycle();
4873
4874        // Needs to be called after mViewFlags is set
4875        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4876            recomputePadding();
4877        }
4878
4879        if (x != 0 || y != 0) {
4880            scrollTo(x, y);
4881        }
4882
4883        if (transformSet) {
4884            setTranslationX(tx);
4885            setTranslationY(ty);
4886            setTranslationZ(tz);
4887            setElevation(elevation);
4888            setRotation(rotation);
4889            setRotationX(rotationX);
4890            setRotationY(rotationY);
4891            setScaleX(sx);
4892            setScaleY(sy);
4893        }
4894
4895        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4896            setScrollContainer(true);
4897        }
4898
4899        computeOpaqueFlags();
4900    }
4901
4902    /**
4903     * An implementation of OnClickListener that attempts to lazily load a
4904     * named click handling method from a parent or ancestor context.
4905     */
4906    private static class DeclaredOnClickListener implements OnClickListener {
4907        private final View mHostView;
4908        private final String mMethodName;
4909
4910        private Method mResolvedMethod;
4911        private Context mResolvedContext;
4912
4913        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4914            mHostView = hostView;
4915            mMethodName = methodName;
4916        }
4917
4918        @Override
4919        public void onClick(@NonNull View v) {
4920            if (mResolvedMethod == null) {
4921                resolveMethod(mHostView.getContext(), mMethodName);
4922            }
4923
4924            try {
4925                mResolvedMethod.invoke(mResolvedContext, v);
4926            } catch (IllegalAccessException e) {
4927                throw new IllegalStateException(
4928                        "Could not execute non-public method for android:onClick", e);
4929            } catch (InvocationTargetException e) {
4930                throw new IllegalStateException(
4931                        "Could not execute method for android:onClick", e);
4932            }
4933        }
4934
4935        @NonNull
4936        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4937            while (context != null) {
4938                try {
4939                    if (!context.isRestricted()) {
4940                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4941                        if (method != null) {
4942                            mResolvedMethod = method;
4943                            mResolvedContext = context;
4944                            return;
4945                        }
4946                    }
4947                } catch (NoSuchMethodException e) {
4948                    // Failed to find method, keep searching up the hierarchy.
4949                }
4950
4951                if (context instanceof ContextWrapper) {
4952                    context = ((ContextWrapper) context).getBaseContext();
4953                } else {
4954                    // Can't search up the hierarchy, null out and fail.
4955                    context = null;
4956                }
4957            }
4958
4959            final int id = mHostView.getId();
4960            final String idText = id == NO_ID ? "" : " with id '"
4961                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4962            throw new IllegalStateException("Could not find method " + mMethodName
4963                    + "(View) in a parent or ancestor Context for android:onClick "
4964                    + "attribute defined on view " + mHostView.getClass() + idText);
4965        }
4966    }
4967
4968    /**
4969     * Non-public constructor for use in testing
4970     */
4971    View() {
4972        mResources = null;
4973        mRenderNode = RenderNode.create(getClass().getName(), this);
4974    }
4975
4976    final boolean debugDraw() {
4977        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
4978    }
4979
4980    private static SparseArray<String> getAttributeMap() {
4981        if (mAttributeMap == null) {
4982            mAttributeMap = new SparseArray<>();
4983        }
4984        return mAttributeMap;
4985    }
4986
4987    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4988        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4989        final int indexCount = t.getIndexCount();
4990        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4991
4992        int i = 0;
4993
4994        // Store raw XML attributes.
4995        for (int j = 0; j < attrsCount; ++j) {
4996            attributes[i] = attrs.getAttributeName(j);
4997            attributes[i + 1] = attrs.getAttributeValue(j);
4998            i += 2;
4999        }
5000
5001        // Store resolved styleable attributes.
5002        final Resources res = t.getResources();
5003        final SparseArray<String> attributeMap = getAttributeMap();
5004        for (int j = 0; j < indexCount; ++j) {
5005            final int index = t.getIndex(j);
5006            if (!t.hasValueOrEmpty(index)) {
5007                // Value is undefined. Skip it.
5008                continue;
5009            }
5010
5011            final int resourceId = t.getResourceId(index, 0);
5012            if (resourceId == 0) {
5013                // Value is not a reference. Skip it.
5014                continue;
5015            }
5016
5017            String resourceName = attributeMap.get(resourceId);
5018            if (resourceName == null) {
5019                try {
5020                    resourceName = res.getResourceName(resourceId);
5021                } catch (Resources.NotFoundException e) {
5022                    resourceName = "0x" + Integer.toHexString(resourceId);
5023                }
5024                attributeMap.put(resourceId, resourceName);
5025            }
5026
5027            attributes[i] = resourceName;
5028            attributes[i + 1] = t.getString(index);
5029            i += 2;
5030        }
5031
5032        // Trim to fit contents.
5033        final String[] trimmed = new String[i];
5034        System.arraycopy(attributes, 0, trimmed, 0, i);
5035        mAttributes = trimmed;
5036    }
5037
5038    public String toString() {
5039        StringBuilder out = new StringBuilder(128);
5040        out.append(getClass().getName());
5041        out.append('{');
5042        out.append(Integer.toHexString(System.identityHashCode(this)));
5043        out.append(' ');
5044        switch (mViewFlags&VISIBILITY_MASK) {
5045            case VISIBLE: out.append('V'); break;
5046            case INVISIBLE: out.append('I'); break;
5047            case GONE: out.append('G'); break;
5048            default: out.append('.'); break;
5049        }
5050        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
5051        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5052        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5053        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5054        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5055        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5056        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5057        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5058        out.append(' ');
5059        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5060        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5061        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5062        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5063            out.append('p');
5064        } else {
5065            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5066        }
5067        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5068        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5069        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5070        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5071        out.append(' ');
5072        out.append(mLeft);
5073        out.append(',');
5074        out.append(mTop);
5075        out.append('-');
5076        out.append(mRight);
5077        out.append(',');
5078        out.append(mBottom);
5079        final int id = getId();
5080        if (id != NO_ID) {
5081            out.append(" #");
5082            out.append(Integer.toHexString(id));
5083            final Resources r = mResources;
5084            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5085                try {
5086                    String pkgname;
5087                    switch (id&0xff000000) {
5088                        case 0x7f000000:
5089                            pkgname="app";
5090                            break;
5091                        case 0x01000000:
5092                            pkgname="android";
5093                            break;
5094                        default:
5095                            pkgname = r.getResourcePackageName(id);
5096                            break;
5097                    }
5098                    String typename = r.getResourceTypeName(id);
5099                    String entryname = r.getResourceEntryName(id);
5100                    out.append(" ");
5101                    out.append(pkgname);
5102                    out.append(":");
5103                    out.append(typename);
5104                    out.append("/");
5105                    out.append(entryname);
5106                } catch (Resources.NotFoundException e) {
5107                }
5108            }
5109        }
5110        out.append("}");
5111        return out.toString();
5112    }
5113
5114    /**
5115     * <p>
5116     * Initializes the fading edges from a given set of styled attributes. This
5117     * method should be called by subclasses that need fading edges and when an
5118     * instance of these subclasses is created programmatically rather than
5119     * being inflated from XML. This method is automatically called when the XML
5120     * is inflated.
5121     * </p>
5122     *
5123     * @param a the styled attributes set to initialize the fading edges from
5124     *
5125     * @removed
5126     */
5127    protected void initializeFadingEdge(TypedArray a) {
5128        // This method probably shouldn't have been included in the SDK to begin with.
5129        // It relies on 'a' having been initialized using an attribute filter array that is
5130        // not publicly available to the SDK. The old method has been renamed
5131        // to initializeFadingEdgeInternal and hidden for framework use only;
5132        // this one initializes using defaults to make it safe to call for apps.
5133
5134        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5135
5136        initializeFadingEdgeInternal(arr);
5137
5138        arr.recycle();
5139    }
5140
5141    /**
5142     * <p>
5143     * Initializes the fading edges from a given set of styled attributes. This
5144     * method should be called by subclasses that need fading edges and when an
5145     * instance of these subclasses is created programmatically rather than
5146     * being inflated from XML. This method is automatically called when the XML
5147     * is inflated.
5148     * </p>
5149     *
5150     * @param a the styled attributes set to initialize the fading edges from
5151     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5152     */
5153    protected void initializeFadingEdgeInternal(TypedArray a) {
5154        initScrollCache();
5155
5156        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5157                R.styleable.View_fadingEdgeLength,
5158                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5159    }
5160
5161    /**
5162     * Returns the size of the vertical faded edges used to indicate that more
5163     * content in this view is visible.
5164     *
5165     * @return The size in pixels of the vertical faded edge or 0 if vertical
5166     *         faded edges are not enabled for this view.
5167     * @attr ref android.R.styleable#View_fadingEdgeLength
5168     */
5169    public int getVerticalFadingEdgeLength() {
5170        if (isVerticalFadingEdgeEnabled()) {
5171            ScrollabilityCache cache = mScrollCache;
5172            if (cache != null) {
5173                return cache.fadingEdgeLength;
5174            }
5175        }
5176        return 0;
5177    }
5178
5179    /**
5180     * Set the size of the faded edge used to indicate that more content in this
5181     * view is available.  Will not change whether the fading edge is enabled; use
5182     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5183     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5184     * for the vertical or horizontal fading edges.
5185     *
5186     * @param length The size in pixels of the faded edge used to indicate that more
5187     *        content in this view is visible.
5188     */
5189    public void setFadingEdgeLength(int length) {
5190        initScrollCache();
5191        mScrollCache.fadingEdgeLength = length;
5192    }
5193
5194    /**
5195     * Returns the size of the horizontal faded edges used to indicate that more
5196     * content in this view is visible.
5197     *
5198     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5199     *         faded edges are not enabled for this view.
5200     * @attr ref android.R.styleable#View_fadingEdgeLength
5201     */
5202    public int getHorizontalFadingEdgeLength() {
5203        if (isHorizontalFadingEdgeEnabled()) {
5204            ScrollabilityCache cache = mScrollCache;
5205            if (cache != null) {
5206                return cache.fadingEdgeLength;
5207            }
5208        }
5209        return 0;
5210    }
5211
5212    /**
5213     * Returns the width of the vertical scrollbar.
5214     *
5215     * @return The width in pixels of the vertical scrollbar or 0 if there
5216     *         is no vertical scrollbar.
5217     */
5218    public int getVerticalScrollbarWidth() {
5219        ScrollabilityCache cache = mScrollCache;
5220        if (cache != null) {
5221            ScrollBarDrawable scrollBar = cache.scrollBar;
5222            if (scrollBar != null) {
5223                int size = scrollBar.getSize(true);
5224                if (size <= 0) {
5225                    size = cache.scrollBarSize;
5226                }
5227                return size;
5228            }
5229            return 0;
5230        }
5231        return 0;
5232    }
5233
5234    /**
5235     * Returns the height of the horizontal scrollbar.
5236     *
5237     * @return The height in pixels of the horizontal scrollbar or 0 if
5238     *         there is no horizontal scrollbar.
5239     */
5240    protected int getHorizontalScrollbarHeight() {
5241        ScrollabilityCache cache = mScrollCache;
5242        if (cache != null) {
5243            ScrollBarDrawable scrollBar = cache.scrollBar;
5244            if (scrollBar != null) {
5245                int size = scrollBar.getSize(false);
5246                if (size <= 0) {
5247                    size = cache.scrollBarSize;
5248                }
5249                return size;
5250            }
5251            return 0;
5252        }
5253        return 0;
5254    }
5255
5256    /**
5257     * <p>
5258     * Initializes the scrollbars from a given set of styled attributes. This
5259     * method should be called by subclasses that need scrollbars and when an
5260     * instance of these subclasses is created programmatically rather than
5261     * being inflated from XML. This method is automatically called when the XML
5262     * is inflated.
5263     * </p>
5264     *
5265     * @param a the styled attributes set to initialize the scrollbars from
5266     *
5267     * @removed
5268     */
5269    protected void initializeScrollbars(TypedArray a) {
5270        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5271        // using the View filter array which is not available to the SDK. As such, internal
5272        // framework usage now uses initializeScrollbarsInternal and we grab a default
5273        // TypedArray with the right filter instead here.
5274        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5275
5276        initializeScrollbarsInternal(arr);
5277
5278        // We ignored the method parameter. Recycle the one we actually did use.
5279        arr.recycle();
5280    }
5281
5282    /**
5283     * <p>
5284     * Initializes the scrollbars from a given set of styled attributes. This
5285     * method should be called by subclasses that need scrollbars and when an
5286     * instance of these subclasses is created programmatically rather than
5287     * being inflated from XML. This method is automatically called when the XML
5288     * is inflated.
5289     * </p>
5290     *
5291     * @param a the styled attributes set to initialize the scrollbars from
5292     * @hide
5293     */
5294    protected void initializeScrollbarsInternal(TypedArray a) {
5295        initScrollCache();
5296
5297        final ScrollabilityCache scrollabilityCache = mScrollCache;
5298
5299        if (scrollabilityCache.scrollBar == null) {
5300            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5301            scrollabilityCache.scrollBar.setState(getDrawableState());
5302            scrollabilityCache.scrollBar.setCallback(this);
5303        }
5304
5305        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5306
5307        if (!fadeScrollbars) {
5308            scrollabilityCache.state = ScrollabilityCache.ON;
5309        }
5310        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5311
5312
5313        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5314                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5315                        .getScrollBarFadeDuration());
5316        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5317                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5318                ViewConfiguration.getScrollDefaultDelay());
5319
5320
5321        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5322                com.android.internal.R.styleable.View_scrollbarSize,
5323                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5324
5325        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5326        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5327
5328        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5329        if (thumb != null) {
5330            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5331        }
5332
5333        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5334                false);
5335        if (alwaysDraw) {
5336            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5337        }
5338
5339        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5340        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5341
5342        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5343        if (thumb != null) {
5344            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5345        }
5346
5347        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5348                false);
5349        if (alwaysDraw) {
5350            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5351        }
5352
5353        // Apply layout direction to the new Drawables if needed
5354        final int layoutDirection = getLayoutDirection();
5355        if (track != null) {
5356            track.setLayoutDirection(layoutDirection);
5357        }
5358        if (thumb != null) {
5359            thumb.setLayoutDirection(layoutDirection);
5360        }
5361
5362        // Re-apply user/background padding so that scrollbar(s) get added
5363        resolvePadding();
5364    }
5365
5366    private void initializeScrollIndicatorsInternal() {
5367        // Some day maybe we'll break this into top/left/start/etc. and let the
5368        // client control it. Until then, you can have any scroll indicator you
5369        // want as long as it's a 1dp foreground-colored rectangle.
5370        if (mScrollIndicatorDrawable == null) {
5371            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5372        }
5373    }
5374
5375    /**
5376     * <p>
5377     * Initalizes the scrollability cache if necessary.
5378     * </p>
5379     */
5380    private void initScrollCache() {
5381        if (mScrollCache == null) {
5382            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5383        }
5384    }
5385
5386    private ScrollabilityCache getScrollCache() {
5387        initScrollCache();
5388        return mScrollCache;
5389    }
5390
5391    /**
5392     * Set the position of the vertical scroll bar. Should be one of
5393     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5394     * {@link #SCROLLBAR_POSITION_RIGHT}.
5395     *
5396     * @param position Where the vertical scroll bar should be positioned.
5397     */
5398    public void setVerticalScrollbarPosition(int position) {
5399        if (mVerticalScrollbarPosition != position) {
5400            mVerticalScrollbarPosition = position;
5401            computeOpaqueFlags();
5402            resolvePadding();
5403        }
5404    }
5405
5406    /**
5407     * @return The position where the vertical scroll bar will show, if applicable.
5408     * @see #setVerticalScrollbarPosition(int)
5409     */
5410    public int getVerticalScrollbarPosition() {
5411        return mVerticalScrollbarPosition;
5412    }
5413
5414    boolean isOnScrollbar(float x, float y) {
5415        if (mScrollCache == null) {
5416            return false;
5417        }
5418        x += getScrollX();
5419        y += getScrollY();
5420        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5421            final Rect bounds = mScrollCache.mScrollBarBounds;
5422            getVerticalScrollBarBounds(bounds);
5423            if (bounds.contains((int)x, (int)y)) {
5424                return true;
5425            }
5426        }
5427        if (isHorizontalScrollBarEnabled()) {
5428            final Rect bounds = mScrollCache.mScrollBarBounds;
5429            getHorizontalScrollBarBounds(bounds);
5430            if (bounds.contains((int)x, (int)y)) {
5431                return true;
5432            }
5433        }
5434        return false;
5435    }
5436
5437    boolean isOnScrollbarThumb(float x, float y) {
5438        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5439    }
5440
5441    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5442        if (mScrollCache == null) {
5443            return false;
5444        }
5445        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5446            x += getScrollX();
5447            y += getScrollY();
5448            final Rect bounds = mScrollCache.mScrollBarBounds;
5449            getVerticalScrollBarBounds(bounds);
5450            final int range = computeVerticalScrollRange();
5451            final int offset = computeVerticalScrollOffset();
5452            final int extent = computeVerticalScrollExtent();
5453            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5454                    extent, range);
5455            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5456                    extent, range, offset);
5457            final int thumbTop = bounds.top + thumbOffset;
5458            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5459                    && y <= thumbTop + thumbLength) {
5460                return true;
5461            }
5462        }
5463        return false;
5464    }
5465
5466    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5467        if (mScrollCache == null) {
5468            return false;
5469        }
5470        if (isHorizontalScrollBarEnabled()) {
5471            x += getScrollX();
5472            y += getScrollY();
5473            final Rect bounds = mScrollCache.mScrollBarBounds;
5474            getHorizontalScrollBarBounds(bounds);
5475            final int range = computeHorizontalScrollRange();
5476            final int offset = computeHorizontalScrollOffset();
5477            final int extent = computeHorizontalScrollExtent();
5478            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5479                    extent, range);
5480            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5481                    extent, range, offset);
5482            final int thumbLeft = bounds.left + thumbOffset;
5483            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5484                    && y <= bounds.bottom) {
5485                return true;
5486            }
5487        }
5488        return false;
5489    }
5490
5491    boolean isDraggingScrollBar() {
5492        return mScrollCache != null
5493                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5494    }
5495
5496    /**
5497     * Sets the state of all scroll indicators.
5498     * <p>
5499     * See {@link #setScrollIndicators(int, int)} for usage information.
5500     *
5501     * @param indicators a bitmask of indicators that should be enabled, or
5502     *                   {@code 0} to disable all indicators
5503     * @see #setScrollIndicators(int, int)
5504     * @see #getScrollIndicators()
5505     * @attr ref android.R.styleable#View_scrollIndicators
5506     */
5507    public void setScrollIndicators(@ScrollIndicators int indicators) {
5508        setScrollIndicators(indicators,
5509                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5510    }
5511
5512    /**
5513     * Sets the state of the scroll indicators specified by the mask. To change
5514     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5515     * <p>
5516     * When a scroll indicator is enabled, it will be displayed if the view
5517     * can scroll in the direction of the indicator.
5518     * <p>
5519     * Multiple indicator types may be enabled or disabled by passing the
5520     * logical OR of the desired types. If multiple types are specified, they
5521     * will all be set to the same enabled state.
5522     * <p>
5523     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5524     *
5525     * @param indicators the indicator direction, or the logical OR of multiple
5526     *             indicator directions. One or more of:
5527     *             <ul>
5528     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5529     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5530     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5531     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5532     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5533     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5534     *             </ul>
5535     * @see #setScrollIndicators(int)
5536     * @see #getScrollIndicators()
5537     * @attr ref android.R.styleable#View_scrollIndicators
5538     */
5539    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5540        // Shift and sanitize mask.
5541        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5542        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5543
5544        // Shift and mask indicators.
5545        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5546        indicators &= mask;
5547
5548        // Merge with non-masked flags.
5549        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5550
5551        if (mPrivateFlags3 != updatedFlags) {
5552            mPrivateFlags3 = updatedFlags;
5553
5554            if (indicators != 0) {
5555                initializeScrollIndicatorsInternal();
5556            }
5557            invalidate();
5558        }
5559    }
5560
5561    /**
5562     * Returns a bitmask representing the enabled scroll indicators.
5563     * <p>
5564     * For example, if the top and left scroll indicators are enabled and all
5565     * other indicators are disabled, the return value will be
5566     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5567     * <p>
5568     * To check whether the bottom scroll indicator is enabled, use the value
5569     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5570     *
5571     * @return a bitmask representing the enabled scroll indicators
5572     */
5573    @ScrollIndicators
5574    public int getScrollIndicators() {
5575        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5576                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5577    }
5578
5579    ListenerInfo getListenerInfo() {
5580        if (mListenerInfo != null) {
5581            return mListenerInfo;
5582        }
5583        mListenerInfo = new ListenerInfo();
5584        return mListenerInfo;
5585    }
5586
5587    /**
5588     * Register a callback to be invoked when the scroll X or Y positions of
5589     * this view change.
5590     * <p>
5591     * <b>Note:</b> Some views handle scrolling independently from View and may
5592     * have their own separate listeners for scroll-type events. For example,
5593     * {@link android.widget.ListView ListView} allows clients to register an
5594     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5595     * to listen for changes in list scroll position.
5596     *
5597     * @param l The listener to notify when the scroll X or Y position changes.
5598     * @see android.view.View#getScrollX()
5599     * @see android.view.View#getScrollY()
5600     */
5601    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5602        getListenerInfo().mOnScrollChangeListener = l;
5603    }
5604
5605    /**
5606     * Register a callback to be invoked when focus of this view changed.
5607     *
5608     * @param l The callback that will run.
5609     */
5610    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5611        getListenerInfo().mOnFocusChangeListener = l;
5612    }
5613
5614    /**
5615     * Add a listener that will be called when the bounds of the view change due to
5616     * layout processing.
5617     *
5618     * @param listener The listener that will be called when layout bounds change.
5619     */
5620    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5621        ListenerInfo li = getListenerInfo();
5622        if (li.mOnLayoutChangeListeners == null) {
5623            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5624        }
5625        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5626            li.mOnLayoutChangeListeners.add(listener);
5627        }
5628    }
5629
5630    /**
5631     * Remove a listener for layout changes.
5632     *
5633     * @param listener The listener for layout bounds change.
5634     */
5635    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5636        ListenerInfo li = mListenerInfo;
5637        if (li == null || li.mOnLayoutChangeListeners == null) {
5638            return;
5639        }
5640        li.mOnLayoutChangeListeners.remove(listener);
5641    }
5642
5643    /**
5644     * Add a listener for attach state changes.
5645     *
5646     * This listener will be called whenever this view is attached or detached
5647     * from a window. Remove the listener using
5648     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5649     *
5650     * @param listener Listener to attach
5651     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5652     */
5653    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5654        ListenerInfo li = getListenerInfo();
5655        if (li.mOnAttachStateChangeListeners == null) {
5656            li.mOnAttachStateChangeListeners
5657                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5658        }
5659        li.mOnAttachStateChangeListeners.add(listener);
5660    }
5661
5662    /**
5663     * Remove a listener for attach state changes. The listener will receive no further
5664     * notification of window attach/detach events.
5665     *
5666     * @param listener Listener to remove
5667     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5668     */
5669    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5670        ListenerInfo li = mListenerInfo;
5671        if (li == null || li.mOnAttachStateChangeListeners == null) {
5672            return;
5673        }
5674        li.mOnAttachStateChangeListeners.remove(listener);
5675    }
5676
5677    /**
5678     * Returns the focus-change callback registered for this view.
5679     *
5680     * @return The callback, or null if one is not registered.
5681     */
5682    public OnFocusChangeListener getOnFocusChangeListener() {
5683        ListenerInfo li = mListenerInfo;
5684        return li != null ? li.mOnFocusChangeListener : null;
5685    }
5686
5687    /**
5688     * Register a callback to be invoked when this view is clicked. If this view is not
5689     * clickable, it becomes clickable.
5690     *
5691     * @param l The callback that will run
5692     *
5693     * @see #setClickable(boolean)
5694     */
5695    public void setOnClickListener(@Nullable OnClickListener l) {
5696        if (!isClickable()) {
5697            setClickable(true);
5698        }
5699        getListenerInfo().mOnClickListener = l;
5700    }
5701
5702    /**
5703     * Return whether this view has an attached OnClickListener.  Returns
5704     * true if there is a listener, false if there is none.
5705     */
5706    public boolean hasOnClickListeners() {
5707        ListenerInfo li = mListenerInfo;
5708        return (li != null && li.mOnClickListener != null);
5709    }
5710
5711    /**
5712     * Register a callback to be invoked when this view is clicked and held. If this view is not
5713     * long clickable, it becomes long clickable.
5714     *
5715     * @param l The callback that will run
5716     *
5717     * @see #setLongClickable(boolean)
5718     */
5719    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5720        if (!isLongClickable()) {
5721            setLongClickable(true);
5722        }
5723        getListenerInfo().mOnLongClickListener = l;
5724    }
5725
5726    /**
5727     * Register a callback to be invoked when this view is context clicked. If the view is not
5728     * context clickable, it becomes context clickable.
5729     *
5730     * @param l The callback that will run
5731     * @see #setContextClickable(boolean)
5732     */
5733    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5734        if (!isContextClickable()) {
5735            setContextClickable(true);
5736        }
5737        getListenerInfo().mOnContextClickListener = l;
5738    }
5739
5740    /**
5741     * Register a callback to be invoked when the context menu for this view is
5742     * being built. If this view is not long clickable, it becomes long clickable.
5743     *
5744     * @param l The callback that will run
5745     *
5746     */
5747    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5748        if (!isLongClickable()) {
5749            setLongClickable(true);
5750        }
5751        getListenerInfo().mOnCreateContextMenuListener = l;
5752    }
5753
5754    /**
5755     * Set an observer to collect stats for each frame rendered for this view.
5756     *
5757     * @hide
5758     */
5759    public void addFrameMetricsListener(Window window,
5760            Window.OnFrameMetricsAvailableListener listener,
5761            Handler handler) {
5762        if (mAttachInfo != null) {
5763            if (mAttachInfo.mThreadedRenderer != null) {
5764                if (mFrameMetricsObservers == null) {
5765                    mFrameMetricsObservers = new ArrayList<>();
5766                }
5767
5768                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5769                        handler.getLooper(), listener);
5770                mFrameMetricsObservers.add(fmo);
5771                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
5772            } else {
5773                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5774            }
5775        } else {
5776            if (mFrameMetricsObservers == null) {
5777                mFrameMetricsObservers = new ArrayList<>();
5778            }
5779
5780            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5781                    handler.getLooper(), listener);
5782            mFrameMetricsObservers.add(fmo);
5783        }
5784    }
5785
5786    /**
5787     * Remove observer configured to collect frame stats for this view.
5788     *
5789     * @hide
5790     */
5791    public void removeFrameMetricsListener(
5792            Window.OnFrameMetricsAvailableListener listener) {
5793        ThreadedRenderer renderer = getThreadedRenderer();
5794        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5795        if (fmo == null) {
5796            throw new IllegalArgumentException(
5797                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5798        }
5799
5800        if (mFrameMetricsObservers != null) {
5801            mFrameMetricsObservers.remove(fmo);
5802            if (renderer != null) {
5803                renderer.removeFrameMetricsObserver(fmo);
5804            }
5805        }
5806    }
5807
5808    private void registerPendingFrameMetricsObservers() {
5809        if (mFrameMetricsObservers != null) {
5810            ThreadedRenderer renderer = getThreadedRenderer();
5811            if (renderer != null) {
5812                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5813                    renderer.addFrameMetricsObserver(fmo);
5814                }
5815            } else {
5816                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5817            }
5818        }
5819    }
5820
5821    private FrameMetricsObserver findFrameMetricsObserver(
5822            Window.OnFrameMetricsAvailableListener listener) {
5823        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5824            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5825            if (observer.mListener == listener) {
5826                return observer;
5827            }
5828        }
5829
5830        return null;
5831    }
5832
5833    /**
5834     * Call this view's OnClickListener, if it is defined.  Performs all normal
5835     * actions associated with clicking: reporting accessibility event, playing
5836     * a sound, etc.
5837     *
5838     * @return True there was an assigned OnClickListener that was called, false
5839     *         otherwise is returned.
5840     */
5841    public boolean performClick() {
5842        final boolean result;
5843        final ListenerInfo li = mListenerInfo;
5844        if (li != null && li.mOnClickListener != null) {
5845            playSoundEffect(SoundEffectConstants.CLICK);
5846            li.mOnClickListener.onClick(this);
5847            result = true;
5848        } else {
5849            result = false;
5850        }
5851
5852        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5853        return result;
5854    }
5855
5856    /**
5857     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5858     * this only calls the listener, and does not do any associated clicking
5859     * actions like reporting an accessibility event.
5860     *
5861     * @return True there was an assigned OnClickListener that was called, false
5862     *         otherwise is returned.
5863     */
5864    public boolean callOnClick() {
5865        ListenerInfo li = mListenerInfo;
5866        if (li != null && li.mOnClickListener != null) {
5867            li.mOnClickListener.onClick(this);
5868            return true;
5869        }
5870        return false;
5871    }
5872
5873    /**
5874     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5875     * context menu if the OnLongClickListener did not consume the event.
5876     *
5877     * @return {@code true} if one of the above receivers consumed the event,
5878     *         {@code false} otherwise
5879     */
5880    public boolean performLongClick() {
5881        return performLongClickInternal(mLongClickX, mLongClickY);
5882    }
5883
5884    /**
5885     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5886     * context menu if the OnLongClickListener did not consume the event,
5887     * anchoring it to an (x,y) coordinate.
5888     *
5889     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5890     *          to disable anchoring
5891     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5892     *          to disable anchoring
5893     * @return {@code true} if one of the above receivers consumed the event,
5894     *         {@code false} otherwise
5895     */
5896    public boolean performLongClick(float x, float y) {
5897        mLongClickX = x;
5898        mLongClickY = y;
5899        final boolean handled = performLongClick();
5900        mLongClickX = Float.NaN;
5901        mLongClickY = Float.NaN;
5902        return handled;
5903    }
5904
5905    /**
5906     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5907     * context menu if the OnLongClickListener did not consume the event,
5908     * optionally anchoring it to an (x,y) coordinate.
5909     *
5910     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5911     *          to disable anchoring
5912     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5913     *          to disable anchoring
5914     * @return {@code true} if one of the above receivers consumed the event,
5915     *         {@code false} otherwise
5916     */
5917    private boolean performLongClickInternal(float x, float y) {
5918        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5919
5920        boolean handled = false;
5921        final ListenerInfo li = mListenerInfo;
5922        if (li != null && li.mOnLongClickListener != null) {
5923            handled = li.mOnLongClickListener.onLongClick(View.this);
5924        }
5925        if (!handled) {
5926            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5927            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5928        }
5929        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
5930            if (!handled) {
5931                handled = showLongClickTooltip((int) x, (int) y);
5932            }
5933        }
5934        if (handled) {
5935            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5936        }
5937        return handled;
5938    }
5939
5940    /**
5941     * Call this view's OnContextClickListener, if it is defined.
5942     *
5943     * @param x the x coordinate of the context click
5944     * @param y the y coordinate of the context click
5945     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5946     *         otherwise.
5947     */
5948    public boolean performContextClick(float x, float y) {
5949        return performContextClick();
5950    }
5951
5952    /**
5953     * Call this view's OnContextClickListener, if it is defined.
5954     *
5955     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5956     *         otherwise.
5957     */
5958    public boolean performContextClick() {
5959        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5960
5961        boolean handled = false;
5962        ListenerInfo li = mListenerInfo;
5963        if (li != null && li.mOnContextClickListener != null) {
5964            handled = li.mOnContextClickListener.onContextClick(View.this);
5965        }
5966        if (handled) {
5967            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5968        }
5969        return handled;
5970    }
5971
5972    /**
5973     * Performs button-related actions during a touch down event.
5974     *
5975     * @param event The event.
5976     * @return True if the down was consumed.
5977     *
5978     * @hide
5979     */
5980    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5981        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5982            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5983            showContextMenu(event.getX(), event.getY());
5984            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5985            return true;
5986        }
5987        return false;
5988    }
5989
5990    /**
5991     * Shows the context menu for this view.
5992     *
5993     * @return {@code true} if the context menu was shown, {@code false}
5994     *         otherwise
5995     * @see #showContextMenu(float, float)
5996     */
5997    public boolean showContextMenu() {
5998        return getParent().showContextMenuForChild(this);
5999    }
6000
6001    /**
6002     * Shows the context menu for this view anchored to the specified
6003     * view-relative coordinate.
6004     *
6005     * @param x the X coordinate in pixels relative to the view to which the
6006     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6007     * @param y the Y coordinate in pixels relative to the view to which the
6008     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6009     * @return {@code true} if the context menu was shown, {@code false}
6010     *         otherwise
6011     */
6012    public boolean showContextMenu(float x, float y) {
6013        return getParent().showContextMenuForChild(this, x, y);
6014    }
6015
6016    /**
6017     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
6018     *
6019     * @param callback Callback that will control the lifecycle of the action mode
6020     * @return The new action mode if it is started, null otherwise
6021     *
6022     * @see ActionMode
6023     * @see #startActionMode(android.view.ActionMode.Callback, int)
6024     */
6025    public ActionMode startActionMode(ActionMode.Callback callback) {
6026        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6027    }
6028
6029    /**
6030     * Start an action mode with the given type.
6031     *
6032     * @param callback Callback that will control the lifecycle of the action mode
6033     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6034     * @return The new action mode if it is started, null otherwise
6035     *
6036     * @see ActionMode
6037     */
6038    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6039        ViewParent parent = getParent();
6040        if (parent == null) return null;
6041        try {
6042            return parent.startActionModeForChild(this, callback, type);
6043        } catch (AbstractMethodError ame) {
6044            // Older implementations of custom views might not implement this.
6045            return parent.startActionModeForChild(this, callback);
6046        }
6047    }
6048
6049    /**
6050     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6051     * Context, creating a unique View identifier to retrieve the result.
6052     *
6053     * @param intent The Intent to be started.
6054     * @param requestCode The request code to use.
6055     * @hide
6056     */
6057    public void startActivityForResult(Intent intent, int requestCode) {
6058        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6059        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6060    }
6061
6062    /**
6063     * If this View corresponds to the calling who, dispatches the activity result.
6064     * @param who The identifier for the targeted View to receive the result.
6065     * @param requestCode The integer request code originally supplied to
6066     *                    startActivityForResult(), allowing you to identify who this
6067     *                    result came from.
6068     * @param resultCode The integer result code returned by the child activity
6069     *                   through its setResult().
6070     * @param data An Intent, which can return result data to the caller
6071     *               (various data can be attached to Intent "extras").
6072     * @return {@code true} if the activity result was dispatched.
6073     * @hide
6074     */
6075    public boolean dispatchActivityResult(
6076            String who, int requestCode, int resultCode, Intent data) {
6077        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6078            onActivityResult(requestCode, resultCode, data);
6079            mStartActivityRequestWho = null;
6080            return true;
6081        }
6082        return false;
6083    }
6084
6085    /**
6086     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6087     *
6088     * @param requestCode The integer request code originally supplied to
6089     *                    startActivityForResult(), allowing you to identify who this
6090     *                    result came from.
6091     * @param resultCode The integer result code returned by the child activity
6092     *                   through its setResult().
6093     * @param data An Intent, which can return result data to the caller
6094     *               (various data can be attached to Intent "extras").
6095     * @hide
6096     */
6097    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6098        // Do nothing.
6099    }
6100
6101    /**
6102     * Register a callback to be invoked when a hardware key is pressed in this view.
6103     * Key presses in software input methods will generally not trigger the methods of
6104     * this listener.
6105     * @param l the key listener to attach to this view
6106     */
6107    public void setOnKeyListener(OnKeyListener l) {
6108        getListenerInfo().mOnKeyListener = l;
6109    }
6110
6111    /**
6112     * Register a callback to be invoked when a touch event is sent to this view.
6113     * @param l the touch listener to attach to this view
6114     */
6115    public void setOnTouchListener(OnTouchListener l) {
6116        getListenerInfo().mOnTouchListener = l;
6117    }
6118
6119    /**
6120     * Register a callback to be invoked when a generic motion event is sent to this view.
6121     * @param l the generic motion listener to attach to this view
6122     */
6123    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6124        getListenerInfo().mOnGenericMotionListener = l;
6125    }
6126
6127    /**
6128     * Register a callback to be invoked when a hover event is sent to this view.
6129     * @param l the hover listener to attach to this view
6130     */
6131    public void setOnHoverListener(OnHoverListener l) {
6132        getListenerInfo().mOnHoverListener = l;
6133    }
6134
6135    /**
6136     * Register a drag event listener callback object for this View. The parameter is
6137     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6138     * View, the system calls the
6139     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6140     * @param l An implementation of {@link android.view.View.OnDragListener}.
6141     */
6142    public void setOnDragListener(OnDragListener l) {
6143        getListenerInfo().mOnDragListener = l;
6144    }
6145
6146    /**
6147     * Give this view focus. This will cause
6148     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6149     *
6150     * Note: this does not check whether this {@link View} should get focus, it just
6151     * gives it focus no matter what.  It should only be called internally by framework
6152     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6153     *
6154     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6155     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6156     *        focus moved when requestFocus() is called. It may not always
6157     *        apply, in which case use the default View.FOCUS_DOWN.
6158     * @param previouslyFocusedRect The rectangle of the view that had focus
6159     *        prior in this View's coordinate system.
6160     */
6161    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6162        if (DBG) {
6163            System.out.println(this + " requestFocus()");
6164        }
6165
6166        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6167            mPrivateFlags |= PFLAG_FOCUSED;
6168
6169            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6170
6171            if (mParent != null) {
6172                mParent.requestChildFocus(this, this);
6173                if (mParent instanceof ViewGroup) {
6174                    ((ViewGroup) mParent).setDefaultFocus(this);
6175                }
6176            }
6177
6178            if (mAttachInfo != null) {
6179                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6180            }
6181
6182            onFocusChanged(true, direction, previouslyFocusedRect);
6183            refreshDrawableState();
6184        }
6185    }
6186
6187    /**
6188     * Sets this view's preference for reveal behavior when it gains focus.
6189     *
6190     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6191     * this view would prefer to be brought fully into view when it gains focus.
6192     * For example, a text field that a user is meant to type into. Other views such
6193     * as scrolling containers may prefer to opt-out of this behavior.</p>
6194     *
6195     * <p>The default value for views is true, though subclasses may change this
6196     * based on their preferred behavior.</p>
6197     *
6198     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6199     *
6200     * @see #getRevealOnFocusHint()
6201     */
6202    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6203        if (revealOnFocus) {
6204            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6205        } else {
6206            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6207        }
6208    }
6209
6210    /**
6211     * Returns this view's preference for reveal behavior when it gains focus.
6212     *
6213     * <p>When this method returns true for a child view requesting focus, ancestor
6214     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6215     * should make a best effort to make the newly focused child fully visible to the user.
6216     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6217     * other properties affecting visibility to the user as part of the focus change.</p>
6218     *
6219     * @return true if this view would prefer to become fully visible when it gains focus,
6220     *         false if it would prefer not to disrupt scroll positioning
6221     *
6222     * @see #setRevealOnFocusHint(boolean)
6223     */
6224    public final boolean getRevealOnFocusHint() {
6225        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6226    }
6227
6228    /**
6229     * Populates <code>outRect</code> with the hotspot bounds. By default,
6230     * the hotspot bounds are identical to the screen bounds.
6231     *
6232     * @param outRect rect to populate with hotspot bounds
6233     * @hide Only for internal use by views and widgets.
6234     */
6235    public void getHotspotBounds(Rect outRect) {
6236        final Drawable background = getBackground();
6237        if (background != null) {
6238            background.getHotspotBounds(outRect);
6239        } else {
6240            getBoundsOnScreen(outRect);
6241        }
6242    }
6243
6244    /**
6245     * Request that a rectangle of this view be visible on the screen,
6246     * scrolling if necessary just enough.
6247     *
6248     * <p>A View should call this if it maintains some notion of which part
6249     * of its content is interesting.  For example, a text editing view
6250     * should call this when its cursor moves.
6251     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6252     * It should not be affected by which part of the View is currently visible or its scroll
6253     * position.
6254     *
6255     * @param rectangle The rectangle in the View's content coordinate space
6256     * @return Whether any parent scrolled.
6257     */
6258    public boolean requestRectangleOnScreen(Rect rectangle) {
6259        return requestRectangleOnScreen(rectangle, false);
6260    }
6261
6262    /**
6263     * Request that a rectangle of this view be visible on the screen,
6264     * scrolling if necessary just enough.
6265     *
6266     * <p>A View should call this if it maintains some notion of which part
6267     * of its content is interesting.  For example, a text editing view
6268     * should call this when its cursor moves.
6269     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6270     * It should not be affected by which part of the View is currently visible or its scroll
6271     * position.
6272     * <p>When <code>immediate</code> is set to true, scrolling will not be
6273     * animated.
6274     *
6275     * @param rectangle The rectangle in the View's content coordinate space
6276     * @param immediate True to forbid animated scrolling, false otherwise
6277     * @return Whether any parent scrolled.
6278     */
6279    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6280        if (mParent == null) {
6281            return false;
6282        }
6283
6284        View child = this;
6285
6286        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6287        position.set(rectangle);
6288
6289        ViewParent parent = mParent;
6290        boolean scrolled = false;
6291        while (parent != null) {
6292            rectangle.set((int) position.left, (int) position.top,
6293                    (int) position.right, (int) position.bottom);
6294
6295            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6296
6297            if (!(parent instanceof View)) {
6298                break;
6299            }
6300
6301            // move it from child's content coordinate space to parent's content coordinate space
6302            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6303
6304            child = (View) parent;
6305            parent = child.getParent();
6306        }
6307
6308        return scrolled;
6309    }
6310
6311    /**
6312     * Called when this view wants to give up focus. If focus is cleared
6313     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6314     * <p>
6315     * <strong>Note:</strong> When a View clears focus the framework is trying
6316     * to give focus to the first focusable View from the top. Hence, if this
6317     * View is the first from the top that can take focus, then all callbacks
6318     * related to clearing focus will be invoked after which the framework will
6319     * give focus to this view.
6320     * </p>
6321     */
6322    public void clearFocus() {
6323        if (DBG) {
6324            System.out.println(this + " clearFocus()");
6325        }
6326
6327        clearFocusInternal(null, true, true);
6328    }
6329
6330    /**
6331     * Clears focus from the view, optionally propagating the change up through
6332     * the parent hierarchy and requesting that the root view place new focus.
6333     *
6334     * @param propagate whether to propagate the change up through the parent
6335     *            hierarchy
6336     * @param refocus when propagate is true, specifies whether to request the
6337     *            root view place new focus
6338     */
6339    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6340        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6341            mPrivateFlags &= ~PFLAG_FOCUSED;
6342
6343            if (propagate && mParent != null) {
6344                mParent.clearChildFocus(this);
6345            }
6346
6347            onFocusChanged(false, 0, null);
6348            refreshDrawableState();
6349
6350            if (propagate && (!refocus || !rootViewRequestFocus())) {
6351                notifyGlobalFocusCleared(this);
6352            }
6353        }
6354    }
6355
6356    void notifyGlobalFocusCleared(View oldFocus) {
6357        if (oldFocus != null && mAttachInfo != null) {
6358            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6359        }
6360    }
6361
6362    boolean rootViewRequestFocus() {
6363        final View root = getRootView();
6364        return root != null && root.requestFocus();
6365    }
6366
6367    /**
6368     * Called internally by the view system when a new view is getting focus.
6369     * This is what clears the old focus.
6370     * <p>
6371     * <b>NOTE:</b> The parent view's focused child must be updated manually
6372     * after calling this method. Otherwise, the view hierarchy may be left in
6373     * an inconstent state.
6374     */
6375    void unFocus(View focused) {
6376        if (DBG) {
6377            System.out.println(this + " unFocus()");
6378        }
6379
6380        clearFocusInternal(focused, false, false);
6381    }
6382
6383    /**
6384     * Returns true if this view has focus itself, or is the ancestor of the
6385     * view that has focus.
6386     *
6387     * @return True if this view has or contains focus, false otherwise.
6388     */
6389    @ViewDebug.ExportedProperty(category = "focus")
6390    public boolean hasFocus() {
6391        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6392    }
6393
6394    /**
6395     * Returns true if this view is focusable or if it contains a reachable View
6396     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6397     * is a View whose parents do not block descendants focus.
6398     *
6399     * Only {@link #VISIBLE} views are considered focusable.
6400     *
6401     * @return True if the view is focusable or if the view contains a focusable
6402     *         View, false otherwise.
6403     *
6404     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6405     * @see ViewGroup#getTouchscreenBlocksFocus()
6406     */
6407    public boolean hasFocusable() {
6408        if (!isFocusableInTouchMode()) {
6409            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6410                final ViewGroup g = (ViewGroup) p;
6411                if (g.shouldBlockFocusForTouchscreen()) {
6412                    return false;
6413                }
6414            }
6415        }
6416        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6417    }
6418
6419    /**
6420     * Called by the view system when the focus state of this view changes.
6421     * When the focus change event is caused by directional navigation, direction
6422     * and previouslyFocusedRect provide insight into where the focus is coming from.
6423     * When overriding, be sure to call up through to the super class so that
6424     * the standard focus handling will occur.
6425     *
6426     * @param gainFocus True if the View has focus; false otherwise.
6427     * @param direction The direction focus has moved when requestFocus()
6428     *                  is called to give this view focus. Values are
6429     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6430     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6431     *                  It may not always apply, in which case use the default.
6432     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6433     *        system, of the previously focused view.  If applicable, this will be
6434     *        passed in as finer grained information about where the focus is coming
6435     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6436     */
6437    @CallSuper
6438    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6439            @Nullable Rect previouslyFocusedRect) {
6440        if (gainFocus) {
6441            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6442        } else {
6443            notifyViewAccessibilityStateChangedIfNeeded(
6444                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6445        }
6446
6447        InputMethodManager imm = InputMethodManager.peekInstance();
6448        if (!gainFocus) {
6449            if (isPressed()) {
6450                setPressed(false);
6451            }
6452            if (imm != null && mAttachInfo != null
6453                    && mAttachInfo.mHasWindowFocus) {
6454                imm.focusOut(this);
6455            }
6456            onFocusLost();
6457        } else if (imm != null && mAttachInfo != null
6458                && mAttachInfo.mHasWindowFocus) {
6459            imm.focusIn(this);
6460        }
6461
6462        invalidate(true);
6463        ListenerInfo li = mListenerInfo;
6464        if (li != null && li.mOnFocusChangeListener != null) {
6465            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6466        }
6467
6468        if (mAttachInfo != null) {
6469            mAttachInfo.mKeyDispatchState.reset(this);
6470        }
6471    }
6472
6473    /**
6474     * Sends an accessibility event of the given type. If accessibility is
6475     * not enabled this method has no effect. The default implementation calls
6476     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6477     * to populate information about the event source (this View), then calls
6478     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6479     * populate the text content of the event source including its descendants,
6480     * and last calls
6481     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6482     * on its parent to request sending of the event to interested parties.
6483     * <p>
6484     * If an {@link AccessibilityDelegate} has been specified via calling
6485     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6486     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6487     * responsible for handling this call.
6488     * </p>
6489     *
6490     * @param eventType The type of the event to send, as defined by several types from
6491     * {@link android.view.accessibility.AccessibilityEvent}, such as
6492     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6493     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6494     *
6495     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6496     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6497     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6498     * @see AccessibilityDelegate
6499     */
6500    public void sendAccessibilityEvent(int eventType) {
6501        if (mAccessibilityDelegate != null) {
6502            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6503        } else {
6504            sendAccessibilityEventInternal(eventType);
6505        }
6506    }
6507
6508    /**
6509     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6510     * {@link AccessibilityEvent} to make an announcement which is related to some
6511     * sort of a context change for which none of the events representing UI transitions
6512     * is a good fit. For example, announcing a new page in a book. If accessibility
6513     * is not enabled this method does nothing.
6514     *
6515     * @param text The announcement text.
6516     */
6517    public void announceForAccessibility(CharSequence text) {
6518        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6519            AccessibilityEvent event = AccessibilityEvent.obtain(
6520                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6521            onInitializeAccessibilityEvent(event);
6522            event.getText().add(text);
6523            event.setContentDescription(null);
6524            mParent.requestSendAccessibilityEvent(this, event);
6525        }
6526    }
6527
6528    /**
6529     * @see #sendAccessibilityEvent(int)
6530     *
6531     * Note: Called from the default {@link AccessibilityDelegate}.
6532     *
6533     * @hide
6534     */
6535    public void sendAccessibilityEventInternal(int eventType) {
6536        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6537            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6538        }
6539    }
6540
6541    /**
6542     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6543     * takes as an argument an empty {@link AccessibilityEvent} and does not
6544     * perform a check whether accessibility is enabled.
6545     * <p>
6546     * If an {@link AccessibilityDelegate} has been specified via calling
6547     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6548     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6549     * is responsible for handling this call.
6550     * </p>
6551     *
6552     * @param event The event to send.
6553     *
6554     * @see #sendAccessibilityEvent(int)
6555     */
6556    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6557        if (mAccessibilityDelegate != null) {
6558            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6559        } else {
6560            sendAccessibilityEventUncheckedInternal(event);
6561        }
6562    }
6563
6564    /**
6565     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6566     *
6567     * Note: Called from the default {@link AccessibilityDelegate}.
6568     *
6569     * @hide
6570     */
6571    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6572        if (!isShown()) {
6573            return;
6574        }
6575        onInitializeAccessibilityEvent(event);
6576        // Only a subset of accessibility events populates text content.
6577        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6578            dispatchPopulateAccessibilityEvent(event);
6579        }
6580        // In the beginning we called #isShown(), so we know that getParent() is not null.
6581        getParent().requestSendAccessibilityEvent(this, event);
6582    }
6583
6584    /**
6585     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6586     * to its children for adding their text content to the event. Note that the
6587     * event text is populated in a separate dispatch path since we add to the
6588     * event not only the text of the source but also the text of all its descendants.
6589     * A typical implementation will call
6590     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6591     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6592     * on each child. Override this method if custom population of the event text
6593     * content is required.
6594     * <p>
6595     * If an {@link AccessibilityDelegate} has been specified via calling
6596     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6597     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6598     * is responsible for handling this call.
6599     * </p>
6600     * <p>
6601     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6602     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6603     * </p>
6604     *
6605     * @param event The event.
6606     *
6607     * @return True if the event population was completed.
6608     */
6609    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6610        if (mAccessibilityDelegate != null) {
6611            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6612        } else {
6613            return dispatchPopulateAccessibilityEventInternal(event);
6614        }
6615    }
6616
6617    /**
6618     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6619     *
6620     * Note: Called from the default {@link AccessibilityDelegate}.
6621     *
6622     * @hide
6623     */
6624    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6625        onPopulateAccessibilityEvent(event);
6626        return false;
6627    }
6628
6629    /**
6630     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6631     * giving a chance to this View to populate the accessibility event with its
6632     * text content. While this method is free to modify event
6633     * attributes other than text content, doing so should normally be performed in
6634     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6635     * <p>
6636     * Example: Adding formatted date string to an accessibility event in addition
6637     *          to the text added by the super implementation:
6638     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6639     *     super.onPopulateAccessibilityEvent(event);
6640     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6641     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6642     *         mCurrentDate.getTimeInMillis(), flags);
6643     *     event.getText().add(selectedDateUtterance);
6644     * }</pre>
6645     * <p>
6646     * If an {@link AccessibilityDelegate} has been specified via calling
6647     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6648     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6649     * is responsible for handling this call.
6650     * </p>
6651     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6652     * information to the event, in case the default implementation has basic information to add.
6653     * </p>
6654     *
6655     * @param event The accessibility event which to populate.
6656     *
6657     * @see #sendAccessibilityEvent(int)
6658     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6659     */
6660    @CallSuper
6661    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6662        if (mAccessibilityDelegate != null) {
6663            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6664        } else {
6665            onPopulateAccessibilityEventInternal(event);
6666        }
6667    }
6668
6669    /**
6670     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6671     *
6672     * Note: Called from the default {@link AccessibilityDelegate}.
6673     *
6674     * @hide
6675     */
6676    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6677    }
6678
6679    /**
6680     * Initializes an {@link AccessibilityEvent} with information about
6681     * this View which is the event source. In other words, the source of
6682     * an accessibility event is the view whose state change triggered firing
6683     * the event.
6684     * <p>
6685     * Example: Setting the password property of an event in addition
6686     *          to properties set by the super implementation:
6687     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6688     *     super.onInitializeAccessibilityEvent(event);
6689     *     event.setPassword(true);
6690     * }</pre>
6691     * <p>
6692     * If an {@link AccessibilityDelegate} has been specified via calling
6693     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6694     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6695     * is responsible for handling this call.
6696     * </p>
6697     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6698     * information to the event, in case the default implementation has basic information to add.
6699     * </p>
6700     * @param event The event to initialize.
6701     *
6702     * @see #sendAccessibilityEvent(int)
6703     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6704     */
6705    @CallSuper
6706    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6707        if (mAccessibilityDelegate != null) {
6708            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6709        } else {
6710            onInitializeAccessibilityEventInternal(event);
6711        }
6712    }
6713
6714    /**
6715     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6716     *
6717     * Note: Called from the default {@link AccessibilityDelegate}.
6718     *
6719     * @hide
6720     */
6721    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6722        event.setSource(this);
6723        event.setClassName(getAccessibilityClassName());
6724        event.setPackageName(getContext().getPackageName());
6725        event.setEnabled(isEnabled());
6726        event.setContentDescription(mContentDescription);
6727
6728        switch (event.getEventType()) {
6729            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6730                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6731                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6732                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6733                event.setItemCount(focusablesTempList.size());
6734                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6735                if (mAttachInfo != null) {
6736                    focusablesTempList.clear();
6737                }
6738            } break;
6739            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6740                CharSequence text = getIterableTextForAccessibility();
6741                if (text != null && text.length() > 0) {
6742                    event.setFromIndex(getAccessibilitySelectionStart());
6743                    event.setToIndex(getAccessibilitySelectionEnd());
6744                    event.setItemCount(text.length());
6745                }
6746            } break;
6747        }
6748    }
6749
6750    /**
6751     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6752     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6753     * This method is responsible for obtaining an accessibility node info from a
6754     * pool of reusable instances and calling
6755     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6756     * initialize the former.
6757     * <p>
6758     * Note: The client is responsible for recycling the obtained instance by calling
6759     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6760     * </p>
6761     *
6762     * @return A populated {@link AccessibilityNodeInfo}.
6763     *
6764     * @see AccessibilityNodeInfo
6765     */
6766    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6767        if (mAccessibilityDelegate != null) {
6768            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6769        } else {
6770            return createAccessibilityNodeInfoInternal();
6771        }
6772    }
6773
6774    /**
6775     * @see #createAccessibilityNodeInfo()
6776     *
6777     * @hide
6778     */
6779    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6780        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6781        if (provider != null) {
6782            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6783        } else {
6784            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6785            onInitializeAccessibilityNodeInfo(info);
6786            return info;
6787        }
6788    }
6789
6790    /**
6791     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6792     * The base implementation sets:
6793     * <ul>
6794     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6795     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6796     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6797     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6798     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6799     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6800     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6801     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6802     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6803     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6804     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6805     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6806     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6807     * </ul>
6808     * <p>
6809     * Subclasses should override this method, call the super implementation,
6810     * and set additional attributes.
6811     * </p>
6812     * <p>
6813     * If an {@link AccessibilityDelegate} has been specified via calling
6814     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6815     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6816     * is responsible for handling this call.
6817     * </p>
6818     *
6819     * @param info The instance to initialize.
6820     */
6821    @CallSuper
6822    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6823        if (mAccessibilityDelegate != null) {
6824            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6825        } else {
6826            onInitializeAccessibilityNodeInfoInternal(info);
6827        }
6828    }
6829
6830    /**
6831     * Gets the location of this view in screen coordinates.
6832     *
6833     * @param outRect The output location
6834     * @hide
6835     */
6836    public void getBoundsOnScreen(Rect outRect) {
6837        getBoundsOnScreen(outRect, false);
6838    }
6839
6840    /**
6841     * Gets the location of this view in screen coordinates.
6842     *
6843     * @param outRect The output location
6844     * @param clipToParent Whether to clip child bounds to the parent ones.
6845     * @hide
6846     */
6847    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6848        if (mAttachInfo == null) {
6849            return;
6850        }
6851
6852        RectF position = mAttachInfo.mTmpTransformRect;
6853        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6854
6855        if (!hasIdentityMatrix()) {
6856            getMatrix().mapRect(position);
6857        }
6858
6859        position.offset(mLeft, mTop);
6860
6861        ViewParent parent = mParent;
6862        while (parent instanceof View) {
6863            View parentView = (View) parent;
6864
6865            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6866
6867            if (clipToParent) {
6868                position.left = Math.max(position.left, 0);
6869                position.top = Math.max(position.top, 0);
6870                position.right = Math.min(position.right, parentView.getWidth());
6871                position.bottom = Math.min(position.bottom, parentView.getHeight());
6872            }
6873
6874            if (!parentView.hasIdentityMatrix()) {
6875                parentView.getMatrix().mapRect(position);
6876            }
6877
6878            position.offset(parentView.mLeft, parentView.mTop);
6879
6880            parent = parentView.mParent;
6881        }
6882
6883        if (parent instanceof ViewRootImpl) {
6884            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6885            position.offset(0, -viewRootImpl.mCurScrollY);
6886        }
6887
6888        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6889
6890        outRect.set(Math.round(position.left), Math.round(position.top),
6891                Math.round(position.right), Math.round(position.bottom));
6892    }
6893
6894    /**
6895     * Return the class name of this object to be used for accessibility purposes.
6896     * Subclasses should only override this if they are implementing something that
6897     * should be seen as a completely new class of view when used by accessibility,
6898     * unrelated to the class it is deriving from.  This is used to fill in
6899     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6900     */
6901    public CharSequence getAccessibilityClassName() {
6902        return View.class.getName();
6903    }
6904
6905    /**
6906     * Called when assist structure is being retrieved from a view as part of
6907     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6908     * @param structure Fill in with structured view data.  The default implementation
6909     * fills in all data that can be inferred from the view itself.
6910     */
6911    public void onProvideStructure(ViewStructure structure) {
6912        onProvideStructureForAssistOrAutoFill(structure, 0);
6913    }
6914
6915    /**
6916     * Called when assist structure is being retrieved from a view as part of an auto-fill request.
6917     *
6918     * <p>The structure must be filled according to the request type, which is set in the
6919     * {@code flags} parameter - see the documentation on each flag for more details.
6920     *
6921     * @param structure Fill in with structured view data.  The default implementation
6922     * fills in all data that can be inferred from the view itself.
6923     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
6924     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
6925     */
6926    public void onProvideAutoFillStructure(ViewStructure structure, int flags) {
6927        onProvideStructureForAssistOrAutoFill(structure, flags);
6928    }
6929
6930    private void onProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
6931        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
6932        // this method should take a boolean with the type of request.
6933        boolean forAutoFill = (flags
6934                & (View.AUTO_FILL_FLAG_TYPE_FILL
6935                        | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0;
6936        final int id = mID;
6937        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6938                && (id&0x0000ffff) != 0) {
6939            String pkg, type, entry;
6940            try {
6941                final Resources res = getResources();
6942                entry = res.getResourceEntryName(id);
6943                type = res.getResourceTypeName(id);
6944                pkg = res.getResourcePackageName(id);
6945            } catch (Resources.NotFoundException e) {
6946                entry = type = pkg = null;
6947            }
6948            structure.setId(id, pkg, type, entry);
6949        } else {
6950            structure.setId(id, null, null, null);
6951        }
6952
6953        if (forAutoFill) {
6954            // The auto-fill id needs to be unique, but its value doesn't matter, so it's better to
6955            // reuse the accessibility id to save space.
6956            structure.setAutoFillId(getAccessibilityViewId());
6957
6958            structure.setAutoFillType(getAutoFillType());
6959        }
6960
6961        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6962        if (!hasIdentityMatrix()) {
6963            structure.setTransformation(getMatrix());
6964        }
6965        structure.setElevation(getZ());
6966        structure.setVisibility(getVisibility());
6967        structure.setEnabled(isEnabled());
6968        if (isClickable()) {
6969            structure.setClickable(true);
6970        }
6971        if (isFocusable()) {
6972            structure.setFocusable(true);
6973        }
6974        if (isFocused()) {
6975            structure.setFocused(true);
6976        }
6977        if (isAccessibilityFocused()) {
6978            structure.setAccessibilityFocused(true);
6979        }
6980        if (isSelected()) {
6981            structure.setSelected(true);
6982        }
6983        if (isActivated()) {
6984            structure.setActivated(true);
6985        }
6986        if (isLongClickable()) {
6987            structure.setLongClickable(true);
6988        }
6989        if (this instanceof Checkable) {
6990            structure.setCheckable(true);
6991            if (((Checkable)this).isChecked()) {
6992                structure.setChecked(true);
6993            }
6994        }
6995        if (isContextClickable()) {
6996            structure.setContextClickable(true);
6997        }
6998        structure.setClassName(getAccessibilityClassName().toString());
6999        structure.setContentDescription(getContentDescription());
7000    }
7001
7002    /**
7003     * Called when assist structure is being retrieved from a view as part of
7004     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
7005     * generate additional virtual structure under this view.  The defaullt implementation
7006     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
7007     * view's virtual accessibility nodes, if any.  You can override this for a more
7008     * optimal implementation providing this data.
7009     */
7010    public void onProvideVirtualStructure(ViewStructure structure) {
7011        onProvideVirtualStructureForAssistOrAutoFill(structure, 0);
7012    }
7013
7014    /**
7015     * Called when assist structure is being retrieved from a view as part of an auto-fill request
7016     * to generate additional virtual structure under this view.
7017     *
7018     * <p>The defaullt implementation uses {@link #getAccessibilityNodeProvider()} to try to
7019     * generate this from the view's virtual accessibility nodes, if any. You can override this
7020     * for a more optimal implementation providing this data.
7021     *
7022     * <p>The structure must be filled according to the request type, which is set in the
7023     * {@code flags} parameter - see the documentation on each flag for more details.
7024     *
7025     * @param structure Fill in with structured view data.
7026     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7027     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
7028     */
7029    public void onProvideAutoFillVirtualStructure(ViewStructure structure, int flags) {
7030        onProvideVirtualStructureForAssistOrAutoFill(structure, flags);
7031    }
7032
7033    private void onProvideVirtualStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
7034        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7035        // this method should take a boolean with the type of request.
7036        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7037        if (provider != null) {
7038            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7039            structure.setChildCount(1);
7040            ViewStructure root = structure.newChild(0);
7041            populateVirtualStructure(root, provider, info, flags);
7042            info.recycle();
7043        }
7044    }
7045
7046    /**
7047     * Gets the {@link VirtualViewDelegate} responsible for auto-filling the virtual children of
7048     * this view.
7049     *
7050     * <p>By default returns {@code null} but should be overridden when view provides a virtual
7051     * hierachy on {@link OnProvideAssistDataListener} that takes flags used by the AutoFill
7052     * Framework (such as {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7053     * {@link #AUTO_FILL_FLAG_TYPE_SAVE}).
7054     */
7055    @Nullable
7056    public VirtualViewDelegate getAutoFillVirtualViewDelegate(
7057            @SuppressWarnings("unused") VirtualViewDelegate.Callback callback) {
7058        return null;
7059    }
7060
7061    /**
7062     * Automatically fills the content of this view with the {@code value}.
7063     *
7064     * <p>By default does nothing, but views should override it (and {@link #getAutoFillType()} to
7065     * support the AutoFill Framework.
7066     *
7067     * <p>Typically, it is implemented by:
7068     *
7069     * <ol>
7070     * <li>Call the proper getter method on {@link AutoFillValue} to fetch the actual value.
7071     * <li>Pass the actual value to the equivalent setter in the view.
7072     * <ol>
7073     *
7074     * <p>For example, a text-field view would call:
7075     *
7076     * <pre class="prettyprint">
7077     * CharSequence text = value.getTextValue();
7078     * if (text != null) {
7079     *     setText(text);
7080     * }
7081     * </pre>
7082     */
7083    public void autoFill(@SuppressWarnings("unused") AutoFillValue value) {
7084    }
7085
7086    /**
7087     * Describes the auto-fill type that should be used on callas to
7088     * {@link #autoFill(AutoFillValue)} and
7089     * {@link VirtualViewDelegate#autoFill(int, AutoFillValue)}.
7090     *
7091     * <p>By default returns {@code null}, but views should override it (and
7092     * {@link #autoFill(AutoFillValue)} to support the AutoFill Framework.
7093     */
7094    @Nullable
7095    public AutoFillType getAutoFillType() {
7096        return null;
7097    }
7098
7099    private void populateVirtualStructure(ViewStructure structure,
7100            AccessibilityNodeProvider provider, AccessibilityNodeInfo info, int flags) {
7101        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7102        // this method should take a boolean with the type of request.
7103
7104        final boolean sanitized = (flags & View.AUTO_FILL_FLAG_TYPE_FILL) != 0;
7105
7106        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
7107                null, null, null);
7108        Rect rect = structure.getTempRect();
7109        info.getBoundsInParent(rect);
7110        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
7111        structure.setVisibility(VISIBLE);
7112        structure.setEnabled(info.isEnabled());
7113        if (info.isClickable()) {
7114            structure.setClickable(true);
7115        }
7116        if (info.isFocusable()) {
7117            structure.setFocusable(true);
7118        }
7119        if (info.isFocused()) {
7120            structure.setFocused(true);
7121        }
7122        if (info.isAccessibilityFocused()) {
7123            structure.setAccessibilityFocused(true);
7124        }
7125        if (info.isSelected()) {
7126            structure.setSelected(true);
7127        }
7128        if (info.isLongClickable()) {
7129            structure.setLongClickable(true);
7130        }
7131        if (info.isCheckable()) {
7132            structure.setCheckable(true);
7133            if (info.isChecked()) {
7134                structure.setChecked(true);
7135            }
7136        }
7137        if (info.isContextClickable()) {
7138            structure.setContextClickable(true);
7139        }
7140        CharSequence cname = info.getClassName();
7141        structure.setClassName(cname != null ? cname.toString() : null);
7142        structure.setContentDescription(info.getContentDescription());
7143        if (!sanitized && (info.getText() != null || info.getError() != null)) {
7144            // TODO(b/33197203) (b/33269702): when sanitized, try to use the Accessibility API to
7145            // just set sanitized values (like text coming from resource files), rather than not
7146            // setting it at all.
7147            structure.setText(info.getText(), info.getTextSelectionStart(),
7148                    info.getTextSelectionEnd());
7149        }
7150        final int NCHILDREN = info.getChildCount();
7151        if (NCHILDREN > 0) {
7152            structure.setChildCount(NCHILDREN);
7153            for (int i=0; i<NCHILDREN; i++) {
7154                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
7155                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
7156                ViewStructure child = structure.newChild(i);
7157                populateVirtualStructure(child, provider, cinfo, flags);
7158                cinfo.recycle();
7159            }
7160        }
7161    }
7162
7163    /**
7164     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
7165     * implementation calls {@link #onProvideStructure} and
7166     * {@link #onProvideVirtualStructure}.
7167     */
7168    public void dispatchProvideStructure(ViewStructure structure) {
7169        dispatchProvideStructureForAssistOrAutoFill(structure, 0);
7170    }
7171
7172    /**
7173     * Dispatch creation of {@link ViewStructure} down the hierarchy.
7174     *
7175     * <p>The structure must be filled according to the request type, which is set in the
7176     * {@code flags} parameter - see the documentation on each flag for more details.
7177     *
7178     * <p>The default implementation calls {@link #onProvideAutoFillStructure(ViewStructure, int)}
7179     * and {@link #onProvideAutoFillVirtualStructure(ViewStructure, int)}.
7180     *
7181     * @param structure Fill in with structured view data.
7182     * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and
7183     * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info).
7184     */
7185    public void dispatchProvideAutoFillStructure(ViewStructure structure, int flags) {
7186        dispatchProvideStructureForAssistOrAutoFill(structure, flags);
7187    }
7188
7189    private void dispatchProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) {
7190        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7191        // this method should take a boolean with the type of request.
7192        boolean forAutoFill = (flags
7193                & (View.AUTO_FILL_FLAG_TYPE_FILL
7194                        | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0;
7195
7196        boolean blocked = forAutoFill ? isAutoFillBlocked() : isAssistBlocked();
7197        if (!blocked) {
7198            if (forAutoFill) {
7199                onProvideAutoFillStructure(structure, flags);
7200                onProvideAutoFillVirtualStructure(structure, flags);
7201            } else {
7202                onProvideStructure(structure);
7203                onProvideVirtualStructure(structure);
7204            }
7205        } else {
7206            structure.setClassName(getAccessibilityClassName().toString());
7207            structure.setAssistBlocked(true);
7208        }
7209    }
7210
7211    /**
7212     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
7213     *
7214     * Note: Called from the default {@link AccessibilityDelegate}.
7215     *
7216     * @hide
7217     */
7218    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
7219        if (mAttachInfo == null) {
7220            return;
7221        }
7222
7223        Rect bounds = mAttachInfo.mTmpInvalRect;
7224
7225        getDrawingRect(bounds);
7226        info.setBoundsInParent(bounds);
7227
7228        getBoundsOnScreen(bounds, true);
7229        info.setBoundsInScreen(bounds);
7230
7231        ViewParent parent = getParentForAccessibility();
7232        if (parent instanceof View) {
7233            info.setParent((View) parent);
7234        }
7235
7236        if (mID != View.NO_ID) {
7237            View rootView = getRootView();
7238            if (rootView == null) {
7239                rootView = this;
7240            }
7241
7242            View label = rootView.findLabelForView(this, mID);
7243            if (label != null) {
7244                info.setLabeledBy(label);
7245            }
7246
7247            if ((mAttachInfo.mAccessibilityFetchFlags
7248                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
7249                    && Resources.resourceHasPackage(mID)) {
7250                try {
7251                    String viewId = getResources().getResourceName(mID);
7252                    info.setViewIdResourceName(viewId);
7253                } catch (Resources.NotFoundException nfe) {
7254                    /* ignore */
7255                }
7256            }
7257        }
7258
7259        if (mLabelForId != View.NO_ID) {
7260            View rootView = getRootView();
7261            if (rootView == null) {
7262                rootView = this;
7263            }
7264            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
7265            if (labeled != null) {
7266                info.setLabelFor(labeled);
7267            }
7268        }
7269
7270        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
7271            View rootView = getRootView();
7272            if (rootView == null) {
7273                rootView = this;
7274            }
7275            View next = rootView.findViewInsideOutShouldExist(this,
7276                    mAccessibilityTraversalBeforeId);
7277            if (next != null && next.includeForAccessibility()) {
7278                info.setTraversalBefore(next);
7279            }
7280        }
7281
7282        if (mAccessibilityTraversalAfterId != View.NO_ID) {
7283            View rootView = getRootView();
7284            if (rootView == null) {
7285                rootView = this;
7286            }
7287            View next = rootView.findViewInsideOutShouldExist(this,
7288                    mAccessibilityTraversalAfterId);
7289            if (next != null && next.includeForAccessibility()) {
7290                info.setTraversalAfter(next);
7291            }
7292        }
7293
7294        info.setVisibleToUser(isVisibleToUser());
7295
7296        info.setImportantForAccessibility(isImportantForAccessibility());
7297        info.setPackageName(mContext.getPackageName());
7298        info.setClassName(getAccessibilityClassName());
7299        info.setContentDescription(getContentDescription());
7300
7301        info.setEnabled(isEnabled());
7302        info.setClickable(isClickable());
7303        info.setFocusable(isFocusable());
7304        info.setFocused(isFocused());
7305        info.setAccessibilityFocused(isAccessibilityFocused());
7306        info.setSelected(isSelected());
7307        info.setLongClickable(isLongClickable());
7308        info.setContextClickable(isContextClickable());
7309        info.setLiveRegion(getAccessibilityLiveRegion());
7310
7311        // TODO: These make sense only if we are in an AdapterView but all
7312        // views can be selected. Maybe from accessibility perspective
7313        // we should report as selectable view in an AdapterView.
7314        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
7315        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
7316
7317        if (isFocusable()) {
7318            if (isFocused()) {
7319                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
7320            } else {
7321                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
7322            }
7323        }
7324
7325        if (!isAccessibilityFocused()) {
7326            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
7327        } else {
7328            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
7329        }
7330
7331        if (isClickable() && isEnabled()) {
7332            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
7333        }
7334
7335        if (isLongClickable() && isEnabled()) {
7336            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
7337        }
7338
7339        if (isContextClickable() && isEnabled()) {
7340            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
7341        }
7342
7343        CharSequence text = getIterableTextForAccessibility();
7344        if (text != null && text.length() > 0) {
7345            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
7346
7347            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
7348            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
7349            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
7350            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
7351                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
7352                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
7353        }
7354
7355        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
7356        populateAccessibilityNodeInfoDrawingOrderInParent(info);
7357    }
7358
7359    /**
7360     * Determine the order in which this view will be drawn relative to its siblings for a11y
7361     *
7362     * @param info The info whose drawing order should be populated
7363     */
7364    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7365        /*
7366         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7367         * drawing order may not be well-defined, and some Views with custom drawing order may
7368         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7369         */
7370        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7371            info.setDrawingOrder(0);
7372            return;
7373        }
7374        int drawingOrderInParent = 1;
7375        // Iterate up the hierarchy if parents are not important for a11y
7376        View viewAtDrawingLevel = this;
7377        final ViewParent parent = getParentForAccessibility();
7378        while (viewAtDrawingLevel != parent) {
7379            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7380            if (!(currentParent instanceof ViewGroup)) {
7381                // Should only happen for the Decor
7382                drawingOrderInParent = 0;
7383                break;
7384            } else {
7385                final ViewGroup parentGroup = (ViewGroup) currentParent;
7386                final int childCount = parentGroup.getChildCount();
7387                if (childCount > 1) {
7388                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7389                    if (preorderedList != null) {
7390                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7391                        for (int i = 0; i < childDrawIndex; i++) {
7392                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7393                        }
7394                    } else {
7395                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7396                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7397                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7398                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7399                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7400                        if (childDrawIndex != 0) {
7401                            for (int i = 0; i < numChildrenToIterate; i++) {
7402                                final int otherDrawIndex = (customOrder ?
7403                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7404                                if (otherDrawIndex < childDrawIndex) {
7405                                    drawingOrderInParent +=
7406                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7407                                }
7408                            }
7409                        }
7410                    }
7411                }
7412            }
7413            viewAtDrawingLevel = (View) currentParent;
7414        }
7415        info.setDrawingOrder(drawingOrderInParent);
7416    }
7417
7418    private static int numViewsForAccessibility(View view) {
7419        if (view != null) {
7420            if (view.includeForAccessibility()) {
7421                return 1;
7422            } else if (view instanceof ViewGroup) {
7423                return ((ViewGroup) view).getNumChildrenForAccessibility();
7424            }
7425        }
7426        return 0;
7427    }
7428
7429    private View findLabelForView(View view, int labeledId) {
7430        if (mMatchLabelForPredicate == null) {
7431            mMatchLabelForPredicate = new MatchLabelForPredicate();
7432        }
7433        mMatchLabelForPredicate.mLabeledId = labeledId;
7434        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7435    }
7436
7437    /**
7438     * Computes whether this view is visible to the user. Such a view is
7439     * attached, visible, all its predecessors are visible, it is not clipped
7440     * entirely by its predecessors, and has an alpha greater than zero.
7441     *
7442     * @return Whether the view is visible on the screen.
7443     *
7444     * @hide
7445     */
7446    protected boolean isVisibleToUser() {
7447        return isVisibleToUser(null);
7448    }
7449
7450    /**
7451     * Computes whether the given portion of this view is visible to the user.
7452     * Such a view is attached, visible, all its predecessors are visible,
7453     * has an alpha greater than zero, and the specified portion is not
7454     * clipped entirely by its predecessors.
7455     *
7456     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7457     *                    <code>null</code>, and the entire view will be tested in this case.
7458     *                    When <code>true</code> is returned by the function, the actual visible
7459     *                    region will be stored in this parameter; that is, if boundInView is fully
7460     *                    contained within the view, no modification will be made, otherwise regions
7461     *                    outside of the visible area of the view will be clipped.
7462     *
7463     * @return Whether the specified portion of the view is visible on the screen.
7464     *
7465     * @hide
7466     */
7467    protected boolean isVisibleToUser(Rect boundInView) {
7468        if (mAttachInfo != null) {
7469            // Attached to invisible window means this view is not visible.
7470            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7471                return false;
7472            }
7473            // An invisible predecessor or one with alpha zero means
7474            // that this view is not visible to the user.
7475            Object current = this;
7476            while (current instanceof View) {
7477                View view = (View) current;
7478                // We have attach info so this view is attached and there is no
7479                // need to check whether we reach to ViewRootImpl on the way up.
7480                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7481                        view.getVisibility() != VISIBLE) {
7482                    return false;
7483                }
7484                current = view.mParent;
7485            }
7486            // Check if the view is entirely covered by its predecessors.
7487            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7488            Point offset = mAttachInfo.mPoint;
7489            if (!getGlobalVisibleRect(visibleRect, offset)) {
7490                return false;
7491            }
7492            // Check if the visible portion intersects the rectangle of interest.
7493            if (boundInView != null) {
7494                visibleRect.offset(-offset.x, -offset.y);
7495                return boundInView.intersect(visibleRect);
7496            }
7497            return true;
7498        }
7499        return false;
7500    }
7501
7502    /**
7503     * Returns the delegate for implementing accessibility support via
7504     * composition. For more details see {@link AccessibilityDelegate}.
7505     *
7506     * @return The delegate, or null if none set.
7507     *
7508     * @hide
7509     */
7510    public AccessibilityDelegate getAccessibilityDelegate() {
7511        return mAccessibilityDelegate;
7512    }
7513
7514    /**
7515     * Sets a delegate for implementing accessibility support via composition
7516     * (as opposed to inheritance). For more details, see
7517     * {@link AccessibilityDelegate}.
7518     * <p>
7519     * <strong>Note:</strong> On platform versions prior to
7520     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7521     * views in the {@code android.widget.*} package are called <i>before</i>
7522     * host methods. This prevents certain properties such as class name from
7523     * being modified by overriding
7524     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7525     * as any changes will be overwritten by the host class.
7526     * <p>
7527     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7528     * methods are called <i>after</i> host methods, which all properties to be
7529     * modified without being overwritten by the host class.
7530     *
7531     * @param delegate the object to which accessibility method calls should be
7532     *                 delegated
7533     * @see AccessibilityDelegate
7534     */
7535    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7536        mAccessibilityDelegate = delegate;
7537    }
7538
7539    /**
7540     * Gets the provider for managing a virtual view hierarchy rooted at this View
7541     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7542     * that explore the window content.
7543     * <p>
7544     * If this method returns an instance, this instance is responsible for managing
7545     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7546     * View including the one representing the View itself. Similarly the returned
7547     * instance is responsible for performing accessibility actions on any virtual
7548     * view or the root view itself.
7549     * </p>
7550     * <p>
7551     * If an {@link AccessibilityDelegate} has been specified via calling
7552     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7553     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7554     * is responsible for handling this call.
7555     * </p>
7556     *
7557     * @return The provider.
7558     *
7559     * @see AccessibilityNodeProvider
7560     */
7561    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7562        if (mAccessibilityDelegate != null) {
7563            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7564        } else {
7565            return null;
7566        }
7567    }
7568
7569    /**
7570     * Gets the unique identifier of this view on the screen for accessibility purposes.
7571     *
7572     * @return The view accessibility id.
7573     *
7574     * @hide
7575     */
7576    public int getAccessibilityViewId() {
7577        if (mAccessibilityViewId == NO_ID) {
7578            mAccessibilityViewId = sNextAccessibilityViewId++;
7579        }
7580        return mAccessibilityViewId;
7581    }
7582
7583    /**
7584     * Gets the unique identifier of the window in which this View reseides.
7585     *
7586     * @return The window accessibility id.
7587     *
7588     * @hide
7589     */
7590    public int getAccessibilityWindowId() {
7591        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7592                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7593    }
7594
7595    /**
7596     * Returns the {@link View}'s content description.
7597     * <p>
7598     * <strong>Note:</strong> Do not override this method, as it will have no
7599     * effect on the content description presented to accessibility services.
7600     * You must call {@link #setContentDescription(CharSequence)} to modify the
7601     * content description.
7602     *
7603     * @return the content description
7604     * @see #setContentDescription(CharSequence)
7605     * @attr ref android.R.styleable#View_contentDescription
7606     */
7607    @ViewDebug.ExportedProperty(category = "accessibility")
7608    public CharSequence getContentDescription() {
7609        return mContentDescription;
7610    }
7611
7612    /**
7613     * Sets the {@link View}'s content description.
7614     * <p>
7615     * A content description briefly describes the view and is primarily used
7616     * for accessibility support to determine how a view should be presented to
7617     * the user. In the case of a view with no textual representation, such as
7618     * {@link android.widget.ImageButton}, a useful content description
7619     * explains what the view does. For example, an image button with a phone
7620     * icon that is used to place a call may use "Call" as its content
7621     * description. An image of a floppy disk that is used to save a file may
7622     * use "Save".
7623     *
7624     * @param contentDescription The content description.
7625     * @see #getContentDescription()
7626     * @attr ref android.R.styleable#View_contentDescription
7627     */
7628    @RemotableViewMethod
7629    public void setContentDescription(CharSequence contentDescription) {
7630        if (mContentDescription == null) {
7631            if (contentDescription == null) {
7632                return;
7633            }
7634        } else if (mContentDescription.equals(contentDescription)) {
7635            return;
7636        }
7637        mContentDescription = contentDescription;
7638        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7639        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7640            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7641            notifySubtreeAccessibilityStateChangedIfNeeded();
7642        } else {
7643            notifyViewAccessibilityStateChangedIfNeeded(
7644                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7645        }
7646    }
7647
7648    /**
7649     * Sets the id of a view before which this one is visited in accessibility traversal.
7650     * A screen-reader must visit the content of this view before the content of the one
7651     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7652     * will traverse the entire content of B before traversing the entire content of A,
7653     * regardles of what traversal strategy it is using.
7654     * <p>
7655     * Views that do not have specified before/after relationships are traversed in order
7656     * determined by the screen-reader.
7657     * </p>
7658     * <p>
7659     * Setting that this view is before a view that is not important for accessibility
7660     * or if this view is not important for accessibility will have no effect as the
7661     * screen-reader is not aware of unimportant views.
7662     * </p>
7663     *
7664     * @param beforeId The id of a view this one precedes in accessibility traversal.
7665     *
7666     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7667     *
7668     * @see #setImportantForAccessibility(int)
7669     */
7670    @RemotableViewMethod
7671    public void setAccessibilityTraversalBefore(int beforeId) {
7672        if (mAccessibilityTraversalBeforeId == beforeId) {
7673            return;
7674        }
7675        mAccessibilityTraversalBeforeId = beforeId;
7676        notifyViewAccessibilityStateChangedIfNeeded(
7677                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7678    }
7679
7680    /**
7681     * Gets the id of a view before which this one is visited in accessibility traversal.
7682     *
7683     * @return The id of a view this one precedes in accessibility traversal if
7684     *         specified, otherwise {@link #NO_ID}.
7685     *
7686     * @see #setAccessibilityTraversalBefore(int)
7687     */
7688    public int getAccessibilityTraversalBefore() {
7689        return mAccessibilityTraversalBeforeId;
7690    }
7691
7692    /**
7693     * Sets the id of a view after which this one is visited in accessibility traversal.
7694     * A screen-reader must visit the content of the other view before the content of this
7695     * one. For example, if view B is set to be after view A, then a screen-reader
7696     * will traverse the entire content of A before traversing the entire content of B,
7697     * regardles of what traversal strategy it is using.
7698     * <p>
7699     * Views that do not have specified before/after relationships are traversed in order
7700     * determined by the screen-reader.
7701     * </p>
7702     * <p>
7703     * Setting that this view is after a view that is not important for accessibility
7704     * or if this view is not important for accessibility will have no effect as the
7705     * screen-reader is not aware of unimportant views.
7706     * </p>
7707     *
7708     * @param afterId The id of a view this one succedees in accessibility traversal.
7709     *
7710     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7711     *
7712     * @see #setImportantForAccessibility(int)
7713     */
7714    @RemotableViewMethod
7715    public void setAccessibilityTraversalAfter(int afterId) {
7716        if (mAccessibilityTraversalAfterId == afterId) {
7717            return;
7718        }
7719        mAccessibilityTraversalAfterId = afterId;
7720        notifyViewAccessibilityStateChangedIfNeeded(
7721                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7722    }
7723
7724    /**
7725     * Gets the id of a view after which this one is visited in accessibility traversal.
7726     *
7727     * @return The id of a view this one succeedes in accessibility traversal if
7728     *         specified, otherwise {@link #NO_ID}.
7729     *
7730     * @see #setAccessibilityTraversalAfter(int)
7731     */
7732    public int getAccessibilityTraversalAfter() {
7733        return mAccessibilityTraversalAfterId;
7734    }
7735
7736    /**
7737     * Gets the id of a view for which this view serves as a label for
7738     * accessibility purposes.
7739     *
7740     * @return The labeled view id.
7741     */
7742    @ViewDebug.ExportedProperty(category = "accessibility")
7743    public int getLabelFor() {
7744        return mLabelForId;
7745    }
7746
7747    /**
7748     * Sets the id of a view for which this view serves as a label for
7749     * accessibility purposes.
7750     *
7751     * @param id The labeled view id.
7752     */
7753    @RemotableViewMethod
7754    public void setLabelFor(@IdRes int id) {
7755        if (mLabelForId == id) {
7756            return;
7757        }
7758        mLabelForId = id;
7759        if (mLabelForId != View.NO_ID
7760                && mID == View.NO_ID) {
7761            mID = generateViewId();
7762        }
7763        notifyViewAccessibilityStateChangedIfNeeded(
7764                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7765    }
7766
7767    /**
7768     * Invoked whenever this view loses focus, either by losing window focus or by losing
7769     * focus within its window. This method can be used to clear any state tied to the
7770     * focus. For instance, if a button is held pressed with the trackball and the window
7771     * loses focus, this method can be used to cancel the press.
7772     *
7773     * Subclasses of View overriding this method should always call super.onFocusLost().
7774     *
7775     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7776     * @see #onWindowFocusChanged(boolean)
7777     *
7778     * @hide pending API council approval
7779     */
7780    @CallSuper
7781    protected void onFocusLost() {
7782        resetPressedState();
7783    }
7784
7785    private void resetPressedState() {
7786        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7787            return;
7788        }
7789
7790        if (isPressed()) {
7791            setPressed(false);
7792
7793            if (!mHasPerformedLongPress) {
7794                removeLongPressCallback();
7795            }
7796        }
7797    }
7798
7799    /**
7800     * Returns true if this view has focus
7801     *
7802     * @return True if this view has focus, false otherwise.
7803     */
7804    @ViewDebug.ExportedProperty(category = "focus")
7805    public boolean isFocused() {
7806        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7807    }
7808
7809    /**
7810     * Find the view in the hierarchy rooted at this view that currently has
7811     * focus.
7812     *
7813     * @return The view that currently has focus, or null if no focused view can
7814     *         be found.
7815     */
7816    public View findFocus() {
7817        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7818    }
7819
7820    /**
7821     * Indicates whether this view is one of the set of scrollable containers in
7822     * its window.
7823     *
7824     * @return whether this view is one of the set of scrollable containers in
7825     * its window
7826     *
7827     * @attr ref android.R.styleable#View_isScrollContainer
7828     */
7829    public boolean isScrollContainer() {
7830        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7831    }
7832
7833    /**
7834     * Change whether this view is one of the set of scrollable containers in
7835     * its window.  This will be used to determine whether the window can
7836     * resize or must pan when a soft input area is open -- scrollable
7837     * containers allow the window to use resize mode since the container
7838     * will appropriately shrink.
7839     *
7840     * @attr ref android.R.styleable#View_isScrollContainer
7841     */
7842    public void setScrollContainer(boolean isScrollContainer) {
7843        if (isScrollContainer) {
7844            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7845                mAttachInfo.mScrollContainers.add(this);
7846                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7847            }
7848            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7849        } else {
7850            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7851                mAttachInfo.mScrollContainers.remove(this);
7852            }
7853            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7854        }
7855    }
7856
7857    /**
7858     * Returns the quality of the drawing cache.
7859     *
7860     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7861     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7862     *
7863     * @see #setDrawingCacheQuality(int)
7864     * @see #setDrawingCacheEnabled(boolean)
7865     * @see #isDrawingCacheEnabled()
7866     *
7867     * @attr ref android.R.styleable#View_drawingCacheQuality
7868     */
7869    @DrawingCacheQuality
7870    public int getDrawingCacheQuality() {
7871        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7872    }
7873
7874    /**
7875     * Set the drawing cache quality of this view. This value is used only when the
7876     * drawing cache is enabled
7877     *
7878     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7879     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7880     *
7881     * @see #getDrawingCacheQuality()
7882     * @see #setDrawingCacheEnabled(boolean)
7883     * @see #isDrawingCacheEnabled()
7884     *
7885     * @attr ref android.R.styleable#View_drawingCacheQuality
7886     */
7887    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7888        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7889    }
7890
7891    /**
7892     * Returns whether the screen should remain on, corresponding to the current
7893     * value of {@link #KEEP_SCREEN_ON}.
7894     *
7895     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7896     *
7897     * @see #setKeepScreenOn(boolean)
7898     *
7899     * @attr ref android.R.styleable#View_keepScreenOn
7900     */
7901    public boolean getKeepScreenOn() {
7902        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7903    }
7904
7905    /**
7906     * Controls whether the screen should remain on, modifying the
7907     * value of {@link #KEEP_SCREEN_ON}.
7908     *
7909     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7910     *
7911     * @see #getKeepScreenOn()
7912     *
7913     * @attr ref android.R.styleable#View_keepScreenOn
7914     */
7915    public void setKeepScreenOn(boolean keepScreenOn) {
7916        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7917    }
7918
7919    /**
7920     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7921     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7922     *
7923     * @attr ref android.R.styleable#View_nextFocusLeft
7924     */
7925    public int getNextFocusLeftId() {
7926        return mNextFocusLeftId;
7927    }
7928
7929    /**
7930     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7931     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7932     * decide automatically.
7933     *
7934     * @attr ref android.R.styleable#View_nextFocusLeft
7935     */
7936    public void setNextFocusLeftId(int nextFocusLeftId) {
7937        mNextFocusLeftId = nextFocusLeftId;
7938    }
7939
7940    /**
7941     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7942     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7943     *
7944     * @attr ref android.R.styleable#View_nextFocusRight
7945     */
7946    public int getNextFocusRightId() {
7947        return mNextFocusRightId;
7948    }
7949
7950    /**
7951     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7952     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7953     * decide automatically.
7954     *
7955     * @attr ref android.R.styleable#View_nextFocusRight
7956     */
7957    public void setNextFocusRightId(int nextFocusRightId) {
7958        mNextFocusRightId = nextFocusRightId;
7959    }
7960
7961    /**
7962     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7963     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7964     *
7965     * @attr ref android.R.styleable#View_nextFocusUp
7966     */
7967    public int getNextFocusUpId() {
7968        return mNextFocusUpId;
7969    }
7970
7971    /**
7972     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7973     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7974     * decide automatically.
7975     *
7976     * @attr ref android.R.styleable#View_nextFocusUp
7977     */
7978    public void setNextFocusUpId(int nextFocusUpId) {
7979        mNextFocusUpId = nextFocusUpId;
7980    }
7981
7982    /**
7983     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7984     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7985     *
7986     * @attr ref android.R.styleable#View_nextFocusDown
7987     */
7988    public int getNextFocusDownId() {
7989        return mNextFocusDownId;
7990    }
7991
7992    /**
7993     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7994     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7995     * decide automatically.
7996     *
7997     * @attr ref android.R.styleable#View_nextFocusDown
7998     */
7999    public void setNextFocusDownId(int nextFocusDownId) {
8000        mNextFocusDownId = nextFocusDownId;
8001    }
8002
8003    /**
8004     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8005     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8006     *
8007     * @attr ref android.R.styleable#View_nextFocusForward
8008     */
8009    public int getNextFocusForwardId() {
8010        return mNextFocusForwardId;
8011    }
8012
8013    /**
8014     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8015     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
8016     * decide automatically.
8017     *
8018     * @attr ref android.R.styleable#View_nextFocusForward
8019     */
8020    public void setNextFocusForwardId(int nextFocusForwardId) {
8021        mNextFocusForwardId = nextFocusForwardId;
8022    }
8023
8024    /**
8025     * Gets the id of the root of the next keyboard navigation cluster.
8026     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
8027     * decide automatically.
8028     *
8029     * @attr ref android.R.styleable#View_nextClusterForward
8030     */
8031    public int getNextClusterForwardId() {
8032        return mNextClusterForwardId;
8033    }
8034
8035    /**
8036     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
8037     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
8038     * decide automatically.
8039     *
8040     * @attr ref android.R.styleable#View_nextClusterForward
8041     */
8042    public void setNextClusterForwardId(int nextClusterForwardId) {
8043        mNextClusterForwardId = nextClusterForwardId;
8044    }
8045
8046    /**
8047     * Gets the id of the root of the next keyboard navigation section.
8048     * @return The next keyboard navigation section ID, or {@link #NO_ID} if the framework should
8049     * decide automatically.
8050     *
8051     * @attr ref android.R.styleable#View_nextSectionForward
8052     */
8053    public int getNextSectionForwardId() {
8054        return mNextSectionForwardId;
8055    }
8056
8057    /**
8058     * Sets the id of the view to use as the root of the next keyboard navigation section.
8059     * @param nextSectionForwardId The next section ID, or {@link #NO_ID} if the framework should
8060     * decide automatically.
8061     *
8062     * @attr ref android.R.styleable#View_nextSectionForward
8063     */
8064    public void setNextSectionForwardId(int nextSectionForwardId) {
8065        mNextSectionForwardId = nextSectionForwardId;
8066    }
8067
8068    /**
8069     * Returns the visibility of this view and all of its ancestors
8070     *
8071     * @return True if this view and all of its ancestors are {@link #VISIBLE}
8072     */
8073    public boolean isShown() {
8074        View current = this;
8075        //noinspection ConstantConditions
8076        do {
8077            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8078                return false;
8079            }
8080            ViewParent parent = current.mParent;
8081            if (parent == null) {
8082                return false; // We are not attached to the view root
8083            }
8084            if (!(parent instanceof View)) {
8085                return true;
8086            }
8087            current = (View) parent;
8088        } while (current != null);
8089
8090        return false;
8091    }
8092
8093    /**
8094     * Called by the view hierarchy when the content insets for a window have
8095     * changed, to allow it to adjust its content to fit within those windows.
8096     * The content insets tell you the space that the status bar, input method,
8097     * and other system windows infringe on the application's window.
8098     *
8099     * <p>You do not normally need to deal with this function, since the default
8100     * window decoration given to applications takes care of applying it to the
8101     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
8102     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
8103     * and your content can be placed under those system elements.  You can then
8104     * use this method within your view hierarchy if you have parts of your UI
8105     * which you would like to ensure are not being covered.
8106     *
8107     * <p>The default implementation of this method simply applies the content
8108     * insets to the view's padding, consuming that content (modifying the
8109     * insets to be 0), and returning true.  This behavior is off by default, but can
8110     * be enabled through {@link #setFitsSystemWindows(boolean)}.
8111     *
8112     * <p>This function's traversal down the hierarchy is depth-first.  The same content
8113     * insets object is propagated down the hierarchy, so any changes made to it will
8114     * be seen by all following views (including potentially ones above in
8115     * the hierarchy since this is a depth-first traversal).  The first view
8116     * that returns true will abort the entire traversal.
8117     *
8118     * <p>The default implementation works well for a situation where it is
8119     * used with a container that covers the entire window, allowing it to
8120     * apply the appropriate insets to its content on all edges.  If you need
8121     * a more complicated layout (such as two different views fitting system
8122     * windows, one on the top of the window, and one on the bottom),
8123     * you can override the method and handle the insets however you would like.
8124     * Note that the insets provided by the framework are always relative to the
8125     * far edges of the window, not accounting for the location of the called view
8126     * within that window.  (In fact when this method is called you do not yet know
8127     * where the layout will place the view, as it is done before layout happens.)
8128     *
8129     * <p>Note: unlike many View methods, there is no dispatch phase to this
8130     * call.  If you are overriding it in a ViewGroup and want to allow the
8131     * call to continue to your children, you must be sure to call the super
8132     * implementation.
8133     *
8134     * <p>Here is a sample layout that makes use of fitting system windows
8135     * to have controls for a video view placed inside of the window decorations
8136     * that it hides and shows.  This can be used with code like the second
8137     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
8138     *
8139     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
8140     *
8141     * @param insets Current content insets of the window.  Prior to
8142     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
8143     * the insets or else you and Android will be unhappy.
8144     *
8145     * @return {@code true} if this view applied the insets and it should not
8146     * continue propagating further down the hierarchy, {@code false} otherwise.
8147     * @see #getFitsSystemWindows()
8148     * @see #setFitsSystemWindows(boolean)
8149     * @see #setSystemUiVisibility(int)
8150     *
8151     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
8152     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
8153     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
8154     * to implement handling their own insets.
8155     */
8156    @Deprecated
8157    protected boolean fitSystemWindows(Rect insets) {
8158        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
8159            if (insets == null) {
8160                // Null insets by definition have already been consumed.
8161                // This call cannot apply insets since there are none to apply,
8162                // so return false.
8163                return false;
8164            }
8165            // If we're not in the process of dispatching the newer apply insets call,
8166            // that means we're not in the compatibility path. Dispatch into the newer
8167            // apply insets path and take things from there.
8168            try {
8169                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
8170                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
8171            } finally {
8172                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
8173            }
8174        } else {
8175            // We're being called from the newer apply insets path.
8176            // Perform the standard fallback behavior.
8177            return fitSystemWindowsInt(insets);
8178        }
8179    }
8180
8181    private boolean fitSystemWindowsInt(Rect insets) {
8182        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
8183            mUserPaddingStart = UNDEFINED_PADDING;
8184            mUserPaddingEnd = UNDEFINED_PADDING;
8185            Rect localInsets = sThreadLocal.get();
8186            if (localInsets == null) {
8187                localInsets = new Rect();
8188                sThreadLocal.set(localInsets);
8189            }
8190            boolean res = computeFitSystemWindows(insets, localInsets);
8191            mUserPaddingLeftInitial = localInsets.left;
8192            mUserPaddingRightInitial = localInsets.right;
8193            internalSetPadding(localInsets.left, localInsets.top,
8194                    localInsets.right, localInsets.bottom);
8195            return res;
8196        }
8197        return false;
8198    }
8199
8200    /**
8201     * Called when the view should apply {@link WindowInsets} according to its internal policy.
8202     *
8203     * <p>This method should be overridden by views that wish to apply a policy different from or
8204     * in addition to the default behavior. Clients that wish to force a view subtree
8205     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
8206     *
8207     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
8208     * it will be called during dispatch instead of this method. The listener may optionally
8209     * call this method from its own implementation if it wishes to apply the view's default
8210     * insets policy in addition to its own.</p>
8211     *
8212     * <p>Implementations of this method should either return the insets parameter unchanged
8213     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
8214     * that this view applied itself. This allows new inset types added in future platform
8215     * versions to pass through existing implementations unchanged without being erroneously
8216     * consumed.</p>
8217     *
8218     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
8219     * property is set then the view will consume the system window insets and apply them
8220     * as padding for the view.</p>
8221     *
8222     * @param insets Insets to apply
8223     * @return The supplied insets with any applied insets consumed
8224     */
8225    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
8226        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
8227            // We weren't called from within a direct call to fitSystemWindows,
8228            // call into it as a fallback in case we're in a class that overrides it
8229            // and has logic to perform.
8230            if (fitSystemWindows(insets.getSystemWindowInsets())) {
8231                return insets.consumeSystemWindowInsets();
8232            }
8233        } else {
8234            // We were called from within a direct call to fitSystemWindows.
8235            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
8236                return insets.consumeSystemWindowInsets();
8237            }
8238        }
8239        return insets;
8240    }
8241
8242    /**
8243     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
8244     * window insets to this view. The listener's
8245     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
8246     * method will be called instead of the view's
8247     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
8248     *
8249     * @param listener Listener to set
8250     *
8251     * @see #onApplyWindowInsets(WindowInsets)
8252     */
8253    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
8254        getListenerInfo().mOnApplyWindowInsetsListener = listener;
8255    }
8256
8257    /**
8258     * Request to apply the given window insets to this view or another view in its subtree.
8259     *
8260     * <p>This method should be called by clients wishing to apply insets corresponding to areas
8261     * obscured by window decorations or overlays. This can include the status and navigation bars,
8262     * action bars, input methods and more. New inset categories may be added in the future.
8263     * The method returns the insets provided minus any that were applied by this view or its
8264     * children.</p>
8265     *
8266     * <p>Clients wishing to provide custom behavior should override the
8267     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
8268     * {@link OnApplyWindowInsetsListener} via the
8269     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
8270     * method.</p>
8271     *
8272     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
8273     * </p>
8274     *
8275     * @param insets Insets to apply
8276     * @return The provided insets minus the insets that were consumed
8277     */
8278    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
8279        try {
8280            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
8281            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
8282                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
8283            } else {
8284                return onApplyWindowInsets(insets);
8285            }
8286        } finally {
8287            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
8288        }
8289    }
8290
8291    /**
8292     * Compute the view's coordinate within the surface.
8293     *
8294     * <p>Computes the coordinates of this view in its surface. The argument
8295     * must be an array of two integers. After the method returns, the array
8296     * contains the x and y location in that order.</p>
8297     * @hide
8298     * @param location an array of two integers in which to hold the coordinates
8299     */
8300    public void getLocationInSurface(@Size(2) int[] location) {
8301        getLocationInWindow(location);
8302        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
8303            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
8304            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
8305        }
8306    }
8307
8308    /**
8309     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
8310     * only available if the view is attached.
8311     *
8312     * @return WindowInsets from the top of the view hierarchy or null if View is detached
8313     */
8314    public WindowInsets getRootWindowInsets() {
8315        if (mAttachInfo != null) {
8316            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
8317        }
8318        return null;
8319    }
8320
8321    /**
8322     * @hide Compute the insets that should be consumed by this view and the ones
8323     * that should propagate to those under it.
8324     */
8325    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
8326        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8327                || mAttachInfo == null
8328                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
8329                        && !mAttachInfo.mOverscanRequested)) {
8330            outLocalInsets.set(inoutInsets);
8331            inoutInsets.set(0, 0, 0, 0);
8332            return true;
8333        } else {
8334            // The application wants to take care of fitting system window for
8335            // the content...  however we still need to take care of any overscan here.
8336            final Rect overscan = mAttachInfo.mOverscanInsets;
8337            outLocalInsets.set(overscan);
8338            inoutInsets.left -= overscan.left;
8339            inoutInsets.top -= overscan.top;
8340            inoutInsets.right -= overscan.right;
8341            inoutInsets.bottom -= overscan.bottom;
8342            return false;
8343        }
8344    }
8345
8346    /**
8347     * Compute insets that should be consumed by this view and the ones that should propagate
8348     * to those under it.
8349     *
8350     * @param in Insets currently being processed by this View, likely received as a parameter
8351     *           to {@link #onApplyWindowInsets(WindowInsets)}.
8352     * @param outLocalInsets A Rect that will receive the insets that should be consumed
8353     *                       by this view
8354     * @return Insets that should be passed along to views under this one
8355     */
8356    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
8357        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8358                || mAttachInfo == null
8359                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
8360            outLocalInsets.set(in.getSystemWindowInsets());
8361            return in.consumeSystemWindowInsets();
8362        } else {
8363            outLocalInsets.set(0, 0, 0, 0);
8364            return in;
8365        }
8366    }
8367
8368    /**
8369     * Sets whether or not this view should account for system screen decorations
8370     * such as the status bar and inset its content; that is, controlling whether
8371     * the default implementation of {@link #fitSystemWindows(Rect)} will be
8372     * executed.  See that method for more details.
8373     *
8374     * <p>Note that if you are providing your own implementation of
8375     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
8376     * flag to true -- your implementation will be overriding the default
8377     * implementation that checks this flag.
8378     *
8379     * @param fitSystemWindows If true, then the default implementation of
8380     * {@link #fitSystemWindows(Rect)} will be executed.
8381     *
8382     * @attr ref android.R.styleable#View_fitsSystemWindows
8383     * @see #getFitsSystemWindows()
8384     * @see #fitSystemWindows(Rect)
8385     * @see #setSystemUiVisibility(int)
8386     */
8387    public void setFitsSystemWindows(boolean fitSystemWindows) {
8388        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
8389    }
8390
8391    /**
8392     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
8393     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
8394     * will be executed.
8395     *
8396     * @return {@code true} if the default implementation of
8397     * {@link #fitSystemWindows(Rect)} will be executed.
8398     *
8399     * @attr ref android.R.styleable#View_fitsSystemWindows
8400     * @see #setFitsSystemWindows(boolean)
8401     * @see #fitSystemWindows(Rect)
8402     * @see #setSystemUiVisibility(int)
8403     */
8404    @ViewDebug.ExportedProperty
8405    public boolean getFitsSystemWindows() {
8406        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8407    }
8408
8409    /** @hide */
8410    public boolean fitsSystemWindows() {
8411        return getFitsSystemWindows();
8412    }
8413
8414    /**
8415     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8416     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8417     */
8418    @Deprecated
8419    public void requestFitSystemWindows() {
8420        if (mParent != null) {
8421            mParent.requestFitSystemWindows();
8422        }
8423    }
8424
8425    /**
8426     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8427     */
8428    public void requestApplyInsets() {
8429        requestFitSystemWindows();
8430    }
8431
8432    /**
8433     * For use by PhoneWindow to make its own system window fitting optional.
8434     * @hide
8435     */
8436    public void makeOptionalFitsSystemWindows() {
8437        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8438    }
8439
8440    /**
8441     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8442     * treat them as such.
8443     * @hide
8444     */
8445    public void getOutsets(Rect outOutsetRect) {
8446        if (mAttachInfo != null) {
8447            outOutsetRect.set(mAttachInfo.mOutsets);
8448        } else {
8449            outOutsetRect.setEmpty();
8450        }
8451    }
8452
8453    /**
8454     * Returns the visibility status for this view.
8455     *
8456     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8457     * @attr ref android.R.styleable#View_visibility
8458     */
8459    @ViewDebug.ExportedProperty(mapping = {
8460        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
8461        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
8462        @ViewDebug.IntToString(from = GONE,      to = "GONE")
8463    })
8464    @Visibility
8465    public int getVisibility() {
8466        return mViewFlags & VISIBILITY_MASK;
8467    }
8468
8469    /**
8470     * Set the visibility state of this view.
8471     *
8472     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8473     * @attr ref android.R.styleable#View_visibility
8474     */
8475    @RemotableViewMethod
8476    public void setVisibility(@Visibility int visibility) {
8477        setFlags(visibility, VISIBILITY_MASK);
8478    }
8479
8480    /**
8481     * Returns the enabled status for this view. The interpretation of the
8482     * enabled state varies by subclass.
8483     *
8484     * @return True if this view is enabled, false otherwise.
8485     */
8486    @ViewDebug.ExportedProperty
8487    public boolean isEnabled() {
8488        return (mViewFlags & ENABLED_MASK) == ENABLED;
8489    }
8490
8491    /**
8492     * Set the enabled state of this view. The interpretation of the enabled
8493     * state varies by subclass.
8494     *
8495     * @param enabled True if this view is enabled, false otherwise.
8496     */
8497    @RemotableViewMethod
8498    public void setEnabled(boolean enabled) {
8499        if (enabled == isEnabled()) return;
8500
8501        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8502
8503        /*
8504         * The View most likely has to change its appearance, so refresh
8505         * the drawable state.
8506         */
8507        refreshDrawableState();
8508
8509        // Invalidate too, since the default behavior for views is to be
8510        // be drawn at 50% alpha rather than to change the drawable.
8511        invalidate(true);
8512
8513        if (!enabled) {
8514            cancelPendingInputEvents();
8515        }
8516    }
8517
8518    /**
8519     * Set whether this view can receive the focus.
8520     *
8521     * Setting this to false will also ensure that this view is not focusable
8522     * in touch mode.
8523     *
8524     * @param focusable If true, this view can receive the focus.
8525     *
8526     * @see #setFocusableInTouchMode(boolean)
8527     * @attr ref android.R.styleable#View_focusable
8528     */
8529    public void setFocusable(boolean focusable) {
8530        if (!focusable) {
8531            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8532        }
8533        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8534    }
8535
8536    /**
8537     * Set whether this view can receive focus while in touch mode.
8538     *
8539     * Setting this to true will also ensure that this view is focusable.
8540     *
8541     * @param focusableInTouchMode If true, this view can receive the focus while
8542     *   in touch mode.
8543     *
8544     * @see #setFocusable(boolean)
8545     * @attr ref android.R.styleable#View_focusableInTouchMode
8546     */
8547    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8548        // Focusable in touch mode should always be set before the focusable flag
8549        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8550        // which, in touch mode, will not successfully request focus on this view
8551        // because the focusable in touch mode flag is not set
8552        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8553        if (focusableInTouchMode) {
8554            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8555        }
8556    }
8557
8558    /**
8559     * Set whether this view should have sound effects enabled for events such as
8560     * clicking and touching.
8561     *
8562     * <p>You may wish to disable sound effects for a view if you already play sounds,
8563     * for instance, a dial key that plays dtmf tones.
8564     *
8565     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8566     * @see #isSoundEffectsEnabled()
8567     * @see #playSoundEffect(int)
8568     * @attr ref android.R.styleable#View_soundEffectsEnabled
8569     */
8570    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8571        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8572    }
8573
8574    /**
8575     * @return whether this view should have sound effects enabled for events such as
8576     *     clicking and touching.
8577     *
8578     * @see #setSoundEffectsEnabled(boolean)
8579     * @see #playSoundEffect(int)
8580     * @attr ref android.R.styleable#View_soundEffectsEnabled
8581     */
8582    @ViewDebug.ExportedProperty
8583    public boolean isSoundEffectsEnabled() {
8584        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8585    }
8586
8587    /**
8588     * Set whether this view should have haptic feedback for events such as
8589     * long presses.
8590     *
8591     * <p>You may wish to disable haptic feedback if your view already controls
8592     * its own haptic feedback.
8593     *
8594     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8595     * @see #isHapticFeedbackEnabled()
8596     * @see #performHapticFeedback(int)
8597     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8598     */
8599    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8600        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8601    }
8602
8603    /**
8604     * @return whether this view should have haptic feedback enabled for events
8605     * long presses.
8606     *
8607     * @see #setHapticFeedbackEnabled(boolean)
8608     * @see #performHapticFeedback(int)
8609     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8610     */
8611    @ViewDebug.ExportedProperty
8612    public boolean isHapticFeedbackEnabled() {
8613        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8614    }
8615
8616    /**
8617     * Returns the layout direction for this view.
8618     *
8619     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8620     *   {@link #LAYOUT_DIRECTION_RTL},
8621     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8622     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8623     *
8624     * @attr ref android.R.styleable#View_layoutDirection
8625     *
8626     * @hide
8627     */
8628    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8629        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8630        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8631        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8632        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8633    })
8634    @LayoutDir
8635    public int getRawLayoutDirection() {
8636        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8637    }
8638
8639    /**
8640     * Set the layout direction for this view. This will propagate a reset of layout direction
8641     * resolution to the view's children and resolve layout direction for this view.
8642     *
8643     * @param layoutDirection the layout direction to set. Should be one of:
8644     *
8645     * {@link #LAYOUT_DIRECTION_LTR},
8646     * {@link #LAYOUT_DIRECTION_RTL},
8647     * {@link #LAYOUT_DIRECTION_INHERIT},
8648     * {@link #LAYOUT_DIRECTION_LOCALE}.
8649     *
8650     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8651     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8652     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8653     *
8654     * @attr ref android.R.styleable#View_layoutDirection
8655     */
8656    @RemotableViewMethod
8657    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8658        if (getRawLayoutDirection() != layoutDirection) {
8659            // Reset the current layout direction and the resolved one
8660            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8661            resetRtlProperties();
8662            // Set the new layout direction (filtered)
8663            mPrivateFlags2 |=
8664                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8665            // We need to resolve all RTL properties as they all depend on layout direction
8666            resolveRtlPropertiesIfNeeded();
8667            requestLayout();
8668            invalidate(true);
8669        }
8670    }
8671
8672    /**
8673     * Returns the resolved layout direction for this view.
8674     *
8675     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8676     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8677     *
8678     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8679     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8680     *
8681     * @attr ref android.R.styleable#View_layoutDirection
8682     */
8683    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8684        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8685        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8686    })
8687    @ResolvedLayoutDir
8688    public int getLayoutDirection() {
8689        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8690        if (targetSdkVersion < JELLY_BEAN_MR1) {
8691            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8692            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8693        }
8694        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8695                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8696    }
8697
8698    /**
8699     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8700     * layout attribute and/or the inherited value from the parent
8701     *
8702     * @return true if the layout is right-to-left.
8703     *
8704     * @hide
8705     */
8706    @ViewDebug.ExportedProperty(category = "layout")
8707    public boolean isLayoutRtl() {
8708        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8709    }
8710
8711    /**
8712     * Indicates whether the view is currently tracking transient state that the
8713     * app should not need to concern itself with saving and restoring, but that
8714     * the framework should take special note to preserve when possible.
8715     *
8716     * <p>A view with transient state cannot be trivially rebound from an external
8717     * data source, such as an adapter binding item views in a list. This may be
8718     * because the view is performing an animation, tracking user selection
8719     * of content, or similar.</p>
8720     *
8721     * @return true if the view has transient state
8722     */
8723    @ViewDebug.ExportedProperty(category = "layout")
8724    public boolean hasTransientState() {
8725        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8726    }
8727
8728    /**
8729     * Set whether this view is currently tracking transient state that the
8730     * framework should attempt to preserve when possible. This flag is reference counted,
8731     * so every call to setHasTransientState(true) should be paired with a later call
8732     * to setHasTransientState(false).
8733     *
8734     * <p>A view with transient state cannot be trivially rebound from an external
8735     * data source, such as an adapter binding item views in a list. This may be
8736     * because the view is performing an animation, tracking user selection
8737     * of content, or similar.</p>
8738     *
8739     * @param hasTransientState true if this view has transient state
8740     */
8741    public void setHasTransientState(boolean hasTransientState) {
8742        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8743                mTransientStateCount - 1;
8744        if (mTransientStateCount < 0) {
8745            mTransientStateCount = 0;
8746            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8747                    "unmatched pair of setHasTransientState calls");
8748        } else if ((hasTransientState && mTransientStateCount == 1) ||
8749                (!hasTransientState && mTransientStateCount == 0)) {
8750            // update flag if we've just incremented up from 0 or decremented down to 0
8751            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8752                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8753            if (mParent != null) {
8754                try {
8755                    mParent.childHasTransientStateChanged(this, hasTransientState);
8756                } catch (AbstractMethodError e) {
8757                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8758                            " does not fully implement ViewParent", e);
8759                }
8760            }
8761        }
8762    }
8763
8764    /**
8765     * Returns true if this view is currently attached to a window.
8766     */
8767    public boolean isAttachedToWindow() {
8768        return mAttachInfo != null;
8769    }
8770
8771    /**
8772     * Returns true if this view has been through at least one layout since it
8773     * was last attached to or detached from a window.
8774     */
8775    public boolean isLaidOut() {
8776        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8777    }
8778
8779    /**
8780     * If this view doesn't do any drawing on its own, set this flag to
8781     * allow further optimizations. By default, this flag is not set on
8782     * View, but could be set on some View subclasses such as ViewGroup.
8783     *
8784     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8785     * you should clear this flag.
8786     *
8787     * @param willNotDraw whether or not this View draw on its own
8788     */
8789    public void setWillNotDraw(boolean willNotDraw) {
8790        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8791    }
8792
8793    /**
8794     * Returns whether or not this View draws on its own.
8795     *
8796     * @return true if this view has nothing to draw, false otherwise
8797     */
8798    @ViewDebug.ExportedProperty(category = "drawing")
8799    public boolean willNotDraw() {
8800        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8801    }
8802
8803    /**
8804     * When a View's drawing cache is enabled, drawing is redirected to an
8805     * offscreen bitmap. Some views, like an ImageView, must be able to
8806     * bypass this mechanism if they already draw a single bitmap, to avoid
8807     * unnecessary usage of the memory.
8808     *
8809     * @param willNotCacheDrawing true if this view does not cache its
8810     *        drawing, false otherwise
8811     */
8812    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8813        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8814    }
8815
8816    /**
8817     * Returns whether or not this View can cache its drawing or not.
8818     *
8819     * @return true if this view does not cache its drawing, false otherwise
8820     */
8821    @ViewDebug.ExportedProperty(category = "drawing")
8822    public boolean willNotCacheDrawing() {
8823        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8824    }
8825
8826    /**
8827     * Indicates whether this view reacts to click events or not.
8828     *
8829     * @return true if the view is clickable, false otherwise
8830     *
8831     * @see #setClickable(boolean)
8832     * @attr ref android.R.styleable#View_clickable
8833     */
8834    @ViewDebug.ExportedProperty
8835    public boolean isClickable() {
8836        return (mViewFlags & CLICKABLE) == CLICKABLE;
8837    }
8838
8839    /**
8840     * Enables or disables click events for this view. When a view
8841     * is clickable it will change its state to "pressed" on every click.
8842     * Subclasses should set the view clickable to visually react to
8843     * user's clicks.
8844     *
8845     * @param clickable true to make the view clickable, false otherwise
8846     *
8847     * @see #isClickable()
8848     * @attr ref android.R.styleable#View_clickable
8849     */
8850    public void setClickable(boolean clickable) {
8851        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8852    }
8853
8854    /**
8855     * Indicates whether this view reacts to long click events or not.
8856     *
8857     * @return true if the view is long clickable, false otherwise
8858     *
8859     * @see #setLongClickable(boolean)
8860     * @attr ref android.R.styleable#View_longClickable
8861     */
8862    public boolean isLongClickable() {
8863        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8864    }
8865
8866    /**
8867     * Enables or disables long click events for this view. When a view is long
8868     * clickable it reacts to the user holding down the button for a longer
8869     * duration than a tap. This event can either launch the listener or a
8870     * context menu.
8871     *
8872     * @param longClickable true to make the view long clickable, false otherwise
8873     * @see #isLongClickable()
8874     * @attr ref android.R.styleable#View_longClickable
8875     */
8876    public void setLongClickable(boolean longClickable) {
8877        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8878    }
8879
8880    /**
8881     * Indicates whether this view reacts to context clicks or not.
8882     *
8883     * @return true if the view is context clickable, false otherwise
8884     * @see #setContextClickable(boolean)
8885     * @attr ref android.R.styleable#View_contextClickable
8886     */
8887    public boolean isContextClickable() {
8888        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8889    }
8890
8891    /**
8892     * Enables or disables context clicking for this view. This event can launch the listener.
8893     *
8894     * @param contextClickable true to make the view react to a context click, false otherwise
8895     * @see #isContextClickable()
8896     * @attr ref android.R.styleable#View_contextClickable
8897     */
8898    public void setContextClickable(boolean contextClickable) {
8899        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8900    }
8901
8902    /**
8903     * Sets the pressed state for this view and provides a touch coordinate for
8904     * animation hinting.
8905     *
8906     * @param pressed Pass true to set the View's internal state to "pressed",
8907     *            or false to reverts the View's internal state from a
8908     *            previously set "pressed" state.
8909     * @param x The x coordinate of the touch that caused the press
8910     * @param y The y coordinate of the touch that caused the press
8911     */
8912    private void setPressed(boolean pressed, float x, float y) {
8913        if (pressed) {
8914            drawableHotspotChanged(x, y);
8915        }
8916
8917        setPressed(pressed);
8918    }
8919
8920    /**
8921     * Sets the pressed state for this view.
8922     *
8923     * @see #isClickable()
8924     * @see #setClickable(boolean)
8925     *
8926     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8927     *        the View's internal state from a previously set "pressed" state.
8928     */
8929    public void setPressed(boolean pressed) {
8930        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8931
8932        if (pressed) {
8933            mPrivateFlags |= PFLAG_PRESSED;
8934        } else {
8935            mPrivateFlags &= ~PFLAG_PRESSED;
8936        }
8937
8938        if (needsRefresh) {
8939            refreshDrawableState();
8940        }
8941        dispatchSetPressed(pressed);
8942    }
8943
8944    /**
8945     * Dispatch setPressed to all of this View's children.
8946     *
8947     * @see #setPressed(boolean)
8948     *
8949     * @param pressed The new pressed state
8950     */
8951    protected void dispatchSetPressed(boolean pressed) {
8952    }
8953
8954    /**
8955     * Indicates whether the view is currently in pressed state. Unless
8956     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8957     * the pressed state.
8958     *
8959     * @see #setPressed(boolean)
8960     * @see #isClickable()
8961     * @see #setClickable(boolean)
8962     *
8963     * @return true if the view is currently pressed, false otherwise
8964     */
8965    @ViewDebug.ExportedProperty
8966    public boolean isPressed() {
8967        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8968    }
8969
8970    /**
8971     * @hide
8972     * Indicates whether this view will participate in data collection through
8973     * {@link ViewStructure}.  If true, it will not provide any data
8974     * for itself or its children.  If false, the normal data collection will be allowed.
8975     *
8976     * @return Returns false if assist data collection is not blocked, else true.
8977     *
8978     * @see #setAssistBlocked(boolean)
8979     * @attr ref android.R.styleable#View_assistBlocked
8980     */
8981    public boolean isAssistBlocked() {
8982        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8983    }
8984
8985    /**
8986     * @hide
8987     * Indicates whether this view will participate in data collection through
8988     * {@link ViewStructure} for auto-fill purposes.
8989     *
8990     * <p>If {@code true}, it will not provide any data for itself or its children.
8991     * <p>If {@code false}, the normal data collection will be allowed.
8992     *
8993     * @return Returns {@code false} if assist data collection for auto-fill is not blocked,
8994     * else {@code true}.
8995     *
8996     * TODO(b/33197203): update / remove javadoc tags below
8997     * @see #setAssistBlocked(boolean)
8998     * @attr ref android.R.styleable#View_assistBlocked
8999     */
9000    public boolean isAutoFillBlocked() {
9001        return false; // TODO(b/33197203): properly implement it
9002    }
9003
9004    /**
9005     * @hide
9006     * Controls whether assist data collection from this view and its children is enabled
9007     * (that is, whether {@link #onProvideStructure} and
9008     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
9009     * allowing normal assist collection.  Setting this to false will disable assist collection.
9010     *
9011     * @param enabled Set to true to <em>disable</em> assist data collection, or false
9012     * (the default) to allow it.
9013     *
9014     * @see #isAssistBlocked()
9015     * @see #onProvideStructure
9016     * @see #onProvideVirtualStructure
9017     * @attr ref android.R.styleable#View_assistBlocked
9018     */
9019    public void setAssistBlocked(boolean enabled) {
9020        if (enabled) {
9021            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
9022        } else {
9023            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
9024        }
9025    }
9026
9027    /**
9028     * Indicates whether this view will save its state (that is,
9029     * whether its {@link #onSaveInstanceState} method will be called).
9030     *
9031     * @return Returns true if the view state saving is enabled, else false.
9032     *
9033     * @see #setSaveEnabled(boolean)
9034     * @attr ref android.R.styleable#View_saveEnabled
9035     */
9036    public boolean isSaveEnabled() {
9037        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
9038    }
9039
9040    /**
9041     * Controls whether the saving of this view's state is
9042     * enabled (that is, whether its {@link #onSaveInstanceState} method
9043     * will be called).  Note that even if freezing is enabled, the
9044     * view still must have an id assigned to it (via {@link #setId(int)})
9045     * for its state to be saved.  This flag can only disable the
9046     * saving of this view; any child views may still have their state saved.
9047     *
9048     * @param enabled Set to false to <em>disable</em> state saving, or true
9049     * (the default) to allow it.
9050     *
9051     * @see #isSaveEnabled()
9052     * @see #setId(int)
9053     * @see #onSaveInstanceState()
9054     * @attr ref android.R.styleable#View_saveEnabled
9055     */
9056    public void setSaveEnabled(boolean enabled) {
9057        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
9058    }
9059
9060    /**
9061     * Gets whether the framework should discard touches when the view's
9062     * window is obscured by another visible window.
9063     * Refer to the {@link View} security documentation for more details.
9064     *
9065     * @return True if touch filtering is enabled.
9066     *
9067     * @see #setFilterTouchesWhenObscured(boolean)
9068     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9069     */
9070    @ViewDebug.ExportedProperty
9071    public boolean getFilterTouchesWhenObscured() {
9072        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
9073    }
9074
9075    /**
9076     * Sets whether the framework should discard touches when the view's
9077     * window is obscured by another visible window.
9078     * Refer to the {@link View} security documentation for more details.
9079     *
9080     * @param enabled True if touch filtering should be enabled.
9081     *
9082     * @see #getFilterTouchesWhenObscured
9083     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9084     */
9085    public void setFilterTouchesWhenObscured(boolean enabled) {
9086        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
9087                FILTER_TOUCHES_WHEN_OBSCURED);
9088    }
9089
9090    /**
9091     * Indicates whether the entire hierarchy under this view will save its
9092     * state when a state saving traversal occurs from its parent.  The default
9093     * is true; if false, these views will not be saved unless
9094     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9095     *
9096     * @return Returns true if the view state saving from parent is enabled, else false.
9097     *
9098     * @see #setSaveFromParentEnabled(boolean)
9099     */
9100    public boolean isSaveFromParentEnabled() {
9101        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
9102    }
9103
9104    /**
9105     * Controls whether the entire hierarchy under this view will save its
9106     * state when a state saving traversal occurs from its parent.  The default
9107     * is true; if false, these views will not be saved unless
9108     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9109     *
9110     * @param enabled Set to false to <em>disable</em> state saving, or true
9111     * (the default) to allow it.
9112     *
9113     * @see #isSaveFromParentEnabled()
9114     * @see #setId(int)
9115     * @see #onSaveInstanceState()
9116     */
9117    public void setSaveFromParentEnabled(boolean enabled) {
9118        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
9119    }
9120
9121
9122    /**
9123     * Returns whether this View is able to take focus.
9124     *
9125     * @return True if this view can take focus, or false otherwise.
9126     * @attr ref android.R.styleable#View_focusable
9127     */
9128    @ViewDebug.ExportedProperty(category = "focus")
9129    public final boolean isFocusable() {
9130        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
9131    }
9132
9133    /**
9134     * When a view is focusable, it may not want to take focus when in touch mode.
9135     * For example, a button would like focus when the user is navigating via a D-pad
9136     * so that the user can click on it, but once the user starts touching the screen,
9137     * the button shouldn't take focus
9138     * @return Whether the view is focusable in touch mode.
9139     * @attr ref android.R.styleable#View_focusableInTouchMode
9140     */
9141    @ViewDebug.ExportedProperty
9142    public final boolean isFocusableInTouchMode() {
9143        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
9144    }
9145
9146    /**
9147     * Find the nearest view in the specified direction that can take focus.
9148     * This does not actually give focus to that view.
9149     *
9150     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9151     *
9152     * @return The nearest focusable in the specified direction, or null if none
9153     *         can be found.
9154     */
9155    public View focusSearch(@FocusRealDirection int direction) {
9156        if (mParent != null) {
9157            return mParent.focusSearch(this, direction);
9158        } else {
9159            return null;
9160        }
9161    }
9162
9163    /**
9164     * Returns whether this View is a root of a keyboard navigation cluster.
9165     *
9166     * @return True if this view is a root of a cluster, or false otherwise.
9167     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9168     */
9169    @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster")
9170    public final boolean isKeyboardNavigationCluster() {
9171        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
9172    }
9173
9174    /**
9175     * Set whether this view is a root of a keyboard navigation cluster.
9176     *
9177     * @param isCluster If true, this view is a root of a cluster.
9178     *
9179     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9180     */
9181    public void setKeyboardNavigationCluster(boolean isCluster) {
9182        if (isCluster) {
9183            mPrivateFlags3 |= PFLAG3_CLUSTER;
9184        } else {
9185            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
9186        }
9187    }
9188
9189    /**
9190     * Returns whether this View is a root of a keyboard navigation section.
9191     *
9192     * @return True if this view is a root of a section, or false otherwise.
9193     * @attr ref android.R.styleable#View_keyboardNavigationSection
9194     */
9195    @ViewDebug.ExportedProperty(category = "keyboardNavigationSection")
9196    public final boolean isKeyboardNavigationSection() {
9197        return (mPrivateFlags3 & PFLAG3_SECTION) != 0;
9198    }
9199
9200    /**
9201     * Set whether this view is a root of a keyboard navigation section.
9202     *
9203     * @param isSection If true, this view is a root of a section.
9204     *
9205     * @attr ref android.R.styleable#View_keyboardNavigationSection
9206     */
9207    public void setKeyboardNavigationSection(boolean isSection) {
9208        if (isSection) {
9209            mPrivateFlags3 |= PFLAG3_SECTION;
9210        } else {
9211            mPrivateFlags3 &= ~PFLAG3_SECTION;
9212        }
9213    }
9214
9215    final boolean isKeyboardNavigationGroupOfType(@KeyboardNavigationGroupType int groupType) {
9216        switch (groupType) {
9217            case KEYBOARD_NAVIGATION_GROUP_CLUSTER:
9218                return isKeyboardNavigationCluster();
9219            case KEYBOARD_NAVIGATION_GROUP_SECTION:
9220                return isKeyboardNavigationSection();
9221            default:
9222                throw new IllegalArgumentException(
9223                        "Unknown keyboard navigation group type: " + groupType);
9224        }
9225    }
9226
9227    /**
9228     * Returns whether this View should receive focus when the focus is restored for the view
9229     * hierarchy containing this view.
9230     * <p>
9231     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9232     * window or serves as a target of cluster or section navigation.
9233     *
9234     * @see #restoreDefaultFocus(int)
9235     *
9236     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
9237     * @attr ref android.R.styleable#View_focusedByDefault
9238     */
9239    @ViewDebug.ExportedProperty(category = "focusedByDefault")
9240    public final boolean isFocusedByDefault() {
9241        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
9242    }
9243
9244    /**
9245     * Sets whether this View should receive focus when the focus is restored for the view
9246     * hierarchy containing this view.
9247     * <p>
9248     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9249     * window or serves as a target of cluster or section navigation.
9250     *
9251     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
9252     *                           {@code false} otherwise.
9253     *
9254     * @see #restoreDefaultFocus(int)
9255     *
9256     * @attr ref android.R.styleable#View_focusedByDefault
9257     */
9258    public void setFocusedByDefault(boolean isFocusedByDefault) {
9259        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
9260            return;
9261        }
9262
9263        if (isFocusedByDefault) {
9264            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
9265        } else {
9266            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
9267        }
9268
9269        if (mParent instanceof ViewGroup) {
9270            if (isFocusedByDefault) {
9271                ((ViewGroup) mParent).setDefaultFocus(this);
9272            } else {
9273                ((ViewGroup) mParent).cleanDefaultFocus(this);
9274            }
9275        }
9276    }
9277
9278    /**
9279     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
9280     *
9281     * @return {@code true} if this view has default focus, {@code false} otherwise
9282     */
9283    boolean hasDefaultFocus() {
9284        return isFocusedByDefault();
9285    }
9286
9287    /**
9288     * Find the nearest keyboard navigation group in the specified direction. The group type can be
9289     * either a cluster or a section.
9290     * This does not actually give focus to that group.
9291     *
9292     * @param groupType Type of the keyboard navigation group
9293     * @param currentGroup The starting point of the search. Null means the current group is not
9294     *                     found yet
9295     * @param direction Direction to look
9296     *
9297     * @return The nearest keyboard navigation group in the specified direction, or null if none
9298     *         can be found
9299     */
9300    public View keyboardNavigationGroupSearch(
9301            @KeyboardNavigationGroupType int groupType, View currentGroup, int direction) {
9302        if (isKeyboardNavigationGroupOfType(groupType)) {
9303            currentGroup = this;
9304        }
9305        if (isRootNamespace()
9306                || (groupType == KEYBOARD_NAVIGATION_GROUP_SECTION
9307                && isKeyboardNavigationCluster())) {
9308            // Root namespace means we should consider ourselves the top of the
9309            // tree for group searching; otherwise we could be group searching
9310            // into other tabs.  see LocalActivityManager and TabHost for more info.
9311            // In addition, a cluster node works as a root for section searches.
9312            return FocusFinder.getInstance().findNextKeyboardNavigationGroup(
9313                    groupType, this, currentGroup, direction);
9314        } else if (mParent != null) {
9315            return mParent.keyboardNavigationGroupSearch(
9316                    groupType, currentGroup, direction);
9317        }
9318        return null;
9319    }
9320
9321    /**
9322     * This method is the last chance for the focused view and its ancestors to
9323     * respond to an arrow key. This is called when the focused view did not
9324     * consume the key internally, nor could the view system find a new view in
9325     * the requested direction to give focus to.
9326     *
9327     * @param focused The currently focused view.
9328     * @param direction The direction focus wants to move. One of FOCUS_UP,
9329     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
9330     * @return True if the this view consumed this unhandled move.
9331     */
9332    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
9333        return false;
9334    }
9335
9336    /**
9337     * If a user manually specified the next view id for a particular direction,
9338     * use the root to look up the view.
9339     * @param root The root view of the hierarchy containing this view.
9340     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
9341     * or FOCUS_BACKWARD.
9342     * @return The user specified next view, or null if there is none.
9343     */
9344    View findUserSetNextFocus(View root, @FocusDirection int direction) {
9345        switch (direction) {
9346            case FOCUS_LEFT:
9347                if (mNextFocusLeftId == View.NO_ID) return null;
9348                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
9349            case FOCUS_RIGHT:
9350                if (mNextFocusRightId == View.NO_ID) return null;
9351                return findViewInsideOutShouldExist(root, mNextFocusRightId);
9352            case FOCUS_UP:
9353                if (mNextFocusUpId == View.NO_ID) return null;
9354                return findViewInsideOutShouldExist(root, mNextFocusUpId);
9355            case FOCUS_DOWN:
9356                if (mNextFocusDownId == View.NO_ID) return null;
9357                return findViewInsideOutShouldExist(root, mNextFocusDownId);
9358            case FOCUS_FORWARD:
9359                if (mNextFocusForwardId == View.NO_ID) return null;
9360                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
9361            case FOCUS_BACKWARD: {
9362                if (mID == View.NO_ID) return null;
9363                final int id = mID;
9364                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
9365                    @Override
9366                    public boolean apply(View t) {
9367                        return t.mNextFocusForwardId == id;
9368                    }
9369                });
9370            }
9371        }
9372        return null;
9373    }
9374
9375    private View findViewInsideOutShouldExist(View root, int id) {
9376        if (mMatchIdPredicate == null) {
9377            mMatchIdPredicate = new MatchIdPredicate();
9378        }
9379        mMatchIdPredicate.mId = id;
9380        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
9381        if (result == null) {
9382            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
9383        }
9384        return result;
9385    }
9386
9387    /**
9388     * Find and return all focusable views that are descendants of this view,
9389     * possibly including this view if it is focusable itself.
9390     *
9391     * @param direction The direction of the focus
9392     * @return A list of focusable views
9393     */
9394    public ArrayList<View> getFocusables(@FocusDirection int direction) {
9395        ArrayList<View> result = new ArrayList<View>(24);
9396        addFocusables(result, direction);
9397        return result;
9398    }
9399
9400    /**
9401     * Add any focusable views that are descendants of this view (possibly
9402     * including this view if it is focusable itself) to views.  If we are in touch mode,
9403     * only add views that are also focusable in touch mode.
9404     *
9405     * @param views Focusable views found so far
9406     * @param direction The direction of the focus
9407     */
9408    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
9409        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
9410    }
9411
9412    /**
9413     * Adds any focusable views that are descendants of this view (possibly
9414     * including this view if it is focusable itself) to views. This method
9415     * adds all focusable views regardless if we are in touch mode or
9416     * only views focusable in touch mode if we are in touch mode or
9417     * only views that can take accessibility focus if accessibility is enabled
9418     * depending on the focusable mode parameter.
9419     *
9420     * @param views Focusable views found so far or null if all we are interested is
9421     *        the number of focusables.
9422     * @param direction The direction of the focus.
9423     * @param focusableMode The type of focusables to be added.
9424     *
9425     * @see #FOCUSABLES_ALL
9426     * @see #FOCUSABLES_TOUCH_MODE
9427     */
9428    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
9429            @FocusableMode int focusableMode) {
9430        if (views == null) {
9431            return;
9432        }
9433        if (!isFocusable()) {
9434            return;
9435        }
9436        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
9437                && !isFocusableInTouchMode()) {
9438            return;
9439        }
9440        views.add(this);
9441    }
9442
9443    /**
9444     * Adds any keyboard navigation group roots that are descendants of this view (possibly
9445     * including this view if it is a group root itself) to views. The group type can be either a
9446     * cluster or a section.
9447     *
9448     * @param groupType Type of the keyboard navigation group
9449     * @param views Keyboard navigation group roots found so far
9450     * @param direction Direction to look
9451     */
9452    public void addKeyboardNavigationGroups(
9453            @KeyboardNavigationGroupType int groupType,
9454            @NonNull Collection<View> views,
9455            int direction) {
9456        if (!(isKeyboardNavigationGroupOfType(groupType))) {
9457            return;
9458        }
9459        views.add(this);
9460    }
9461
9462    /**
9463     * Finds the Views that contain given text. The containment is case insensitive.
9464     * The search is performed by either the text that the View renders or the content
9465     * description that describes the view for accessibility purposes and the view does
9466     * not render or both. Clients can specify how the search is to be performed via
9467     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
9468     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
9469     *
9470     * @param outViews The output list of matching Views.
9471     * @param searched The text to match against.
9472     *
9473     * @see #FIND_VIEWS_WITH_TEXT
9474     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
9475     * @see #setContentDescription(CharSequence)
9476     */
9477    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
9478            @FindViewFlags int flags) {
9479        if (getAccessibilityNodeProvider() != null) {
9480            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
9481                outViews.add(this);
9482            }
9483        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
9484                && (searched != null && searched.length() > 0)
9485                && (mContentDescription != null && mContentDescription.length() > 0)) {
9486            String searchedLowerCase = searched.toString().toLowerCase();
9487            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
9488            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
9489                outViews.add(this);
9490            }
9491        }
9492    }
9493
9494    /**
9495     * Find and return all touchable views that are descendants of this view,
9496     * possibly including this view if it is touchable itself.
9497     *
9498     * @return A list of touchable views
9499     */
9500    public ArrayList<View> getTouchables() {
9501        ArrayList<View> result = new ArrayList<View>();
9502        addTouchables(result);
9503        return result;
9504    }
9505
9506    /**
9507     * Add any touchable views that are descendants of this view (possibly
9508     * including this view if it is touchable itself) to views.
9509     *
9510     * @param views Touchable views found so far
9511     */
9512    public void addTouchables(ArrayList<View> views) {
9513        final int viewFlags = mViewFlags;
9514
9515        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
9516                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
9517                && (viewFlags & ENABLED_MASK) == ENABLED) {
9518            views.add(this);
9519        }
9520    }
9521
9522    /**
9523     * Returns whether this View is accessibility focused.
9524     *
9525     * @return True if this View is accessibility focused.
9526     */
9527    public boolean isAccessibilityFocused() {
9528        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
9529    }
9530
9531    /**
9532     * Call this to try to give accessibility focus to this view.
9533     *
9534     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
9535     * returns false or the view is no visible or the view already has accessibility
9536     * focus.
9537     *
9538     * See also {@link #focusSearch(int)}, which is what you call to say that you
9539     * have focus, and you want your parent to look for the next one.
9540     *
9541     * @return Whether this view actually took accessibility focus.
9542     *
9543     * @hide
9544     */
9545    public boolean requestAccessibilityFocus() {
9546        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
9547        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
9548            return false;
9549        }
9550        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9551            return false;
9552        }
9553        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
9554            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
9555            ViewRootImpl viewRootImpl = getViewRootImpl();
9556            if (viewRootImpl != null) {
9557                viewRootImpl.setAccessibilityFocus(this, null);
9558            }
9559            invalidate();
9560            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
9561            return true;
9562        }
9563        return false;
9564    }
9565
9566    /**
9567     * Call this to try to clear accessibility focus of this view.
9568     *
9569     * See also {@link #focusSearch(int)}, which is what you call to say that you
9570     * have focus, and you want your parent to look for the next one.
9571     *
9572     * @hide
9573     */
9574    public void clearAccessibilityFocus() {
9575        clearAccessibilityFocusNoCallbacks(0);
9576
9577        // Clear the global reference of accessibility focus if this view or
9578        // any of its descendants had accessibility focus. This will NOT send
9579        // an event or update internal state if focus is cleared from a
9580        // descendant view, which may leave views in inconsistent states.
9581        final ViewRootImpl viewRootImpl = getViewRootImpl();
9582        if (viewRootImpl != null) {
9583            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
9584            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9585                viewRootImpl.setAccessibilityFocus(null, null);
9586            }
9587        }
9588    }
9589
9590    private void sendAccessibilityHoverEvent(int eventType) {
9591        // Since we are not delivering to a client accessibility events from not
9592        // important views (unless the clinet request that) we need to fire the
9593        // event from the deepest view exposed to the client. As a consequence if
9594        // the user crosses a not exposed view the client will see enter and exit
9595        // of the exposed predecessor followed by and enter and exit of that same
9596        // predecessor when entering and exiting the not exposed descendant. This
9597        // is fine since the client has a clear idea which view is hovered at the
9598        // price of a couple more events being sent. This is a simple and
9599        // working solution.
9600        View source = this;
9601        while (true) {
9602            if (source.includeForAccessibility()) {
9603                source.sendAccessibilityEvent(eventType);
9604                return;
9605            }
9606            ViewParent parent = source.getParent();
9607            if (parent instanceof View) {
9608                source = (View) parent;
9609            } else {
9610                return;
9611            }
9612        }
9613    }
9614
9615    /**
9616     * Clears accessibility focus without calling any callback methods
9617     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9618     * is used separately from that one for clearing accessibility focus when
9619     * giving this focus to another view.
9620     *
9621     * @param action The action, if any, that led to focus being cleared. Set to
9622     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9623     * the window.
9624     */
9625    void clearAccessibilityFocusNoCallbacks(int action) {
9626        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9627            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9628            invalidate();
9629            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9630                AccessibilityEvent event = AccessibilityEvent.obtain(
9631                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9632                event.setAction(action);
9633                if (mAccessibilityDelegate != null) {
9634                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9635                } else {
9636                    sendAccessibilityEventUnchecked(event);
9637                }
9638            }
9639        }
9640    }
9641
9642    /**
9643     * Call this to try to give focus to a specific view or to one of its
9644     * descendants.
9645     *
9646     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9647     * false), or if it is focusable and it is not focusable in touch mode
9648     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9649     *
9650     * See also {@link #focusSearch(int)}, which is what you call to say that you
9651     * have focus, and you want your parent to look for the next one.
9652     *
9653     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9654     * {@link #FOCUS_DOWN} and <code>null</code>.
9655     *
9656     * @return Whether this view or one of its descendants actually took focus.
9657     */
9658    public final boolean requestFocus() {
9659        return requestFocus(View.FOCUS_DOWN);
9660    }
9661
9662    /**
9663     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
9664     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
9665     * Nested keyboard navigation clusters are excluded from the hierarchy.
9666     *
9667     * @param direction The direction of the focus
9668     * @return Whether this view or one of its descendants actually took focus
9669     */
9670    public boolean restoreDefaultFocus(@FocusDirection int direction) {
9671        return requestFocus(direction);
9672    }
9673
9674    /**
9675     * Call this to try to give focus to a specific view or to one of its
9676     * descendants and give it a hint about what direction focus is heading.
9677     *
9678     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9679     * false), or if it is focusable and it is not focusable in touch mode
9680     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9681     *
9682     * See also {@link #focusSearch(int)}, which is what you call to say that you
9683     * have focus, and you want your parent to look for the next one.
9684     *
9685     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9686     * <code>null</code> set for the previously focused rectangle.
9687     *
9688     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9689     * @return Whether this view or one of its descendants actually took focus.
9690     */
9691    public final boolean requestFocus(int direction) {
9692        return requestFocus(direction, null);
9693    }
9694
9695    /**
9696     * Call this to try to give focus to a specific view or to one of its descendants
9697     * and give it hints about the direction and a specific rectangle that the focus
9698     * is coming from.  The rectangle can help give larger views a finer grained hint
9699     * about where focus is coming from, and therefore, where to show selection, or
9700     * forward focus change internally.
9701     *
9702     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9703     * false), or if it is focusable and it is not focusable in touch mode
9704     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9705     *
9706     * A View will not take focus if it is not visible.
9707     *
9708     * A View will not take focus if one of its parents has
9709     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9710     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9711     *
9712     * See also {@link #focusSearch(int)}, which is what you call to say that you
9713     * have focus, and you want your parent to look for the next one.
9714     *
9715     * You may wish to override this method if your custom {@link View} has an internal
9716     * {@link View} that it wishes to forward the request to.
9717     *
9718     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9719     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9720     *        to give a finer grained hint about where focus is coming from.  May be null
9721     *        if there is no hint.
9722     * @return Whether this view or one of its descendants actually took focus.
9723     */
9724    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9725        return requestFocusNoSearch(direction, previouslyFocusedRect);
9726    }
9727
9728    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9729        // need to be focusable
9730        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9731                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9732            return false;
9733        }
9734
9735        // need to be focusable in touch mode if in touch mode
9736        if (isInTouchMode() &&
9737            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9738               return false;
9739        }
9740
9741        // need to not have any parents blocking us
9742        if (hasAncestorThatBlocksDescendantFocus()) {
9743            return false;
9744        }
9745
9746        handleFocusGainInternal(direction, previouslyFocusedRect);
9747        return true;
9748    }
9749
9750    /**
9751     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9752     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9753     * touch mode to request focus when they are touched.
9754     *
9755     * @return Whether this view or one of its descendants actually took focus.
9756     *
9757     * @see #isInTouchMode()
9758     *
9759     */
9760    public final boolean requestFocusFromTouch() {
9761        // Leave touch mode if we need to
9762        if (isInTouchMode()) {
9763            ViewRootImpl viewRoot = getViewRootImpl();
9764            if (viewRoot != null) {
9765                viewRoot.ensureTouchMode(false);
9766            }
9767        }
9768        return requestFocus(View.FOCUS_DOWN);
9769    }
9770
9771    /**
9772     * @return Whether any ancestor of this view blocks descendant focus.
9773     */
9774    private boolean hasAncestorThatBlocksDescendantFocus() {
9775        final boolean focusableInTouchMode = isFocusableInTouchMode();
9776        ViewParent ancestor = mParent;
9777        while (ancestor instanceof ViewGroup) {
9778            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9779            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9780                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9781                return true;
9782            } else {
9783                ancestor = vgAncestor.getParent();
9784            }
9785        }
9786        return false;
9787    }
9788
9789    /**
9790     * Gets the mode for determining whether this View is important for accessibility.
9791     * A view is important for accessibility if it fires accessibility events and if it
9792     * is reported to accessibility services that query the screen.
9793     *
9794     * @return The mode for determining whether a view is important for accessibility, one
9795     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
9796     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
9797     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
9798     *
9799     * @attr ref android.R.styleable#View_importantForAccessibility
9800     *
9801     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9802     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9803     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9804     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9805     */
9806    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9807            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9808            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9809            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9810            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9811                    to = "noHideDescendants")
9812        })
9813    public int getImportantForAccessibility() {
9814        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9815                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9816    }
9817
9818    /**
9819     * Sets the live region mode for this view. This indicates to accessibility
9820     * services whether they should automatically notify the user about changes
9821     * to the view's content description or text, or to the content descriptions
9822     * or text of the view's children (where applicable).
9823     * <p>
9824     * For example, in a login screen with a TextView that displays an "incorrect
9825     * password" notification, that view should be marked as a live region with
9826     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9827     * <p>
9828     * To disable change notifications for this view, use
9829     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9830     * mode for most views.
9831     * <p>
9832     * To indicate that the user should be notified of changes, use
9833     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9834     * <p>
9835     * If the view's changes should interrupt ongoing speech and notify the user
9836     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9837     *
9838     * @param mode The live region mode for this view, one of:
9839     *        <ul>
9840     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9841     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9842     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9843     *        </ul>
9844     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9845     */
9846    public void setAccessibilityLiveRegion(int mode) {
9847        if (mode != getAccessibilityLiveRegion()) {
9848            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9849            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9850                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9851            notifyViewAccessibilityStateChangedIfNeeded(
9852                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9853        }
9854    }
9855
9856    /**
9857     * Gets the live region mode for this View.
9858     *
9859     * @return The live region mode for the view.
9860     *
9861     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9862     *
9863     * @see #setAccessibilityLiveRegion(int)
9864     */
9865    public int getAccessibilityLiveRegion() {
9866        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9867                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9868    }
9869
9870    /**
9871     * Sets how to determine whether this view is important for accessibility
9872     * which is if it fires accessibility events and if it is reported to
9873     * accessibility services that query the screen.
9874     *
9875     * @param mode How to determine whether this view is important for accessibility.
9876     *
9877     * @attr ref android.R.styleable#View_importantForAccessibility
9878     *
9879     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9880     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9881     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9882     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9883     */
9884    public void setImportantForAccessibility(int mode) {
9885        final int oldMode = getImportantForAccessibility();
9886        if (mode != oldMode) {
9887            final boolean hideDescendants =
9888                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9889
9890            // If this node or its descendants are no longer important, try to
9891            // clear accessibility focus.
9892            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9893                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9894                if (focusHost != null) {
9895                    focusHost.clearAccessibilityFocus();
9896                }
9897            }
9898
9899            // If we're moving between AUTO and another state, we might not need
9900            // to send a subtree changed notification. We'll store the computed
9901            // importance, since we'll need to check it later to make sure.
9902            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9903                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9904            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9905            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9906            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9907                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9908            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9909                notifySubtreeAccessibilityStateChangedIfNeeded();
9910            } else {
9911                notifyViewAccessibilityStateChangedIfNeeded(
9912                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9913            }
9914        }
9915    }
9916
9917    /**
9918     * Returns the view within this view's hierarchy that is hosting
9919     * accessibility focus.
9920     *
9921     * @param searchDescendants whether to search for focus in descendant views
9922     * @return the view hosting accessibility focus, or {@code null}
9923     */
9924    private View findAccessibilityFocusHost(boolean searchDescendants) {
9925        if (isAccessibilityFocusedViewOrHost()) {
9926            return this;
9927        }
9928
9929        if (searchDescendants) {
9930            final ViewRootImpl viewRoot = getViewRootImpl();
9931            if (viewRoot != null) {
9932                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9933                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9934                    return focusHost;
9935                }
9936            }
9937        }
9938
9939        return null;
9940    }
9941
9942    /**
9943     * Computes whether this view should be exposed for accessibility. In
9944     * general, views that are interactive or provide information are exposed
9945     * while views that serve only as containers are hidden.
9946     * <p>
9947     * If an ancestor of this view has importance
9948     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9949     * returns <code>false</code>.
9950     * <p>
9951     * Otherwise, the value is computed according to the view's
9952     * {@link #getImportantForAccessibility()} value:
9953     * <ol>
9954     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9955     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9956     * </code>
9957     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9958     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9959     * view satisfies any of the following:
9960     * <ul>
9961     * <li>Is actionable, e.g. {@link #isClickable()},
9962     * {@link #isLongClickable()}, or {@link #isFocusable()}
9963     * <li>Has an {@link AccessibilityDelegate}
9964     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9965     * {@link OnKeyListener}, etc.
9966     * <li>Is an accessibility live region, e.g.
9967     * {@link #getAccessibilityLiveRegion()} is not
9968     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9969     * </ul>
9970     * </ol>
9971     *
9972     * @return Whether the view is exposed for accessibility.
9973     * @see #setImportantForAccessibility(int)
9974     * @see #getImportantForAccessibility()
9975     */
9976    public boolean isImportantForAccessibility() {
9977        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9978                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9979        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9980                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9981            return false;
9982        }
9983
9984        // Check parent mode to ensure we're not hidden.
9985        ViewParent parent = mParent;
9986        while (parent instanceof View) {
9987            if (((View) parent).getImportantForAccessibility()
9988                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9989                return false;
9990            }
9991            parent = parent.getParent();
9992        }
9993
9994        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9995                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9996                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9997    }
9998
9999    /**
10000     * Gets the parent for accessibility purposes. Note that the parent for
10001     * accessibility is not necessary the immediate parent. It is the first
10002     * predecessor that is important for accessibility.
10003     *
10004     * @return The parent for accessibility purposes.
10005     */
10006    public ViewParent getParentForAccessibility() {
10007        if (mParent instanceof View) {
10008            View parentView = (View) mParent;
10009            if (parentView.includeForAccessibility()) {
10010                return mParent;
10011            } else {
10012                return mParent.getParentForAccessibility();
10013            }
10014        }
10015        return null;
10016    }
10017
10018    /**
10019     * Adds the children of this View relevant for accessibility to the given list
10020     * as output. Since some Views are not important for accessibility the added
10021     * child views are not necessarily direct children of this view, rather they are
10022     * the first level of descendants important for accessibility.
10023     *
10024     * @param outChildren The output list that will receive children for accessibility.
10025     */
10026    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
10027
10028    }
10029
10030    /**
10031     * Whether to regard this view for accessibility. A view is regarded for
10032     * accessibility if it is important for accessibility or the querying
10033     * accessibility service has explicitly requested that view not
10034     * important for accessibility are regarded.
10035     *
10036     * @return Whether to regard the view for accessibility.
10037     *
10038     * @hide
10039     */
10040    public boolean includeForAccessibility() {
10041        if (mAttachInfo != null) {
10042            return (mAttachInfo.mAccessibilityFetchFlags
10043                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
10044                    || isImportantForAccessibility();
10045        }
10046        return false;
10047    }
10048
10049    /**
10050     * Returns whether the View is considered actionable from
10051     * accessibility perspective. Such view are important for
10052     * accessibility.
10053     *
10054     * @return True if the view is actionable for accessibility.
10055     *
10056     * @hide
10057     */
10058    public boolean isActionableForAccessibility() {
10059        return (isClickable() || isLongClickable() || isFocusable());
10060    }
10061
10062    /**
10063     * Returns whether the View has registered callbacks which makes it
10064     * important for accessibility.
10065     *
10066     * @return True if the view is actionable for accessibility.
10067     */
10068    private boolean hasListenersForAccessibility() {
10069        ListenerInfo info = getListenerInfo();
10070        return mTouchDelegate != null || info.mOnKeyListener != null
10071                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
10072                || info.mOnHoverListener != null || info.mOnDragListener != null;
10073    }
10074
10075    /**
10076     * Notifies that the accessibility state of this view changed. The change
10077     * is local to this view and does not represent structural changes such
10078     * as children and parent. For example, the view became focusable. The
10079     * notification is at at most once every
10080     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10081     * to avoid unnecessary load to the system. Also once a view has a pending
10082     * notification this method is a NOP until the notification has been sent.
10083     *
10084     * @hide
10085     */
10086    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
10087        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10088            return;
10089        }
10090        if (mSendViewStateChangedAccessibilityEvent == null) {
10091            mSendViewStateChangedAccessibilityEvent =
10092                    new SendViewStateChangedAccessibilityEvent();
10093        }
10094        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
10095    }
10096
10097    /**
10098     * Notifies that the accessibility state of this view changed. The change
10099     * is *not* local to this view and does represent structural changes such
10100     * as children and parent. For example, the view size changed. The
10101     * notification is at at most once every
10102     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10103     * to avoid unnecessary load to the system. Also once a view has a pending
10104     * notification this method is a NOP until the notification has been sent.
10105     *
10106     * @hide
10107     */
10108    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
10109        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10110            return;
10111        }
10112        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
10113            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10114            if (mParent != null) {
10115                try {
10116                    mParent.notifySubtreeAccessibilityStateChanged(
10117                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
10118                } catch (AbstractMethodError e) {
10119                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10120                            " does not fully implement ViewParent", e);
10121                }
10122            }
10123        }
10124    }
10125
10126    /**
10127     * Change the visibility of the View without triggering any other changes. This is
10128     * important for transitions, where visibility changes should not adjust focus or
10129     * trigger a new layout. This is only used when the visibility has already been changed
10130     * and we need a transient value during an animation. When the animation completes,
10131     * the original visibility value is always restored.
10132     *
10133     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
10134     * @hide
10135     */
10136    public void setTransitionVisibility(@Visibility int visibility) {
10137        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
10138    }
10139
10140    /**
10141     * Reset the flag indicating the accessibility state of the subtree rooted
10142     * at this view changed.
10143     */
10144    void resetSubtreeAccessibilityStateChanged() {
10145        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10146    }
10147
10148    /**
10149     * Report an accessibility action to this view's parents for delegated processing.
10150     *
10151     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
10152     * call this method to delegate an accessibility action to a supporting parent. If the parent
10153     * returns true from its
10154     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
10155     * method this method will return true to signify that the action was consumed.</p>
10156     *
10157     * <p>This method is useful for implementing nested scrolling child views. If
10158     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
10159     * a custom view implementation may invoke this method to allow a parent to consume the
10160     * scroll first. If this method returns true the custom view should skip its own scrolling
10161     * behavior.</p>
10162     *
10163     * @param action Accessibility action to delegate
10164     * @param arguments Optional action arguments
10165     * @return true if the action was consumed by a parent
10166     */
10167    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
10168        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
10169            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
10170                return true;
10171            }
10172        }
10173        return false;
10174    }
10175
10176    /**
10177     * Performs the specified accessibility action on the view. For
10178     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
10179     * <p>
10180     * If an {@link AccessibilityDelegate} has been specified via calling
10181     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
10182     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
10183     * is responsible for handling this call.
10184     * </p>
10185     *
10186     * <p>The default implementation will delegate
10187     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
10188     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
10189     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
10190     *
10191     * @param action The action to perform.
10192     * @param arguments Optional action arguments.
10193     * @return Whether the action was performed.
10194     */
10195    public boolean performAccessibilityAction(int action, Bundle arguments) {
10196      if (mAccessibilityDelegate != null) {
10197          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
10198      } else {
10199          return performAccessibilityActionInternal(action, arguments);
10200      }
10201    }
10202
10203   /**
10204    * @see #performAccessibilityAction(int, Bundle)
10205    *
10206    * Note: Called from the default {@link AccessibilityDelegate}.
10207    *
10208    * @hide
10209    */
10210    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
10211        if (isNestedScrollingEnabled()
10212                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
10213                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
10214                || action == R.id.accessibilityActionScrollUp
10215                || action == R.id.accessibilityActionScrollLeft
10216                || action == R.id.accessibilityActionScrollDown
10217                || action == R.id.accessibilityActionScrollRight)) {
10218            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
10219                return true;
10220            }
10221        }
10222
10223        switch (action) {
10224            case AccessibilityNodeInfo.ACTION_CLICK: {
10225                if (isClickable()) {
10226                    performClick();
10227                    return true;
10228                }
10229            } break;
10230            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
10231                if (isLongClickable()) {
10232                    performLongClick();
10233                    return true;
10234                }
10235            } break;
10236            case AccessibilityNodeInfo.ACTION_FOCUS: {
10237                if (!hasFocus()) {
10238                    // Get out of touch mode since accessibility
10239                    // wants to move focus around.
10240                    getViewRootImpl().ensureTouchMode(false);
10241                    return requestFocus();
10242                }
10243            } break;
10244            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
10245                if (hasFocus()) {
10246                    clearFocus();
10247                    return !isFocused();
10248                }
10249            } break;
10250            case AccessibilityNodeInfo.ACTION_SELECT: {
10251                if (!isSelected()) {
10252                    setSelected(true);
10253                    return isSelected();
10254                }
10255            } break;
10256            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
10257                if (isSelected()) {
10258                    setSelected(false);
10259                    return !isSelected();
10260                }
10261            } break;
10262            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
10263                if (!isAccessibilityFocused()) {
10264                    return requestAccessibilityFocus();
10265                }
10266            } break;
10267            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
10268                if (isAccessibilityFocused()) {
10269                    clearAccessibilityFocus();
10270                    return true;
10271                }
10272            } break;
10273            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
10274                if (arguments != null) {
10275                    final int granularity = arguments.getInt(
10276                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10277                    final boolean extendSelection = arguments.getBoolean(
10278                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10279                    return traverseAtGranularity(granularity, true, extendSelection);
10280                }
10281            } break;
10282            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
10283                if (arguments != null) {
10284                    final int granularity = arguments.getInt(
10285                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10286                    final boolean extendSelection = arguments.getBoolean(
10287                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10288                    return traverseAtGranularity(granularity, false, extendSelection);
10289                }
10290            } break;
10291            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
10292                CharSequence text = getIterableTextForAccessibility();
10293                if (text == null) {
10294                    return false;
10295                }
10296                final int start = (arguments != null) ? arguments.getInt(
10297                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
10298                final int end = (arguments != null) ? arguments.getInt(
10299                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
10300                // Only cursor position can be specified (selection length == 0)
10301                if ((getAccessibilitySelectionStart() != start
10302                        || getAccessibilitySelectionEnd() != end)
10303                        && (start == end)) {
10304                    setAccessibilitySelection(start, end);
10305                    notifyViewAccessibilityStateChangedIfNeeded(
10306                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10307                    return true;
10308                }
10309            } break;
10310            case R.id.accessibilityActionShowOnScreen: {
10311                if (mAttachInfo != null) {
10312                    final Rect r = mAttachInfo.mTmpInvalRect;
10313                    getDrawingRect(r);
10314                    return requestRectangleOnScreen(r, true);
10315                }
10316            } break;
10317            case R.id.accessibilityActionContextClick: {
10318                if (isContextClickable()) {
10319                    performContextClick();
10320                    return true;
10321                }
10322            } break;
10323        }
10324        return false;
10325    }
10326
10327    private boolean traverseAtGranularity(int granularity, boolean forward,
10328            boolean extendSelection) {
10329        CharSequence text = getIterableTextForAccessibility();
10330        if (text == null || text.length() == 0) {
10331            return false;
10332        }
10333        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
10334        if (iterator == null) {
10335            return false;
10336        }
10337        int current = getAccessibilitySelectionEnd();
10338        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10339            current = forward ? 0 : text.length();
10340        }
10341        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
10342        if (range == null) {
10343            return false;
10344        }
10345        final int segmentStart = range[0];
10346        final int segmentEnd = range[1];
10347        int selectionStart;
10348        int selectionEnd;
10349        if (extendSelection && isAccessibilitySelectionExtendable()) {
10350            selectionStart = getAccessibilitySelectionStart();
10351            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
10352                selectionStart = forward ? segmentStart : segmentEnd;
10353            }
10354            selectionEnd = forward ? segmentEnd : segmentStart;
10355        } else {
10356            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
10357        }
10358        setAccessibilitySelection(selectionStart, selectionEnd);
10359        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
10360                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
10361        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
10362        return true;
10363    }
10364
10365    /**
10366     * Gets the text reported for accessibility purposes.
10367     *
10368     * @return The accessibility text.
10369     *
10370     * @hide
10371     */
10372    public CharSequence getIterableTextForAccessibility() {
10373        return getContentDescription();
10374    }
10375
10376    /**
10377     * Gets whether accessibility selection can be extended.
10378     *
10379     * @return If selection is extensible.
10380     *
10381     * @hide
10382     */
10383    public boolean isAccessibilitySelectionExtendable() {
10384        return false;
10385    }
10386
10387    /**
10388     * @hide
10389     */
10390    public int getAccessibilitySelectionStart() {
10391        return mAccessibilityCursorPosition;
10392    }
10393
10394    /**
10395     * @hide
10396     */
10397    public int getAccessibilitySelectionEnd() {
10398        return getAccessibilitySelectionStart();
10399    }
10400
10401    /**
10402     * @hide
10403     */
10404    public void setAccessibilitySelection(int start, int end) {
10405        if (start ==  end && end == mAccessibilityCursorPosition) {
10406            return;
10407        }
10408        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
10409            mAccessibilityCursorPosition = start;
10410        } else {
10411            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
10412        }
10413        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
10414    }
10415
10416    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
10417            int fromIndex, int toIndex) {
10418        if (mParent == null) {
10419            return;
10420        }
10421        AccessibilityEvent event = AccessibilityEvent.obtain(
10422                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
10423        onInitializeAccessibilityEvent(event);
10424        onPopulateAccessibilityEvent(event);
10425        event.setFromIndex(fromIndex);
10426        event.setToIndex(toIndex);
10427        event.setAction(action);
10428        event.setMovementGranularity(granularity);
10429        mParent.requestSendAccessibilityEvent(this, event);
10430    }
10431
10432    /**
10433     * @hide
10434     */
10435    public TextSegmentIterator getIteratorForGranularity(int granularity) {
10436        switch (granularity) {
10437            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
10438                CharSequence text = getIterableTextForAccessibility();
10439                if (text != null && text.length() > 0) {
10440                    CharacterTextSegmentIterator iterator =
10441                        CharacterTextSegmentIterator.getInstance(
10442                                mContext.getResources().getConfiguration().locale);
10443                    iterator.initialize(text.toString());
10444                    return iterator;
10445                }
10446            } break;
10447            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
10448                CharSequence text = getIterableTextForAccessibility();
10449                if (text != null && text.length() > 0) {
10450                    WordTextSegmentIterator iterator =
10451                        WordTextSegmentIterator.getInstance(
10452                                mContext.getResources().getConfiguration().locale);
10453                    iterator.initialize(text.toString());
10454                    return iterator;
10455                }
10456            } break;
10457            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
10458                CharSequence text = getIterableTextForAccessibility();
10459                if (text != null && text.length() > 0) {
10460                    ParagraphTextSegmentIterator iterator =
10461                        ParagraphTextSegmentIterator.getInstance();
10462                    iterator.initialize(text.toString());
10463                    return iterator;
10464                }
10465            } break;
10466        }
10467        return null;
10468    }
10469
10470    /**
10471     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
10472     * and {@link #onFinishTemporaryDetach()}.
10473     *
10474     * <p>This method always returns {@code true} when called directly or indirectly from
10475     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
10476     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
10477     * <ul>
10478     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
10479     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
10480     * </ul>
10481     * </p>
10482     *
10483     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
10484     * and {@link #onFinishTemporaryDetach()}.
10485     */
10486    public final boolean isTemporarilyDetached() {
10487        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
10488    }
10489
10490    /**
10491     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
10492     * a container View.
10493     */
10494    @CallSuper
10495    public void dispatchStartTemporaryDetach() {
10496        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
10497        onStartTemporaryDetach();
10498    }
10499
10500    /**
10501     * This is called when a container is going to temporarily detach a child, with
10502     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
10503     * It will either be followed by {@link #onFinishTemporaryDetach()} or
10504     * {@link #onDetachedFromWindow()} when the container is done.
10505     */
10506    public void onStartTemporaryDetach() {
10507        removeUnsetPressCallback();
10508        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
10509    }
10510
10511    /**
10512     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
10513     * a container View.
10514     */
10515    @CallSuper
10516    public void dispatchFinishTemporaryDetach() {
10517        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
10518        onFinishTemporaryDetach();
10519        if (hasWindowFocus() && hasFocus()) {
10520            InputMethodManager.getInstance().focusIn(this);
10521        }
10522    }
10523
10524    /**
10525     * Called after {@link #onStartTemporaryDetach} when the container is done
10526     * changing the view.
10527     */
10528    public void onFinishTemporaryDetach() {
10529    }
10530
10531    /**
10532     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
10533     * for this view's window.  Returns null if the view is not currently attached
10534     * to the window.  Normally you will not need to use this directly, but
10535     * just use the standard high-level event callbacks like
10536     * {@link #onKeyDown(int, KeyEvent)}.
10537     */
10538    public KeyEvent.DispatcherState getKeyDispatcherState() {
10539        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
10540    }
10541
10542    /**
10543     * Dispatch a key event before it is processed by any input method
10544     * associated with the view hierarchy.  This can be used to intercept
10545     * key events in special situations before the IME consumes them; a
10546     * typical example would be handling the BACK key to update the application's
10547     * UI instead of allowing the IME to see it and close itself.
10548     *
10549     * @param event The key event to be dispatched.
10550     * @return True if the event was handled, false otherwise.
10551     */
10552    public boolean dispatchKeyEventPreIme(KeyEvent event) {
10553        return onKeyPreIme(event.getKeyCode(), event);
10554    }
10555
10556    /**
10557     * Dispatch a key event to the next view on the focus path. This path runs
10558     * from the top of the view tree down to the currently focused view. If this
10559     * view has focus, it will dispatch to itself. Otherwise it will dispatch
10560     * the next node down the focus path. This method also fires any key
10561     * listeners.
10562     *
10563     * @param event The key event to be dispatched.
10564     * @return True if the event was handled, false otherwise.
10565     */
10566    public boolean dispatchKeyEvent(KeyEvent event) {
10567        if (mInputEventConsistencyVerifier != null) {
10568            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
10569        }
10570
10571        // Give any attached key listener a first crack at the event.
10572        //noinspection SimplifiableIfStatement
10573        ListenerInfo li = mListenerInfo;
10574        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10575                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
10576            return true;
10577        }
10578
10579        if (event.dispatch(this, mAttachInfo != null
10580                ? mAttachInfo.mKeyDispatchState : null, this)) {
10581            return true;
10582        }
10583
10584        if (mInputEventConsistencyVerifier != null) {
10585            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10586        }
10587        return false;
10588    }
10589
10590    /**
10591     * Dispatches a key shortcut event.
10592     *
10593     * @param event The key event to be dispatched.
10594     * @return True if the event was handled by the view, false otherwise.
10595     */
10596    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
10597        return onKeyShortcut(event.getKeyCode(), event);
10598    }
10599
10600    /**
10601     * Pass the touch screen motion event down to the target view, or this
10602     * view if it is the target.
10603     *
10604     * @param event The motion event to be dispatched.
10605     * @return True if the event was handled by the view, false otherwise.
10606     */
10607    public boolean dispatchTouchEvent(MotionEvent event) {
10608        // If the event should be handled by accessibility focus first.
10609        if (event.isTargetAccessibilityFocus()) {
10610            // We don't have focus or no virtual descendant has it, do not handle the event.
10611            if (!isAccessibilityFocusedViewOrHost()) {
10612                return false;
10613            }
10614            // We have focus and got the event, then use normal event dispatch.
10615            event.setTargetAccessibilityFocus(false);
10616        }
10617
10618        boolean result = false;
10619
10620        if (mInputEventConsistencyVerifier != null) {
10621            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
10622        }
10623
10624        final int actionMasked = event.getActionMasked();
10625        if (actionMasked == MotionEvent.ACTION_DOWN) {
10626            // Defensive cleanup for new gesture
10627            stopNestedScroll();
10628        }
10629
10630        if (onFilterTouchEventForSecurity(event)) {
10631            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10632                result = true;
10633            }
10634            //noinspection SimplifiableIfStatement
10635            ListenerInfo li = mListenerInfo;
10636            if (li != null && li.mOnTouchListener != null
10637                    && (mViewFlags & ENABLED_MASK) == ENABLED
10638                    && li.mOnTouchListener.onTouch(this, event)) {
10639                result = true;
10640            }
10641
10642            if (!result && onTouchEvent(event)) {
10643                result = true;
10644            }
10645        }
10646
10647        if (!result && mInputEventConsistencyVerifier != null) {
10648            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10649        }
10650
10651        // Clean up after nested scrolls if this is the end of a gesture;
10652        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10653        // of the gesture.
10654        if (actionMasked == MotionEvent.ACTION_UP ||
10655                actionMasked == MotionEvent.ACTION_CANCEL ||
10656                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10657            stopNestedScroll();
10658        }
10659
10660        return result;
10661    }
10662
10663    boolean isAccessibilityFocusedViewOrHost() {
10664        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10665                .getAccessibilityFocusedHost() == this);
10666    }
10667
10668    /**
10669     * Filter the touch event to apply security policies.
10670     *
10671     * @param event The motion event to be filtered.
10672     * @return True if the event should be dispatched, false if the event should be dropped.
10673     *
10674     * @see #getFilterTouchesWhenObscured
10675     */
10676    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10677        //noinspection RedundantIfStatement
10678        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10679                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10680            // Window is obscured, drop this touch.
10681            return false;
10682        }
10683        return true;
10684    }
10685
10686    /**
10687     * Pass a trackball motion event down to the focused view.
10688     *
10689     * @param event The motion event to be dispatched.
10690     * @return True if the event was handled by the view, false otherwise.
10691     */
10692    public boolean dispatchTrackballEvent(MotionEvent event) {
10693        if (mInputEventConsistencyVerifier != null) {
10694            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10695        }
10696
10697        return onTrackballEvent(event);
10698    }
10699
10700    /**
10701     * Dispatch a generic motion event.
10702     * <p>
10703     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10704     * are delivered to the view under the pointer.  All other generic motion events are
10705     * delivered to the focused view.  Hover events are handled specially and are delivered
10706     * to {@link #onHoverEvent(MotionEvent)}.
10707     * </p>
10708     *
10709     * @param event The motion event to be dispatched.
10710     * @return True if the event was handled by the view, false otherwise.
10711     */
10712    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10713        if (mInputEventConsistencyVerifier != null) {
10714            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10715        }
10716
10717        final int source = event.getSource();
10718        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10719            final int action = event.getAction();
10720            if (action == MotionEvent.ACTION_HOVER_ENTER
10721                    || action == MotionEvent.ACTION_HOVER_MOVE
10722                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10723                if (dispatchHoverEvent(event)) {
10724                    return true;
10725                }
10726            } else if (dispatchGenericPointerEvent(event)) {
10727                return true;
10728            }
10729        } else if (dispatchGenericFocusedEvent(event)) {
10730            return true;
10731        }
10732
10733        if (dispatchGenericMotionEventInternal(event)) {
10734            return true;
10735        }
10736
10737        if (mInputEventConsistencyVerifier != null) {
10738            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10739        }
10740        return false;
10741    }
10742
10743    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10744        //noinspection SimplifiableIfStatement
10745        ListenerInfo li = mListenerInfo;
10746        if (li != null && li.mOnGenericMotionListener != null
10747                && (mViewFlags & ENABLED_MASK) == ENABLED
10748                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10749            return true;
10750        }
10751
10752        if (onGenericMotionEvent(event)) {
10753            return true;
10754        }
10755
10756        final int actionButton = event.getActionButton();
10757        switch (event.getActionMasked()) {
10758            case MotionEvent.ACTION_BUTTON_PRESS:
10759                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10760                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10761                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10762                    if (performContextClick(event.getX(), event.getY())) {
10763                        mInContextButtonPress = true;
10764                        setPressed(true, event.getX(), event.getY());
10765                        removeTapCallback();
10766                        removeLongPressCallback();
10767                        return true;
10768                    }
10769                }
10770                break;
10771
10772            case MotionEvent.ACTION_BUTTON_RELEASE:
10773                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10774                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10775                    mInContextButtonPress = false;
10776                    mIgnoreNextUpEvent = true;
10777                }
10778                break;
10779        }
10780
10781        if (mInputEventConsistencyVerifier != null) {
10782            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10783        }
10784        return false;
10785    }
10786
10787    /**
10788     * Dispatch a hover event.
10789     * <p>
10790     * Do not call this method directly.
10791     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10792     * </p>
10793     *
10794     * @param event The motion event to be dispatched.
10795     * @return True if the event was handled by the view, false otherwise.
10796     */
10797    protected boolean dispatchHoverEvent(MotionEvent event) {
10798        ListenerInfo li = mListenerInfo;
10799        //noinspection SimplifiableIfStatement
10800        if (li != null && li.mOnHoverListener != null
10801                && (mViewFlags & ENABLED_MASK) == ENABLED
10802                && li.mOnHoverListener.onHover(this, event)) {
10803            return true;
10804        }
10805
10806        return onHoverEvent(event);
10807    }
10808
10809    /**
10810     * Returns true if the view has a child to which it has recently sent
10811     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10812     * it does not have a hovered child, then it must be the innermost hovered view.
10813     * @hide
10814     */
10815    protected boolean hasHoveredChild() {
10816        return false;
10817    }
10818
10819    /**
10820     * Dispatch a generic motion event to the view under the first pointer.
10821     * <p>
10822     * Do not call this method directly.
10823     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10824     * </p>
10825     *
10826     * @param event The motion event to be dispatched.
10827     * @return True if the event was handled by the view, false otherwise.
10828     */
10829    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10830        return false;
10831    }
10832
10833    /**
10834     * Dispatch a generic motion event to the currently focused view.
10835     * <p>
10836     * Do not call this method directly.
10837     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10838     * </p>
10839     *
10840     * @param event The motion event to be dispatched.
10841     * @return True if the event was handled by the view, false otherwise.
10842     */
10843    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10844        return false;
10845    }
10846
10847    /**
10848     * Dispatch a pointer event.
10849     * <p>
10850     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10851     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10852     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10853     * and should not be expected to handle other pointing device features.
10854     * </p>
10855     *
10856     * @param event The motion event to be dispatched.
10857     * @return True if the event was handled by the view, false otherwise.
10858     * @hide
10859     */
10860    public final boolean dispatchPointerEvent(MotionEvent event) {
10861        if (event.isTouchEvent()) {
10862            return dispatchTouchEvent(event);
10863        } else {
10864            return dispatchGenericMotionEvent(event);
10865        }
10866    }
10867
10868    /**
10869     * Called when the window containing this view gains or loses window focus.
10870     * ViewGroups should override to route to their children.
10871     *
10872     * @param hasFocus True if the window containing this view now has focus,
10873     *        false otherwise.
10874     */
10875    public void dispatchWindowFocusChanged(boolean hasFocus) {
10876        onWindowFocusChanged(hasFocus);
10877    }
10878
10879    /**
10880     * Called when the window containing this view gains or loses focus.  Note
10881     * that this is separate from view focus: to receive key events, both
10882     * your view and its window must have focus.  If a window is displayed
10883     * on top of yours that takes input focus, then your own window will lose
10884     * focus but the view focus will remain unchanged.
10885     *
10886     * @param hasWindowFocus True if the window containing this view now has
10887     *        focus, false otherwise.
10888     */
10889    public void onWindowFocusChanged(boolean hasWindowFocus) {
10890        InputMethodManager imm = InputMethodManager.peekInstance();
10891        if (!hasWindowFocus) {
10892            if (isPressed()) {
10893                setPressed(false);
10894            }
10895            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
10896            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10897                imm.focusOut(this);
10898            }
10899            removeLongPressCallback();
10900            removeTapCallback();
10901            onFocusLost();
10902        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10903            imm.focusIn(this);
10904        }
10905        refreshDrawableState();
10906    }
10907
10908    /**
10909     * Returns true if this view is in a window that currently has window focus.
10910     * Note that this is not the same as the view itself having focus.
10911     *
10912     * @return True if this view is in a window that currently has window focus.
10913     */
10914    public boolean hasWindowFocus() {
10915        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10916    }
10917
10918    /**
10919     * Dispatch a view visibility change down the view hierarchy.
10920     * ViewGroups should override to route to their children.
10921     * @param changedView The view whose visibility changed. Could be 'this' or
10922     * an ancestor view.
10923     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10924     * {@link #INVISIBLE} or {@link #GONE}.
10925     */
10926    protected void dispatchVisibilityChanged(@NonNull View changedView,
10927            @Visibility int visibility) {
10928        onVisibilityChanged(changedView, visibility);
10929    }
10930
10931    /**
10932     * Called when the visibility of the view or an ancestor of the view has
10933     * changed.
10934     *
10935     * @param changedView The view whose visibility changed. May be
10936     *                    {@code this} or an ancestor view.
10937     * @param visibility The new visibility, one of {@link #VISIBLE},
10938     *                   {@link #INVISIBLE} or {@link #GONE}.
10939     */
10940    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10941    }
10942
10943    /**
10944     * Dispatch a hint about whether this view is displayed. For instance, when
10945     * a View moves out of the screen, it might receives a display hint indicating
10946     * the view is not displayed. Applications should not <em>rely</em> on this hint
10947     * as there is no guarantee that they will receive one.
10948     *
10949     * @param hint A hint about whether or not this view is displayed:
10950     * {@link #VISIBLE} or {@link #INVISIBLE}.
10951     */
10952    public void dispatchDisplayHint(@Visibility int hint) {
10953        onDisplayHint(hint);
10954    }
10955
10956    /**
10957     * Gives this view a hint about whether is displayed or not. For instance, when
10958     * a View moves out of the screen, it might receives a display hint indicating
10959     * the view is not displayed. Applications should not <em>rely</em> on this hint
10960     * as there is no guarantee that they will receive one.
10961     *
10962     * @param hint A hint about whether or not this view is displayed:
10963     * {@link #VISIBLE} or {@link #INVISIBLE}.
10964     */
10965    protected void onDisplayHint(@Visibility int hint) {
10966    }
10967
10968    /**
10969     * Dispatch a window visibility change down the view hierarchy.
10970     * ViewGroups should override to route to their children.
10971     *
10972     * @param visibility The new visibility of the window.
10973     *
10974     * @see #onWindowVisibilityChanged(int)
10975     */
10976    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10977        onWindowVisibilityChanged(visibility);
10978    }
10979
10980    /**
10981     * Called when the window containing has change its visibility
10982     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10983     * that this tells you whether or not your window is being made visible
10984     * to the window manager; this does <em>not</em> tell you whether or not
10985     * your window is obscured by other windows on the screen, even if it
10986     * is itself visible.
10987     *
10988     * @param visibility The new visibility of the window.
10989     */
10990    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10991        if (visibility == VISIBLE) {
10992            initialAwakenScrollBars();
10993        }
10994    }
10995
10996    /**
10997     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10998     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10999     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
11000     *
11001     * @param isVisible true if this view's visibility to the user is uninterrupted by its
11002     *                  ancestors or by window visibility
11003     * @return true if this view is visible to the user, not counting clipping or overlapping
11004     */
11005    boolean dispatchVisibilityAggregated(boolean isVisible) {
11006        final boolean thisVisible = getVisibility() == VISIBLE;
11007        // If we're not visible but something is telling us we are, ignore it.
11008        if (thisVisible || !isVisible) {
11009            onVisibilityAggregated(isVisible);
11010        }
11011        return thisVisible && isVisible;
11012    }
11013
11014    /**
11015     * Called when the user-visibility of this View is potentially affected by a change
11016     * to this view itself, an ancestor view or the window this view is attached to.
11017     *
11018     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
11019     *                  and this view's window is also visible
11020     */
11021    @CallSuper
11022    public void onVisibilityAggregated(boolean isVisible) {
11023        if (isVisible && mAttachInfo != null) {
11024            initialAwakenScrollBars();
11025        }
11026
11027        final Drawable dr = mBackground;
11028        if (dr != null && isVisible != dr.isVisible()) {
11029            dr.setVisible(isVisible, false);
11030        }
11031        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
11032        if (fg != null && isVisible != fg.isVisible()) {
11033            fg.setVisible(isVisible, false);
11034        }
11035    }
11036
11037    /**
11038     * Returns the current visibility of the window this view is attached to
11039     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
11040     *
11041     * @return Returns the current visibility of the view's window.
11042     */
11043    @Visibility
11044    public int getWindowVisibility() {
11045        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
11046    }
11047
11048    /**
11049     * Retrieve the overall visible display size in which the window this view is
11050     * attached to has been positioned in.  This takes into account screen
11051     * decorations above the window, for both cases where the window itself
11052     * is being position inside of them or the window is being placed under
11053     * then and covered insets are used for the window to position its content
11054     * inside.  In effect, this tells you the available area where content can
11055     * be placed and remain visible to users.
11056     *
11057     * <p>This function requires an IPC back to the window manager to retrieve
11058     * the requested information, so should not be used in performance critical
11059     * code like drawing.
11060     *
11061     * @param outRect Filled in with the visible display frame.  If the view
11062     * is not attached to a window, this is simply the raw display size.
11063     */
11064    public void getWindowVisibleDisplayFrame(Rect outRect) {
11065        if (mAttachInfo != null) {
11066            try {
11067                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11068            } catch (RemoteException e) {
11069                return;
11070            }
11071            // XXX This is really broken, and probably all needs to be done
11072            // in the window manager, and we need to know more about whether
11073            // we want the area behind or in front of the IME.
11074            final Rect insets = mAttachInfo.mVisibleInsets;
11075            outRect.left += insets.left;
11076            outRect.top += insets.top;
11077            outRect.right -= insets.right;
11078            outRect.bottom -= insets.bottom;
11079            return;
11080        }
11081        // The view is not attached to a display so we don't have a context.
11082        // Make a best guess about the display size.
11083        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11084        d.getRectSize(outRect);
11085    }
11086
11087    /**
11088     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
11089     * is currently in without any insets.
11090     *
11091     * @hide
11092     */
11093    public void getWindowDisplayFrame(Rect outRect) {
11094        if (mAttachInfo != null) {
11095            try {
11096                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11097            } catch (RemoteException e) {
11098                return;
11099            }
11100            return;
11101        }
11102        // The view is not attached to a display so we don't have a context.
11103        // Make a best guess about the display size.
11104        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11105        d.getRectSize(outRect);
11106    }
11107
11108    /**
11109     * Dispatch a notification about a resource configuration change down
11110     * the view hierarchy.
11111     * ViewGroups should override to route to their children.
11112     *
11113     * @param newConfig The new resource configuration.
11114     *
11115     * @see #onConfigurationChanged(android.content.res.Configuration)
11116     */
11117    public void dispatchConfigurationChanged(Configuration newConfig) {
11118        onConfigurationChanged(newConfig);
11119    }
11120
11121    /**
11122     * Called when the current configuration of the resources being used
11123     * by the application have changed.  You can use this to decide when
11124     * to reload resources that can changed based on orientation and other
11125     * configuration characteristics.  You only need to use this if you are
11126     * not relying on the normal {@link android.app.Activity} mechanism of
11127     * recreating the activity instance upon a configuration change.
11128     *
11129     * @param newConfig The new resource configuration.
11130     */
11131    protected void onConfigurationChanged(Configuration newConfig) {
11132    }
11133
11134    /**
11135     * Private function to aggregate all per-view attributes in to the view
11136     * root.
11137     */
11138    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11139        performCollectViewAttributes(attachInfo, visibility);
11140    }
11141
11142    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11143        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
11144            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
11145                attachInfo.mKeepScreenOn = true;
11146            }
11147            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
11148            ListenerInfo li = mListenerInfo;
11149            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
11150                attachInfo.mHasSystemUiListeners = true;
11151            }
11152        }
11153    }
11154
11155    void needGlobalAttributesUpdate(boolean force) {
11156        final AttachInfo ai = mAttachInfo;
11157        if (ai != null && !ai.mRecomputeGlobalAttributes) {
11158            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
11159                    || ai.mHasSystemUiListeners) {
11160                ai.mRecomputeGlobalAttributes = true;
11161            }
11162        }
11163    }
11164
11165    /**
11166     * Returns whether the device is currently in touch mode.  Touch mode is entered
11167     * once the user begins interacting with the device by touch, and affects various
11168     * things like whether focus is always visible to the user.
11169     *
11170     * @return Whether the device is in touch mode.
11171     */
11172    @ViewDebug.ExportedProperty
11173    public boolean isInTouchMode() {
11174        if (mAttachInfo != null) {
11175            return mAttachInfo.mInTouchMode;
11176        } else {
11177            return ViewRootImpl.isInTouchMode();
11178        }
11179    }
11180
11181    /**
11182     * Returns the context the view is running in, through which it can
11183     * access the current theme, resources, etc.
11184     *
11185     * @return The view's Context.
11186     */
11187    @ViewDebug.CapturedViewProperty
11188    public final Context getContext() {
11189        return mContext;
11190    }
11191
11192    /**
11193     * Handle a key event before it is processed by any input method
11194     * associated with the view hierarchy.  This can be used to intercept
11195     * key events in special situations before the IME consumes them; a
11196     * typical example would be handling the BACK key to update the application's
11197     * UI instead of allowing the IME to see it and close itself.
11198     *
11199     * @param keyCode The value in event.getKeyCode().
11200     * @param event Description of the key event.
11201     * @return If you handled the event, return true. If you want to allow the
11202     *         event to be handled by the next receiver, return false.
11203     */
11204    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
11205        return false;
11206    }
11207
11208    /**
11209     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
11210     * KeyEvent.Callback.onKeyDown()}: perform press of the view
11211     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
11212     * is released, if the view is enabled and clickable.
11213     * <p>
11214     * Key presses in software keyboards will generally NOT trigger this
11215     * listener, although some may elect to do so in some situations. Do not
11216     * rely on this to catch software key presses.
11217     *
11218     * @param keyCode a key code that represents the button pressed, from
11219     *                {@link android.view.KeyEvent}
11220     * @param event the KeyEvent object that defines the button action
11221     */
11222    public boolean onKeyDown(int keyCode, KeyEvent event) {
11223        if (KeyEvent.isConfirmKey(keyCode)) {
11224            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11225                return true;
11226            }
11227
11228            if (event.getRepeatCount() == 0) {
11229                // Long clickable items don't necessarily have to be clickable.
11230                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
11231                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
11232                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
11233                    // For the purposes of menu anchoring and drawable hotspots,
11234                    // key events are considered to be at the center of the view.
11235                    final float x = getWidth() / 2f;
11236                    final float y = getHeight() / 2f;
11237                    if (clickable) {
11238                        setPressed(true, x, y);
11239                    }
11240                    checkForLongClick(0, x, y);
11241                    return true;
11242                }
11243            }
11244        }
11245
11246        return false;
11247    }
11248
11249    /**
11250     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
11251     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
11252     * the event).
11253     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11254     * although some may elect to do so in some situations. Do not rely on this to
11255     * catch software key presses.
11256     */
11257    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
11258        return false;
11259    }
11260
11261    /**
11262     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
11263     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
11264     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
11265     * or {@link KeyEvent#KEYCODE_SPACE} is released.
11266     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11267     * although some may elect to do so in some situations. Do not rely on this to
11268     * catch software key presses.
11269     *
11270     * @param keyCode A key code that represents the button pressed, from
11271     *                {@link android.view.KeyEvent}.
11272     * @param event   The KeyEvent object that defines the button action.
11273     */
11274    public boolean onKeyUp(int keyCode, KeyEvent event) {
11275        if (KeyEvent.isConfirmKey(keyCode)) {
11276            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11277                return true;
11278            }
11279            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
11280                setPressed(false);
11281
11282                if (!mHasPerformedLongPress) {
11283                    // This is a tap, so remove the longpress check
11284                    removeLongPressCallback();
11285                    return performClick();
11286                }
11287            }
11288        }
11289        return false;
11290    }
11291
11292    /**
11293     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
11294     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
11295     * the event).
11296     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11297     * although some may elect to do so in some situations. Do not rely on this to
11298     * catch software key presses.
11299     *
11300     * @param keyCode     A key code that represents the button pressed, from
11301     *                    {@link android.view.KeyEvent}.
11302     * @param repeatCount The number of times the action was made.
11303     * @param event       The KeyEvent object that defines the button action.
11304     */
11305    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
11306        return false;
11307    }
11308
11309    /**
11310     * Called on the focused view when a key shortcut event is not handled.
11311     * Override this method to implement local key shortcuts for the View.
11312     * Key shortcuts can also be implemented by setting the
11313     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
11314     *
11315     * @param keyCode The value in event.getKeyCode().
11316     * @param event Description of the key event.
11317     * @return If you handled the event, return true. If you want to allow the
11318     *         event to be handled by the next receiver, return false.
11319     */
11320    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
11321        return false;
11322    }
11323
11324    /**
11325     * Check whether the called view is a text editor, in which case it
11326     * would make sense to automatically display a soft input window for
11327     * it.  Subclasses should override this if they implement
11328     * {@link #onCreateInputConnection(EditorInfo)} to return true if
11329     * a call on that method would return a non-null InputConnection, and
11330     * they are really a first-class editor that the user would normally
11331     * start typing on when the go into a window containing your view.
11332     *
11333     * <p>The default implementation always returns false.  This does
11334     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
11335     * will not be called or the user can not otherwise perform edits on your
11336     * view; it is just a hint to the system that this is not the primary
11337     * purpose of this view.
11338     *
11339     * @return Returns true if this view is a text editor, else false.
11340     */
11341    public boolean onCheckIsTextEditor() {
11342        return false;
11343    }
11344
11345    /**
11346     * Create a new InputConnection for an InputMethod to interact
11347     * with the view.  The default implementation returns null, since it doesn't
11348     * support input methods.  You can override this to implement such support.
11349     * This is only needed for views that take focus and text input.
11350     *
11351     * <p>When implementing this, you probably also want to implement
11352     * {@link #onCheckIsTextEditor()} to indicate you will return a
11353     * non-null InputConnection.</p>
11354     *
11355     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
11356     * object correctly and in its entirety, so that the connected IME can rely
11357     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
11358     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
11359     * must be filled in with the correct cursor position for IMEs to work correctly
11360     * with your application.</p>
11361     *
11362     * @param outAttrs Fill in with attribute information about the connection.
11363     */
11364    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
11365        return null;
11366    }
11367
11368    /**
11369     * Called by the {@link android.view.inputmethod.InputMethodManager}
11370     * when a view who is not the current
11371     * input connection target is trying to make a call on the manager.  The
11372     * default implementation returns false; you can override this to return
11373     * true for certain views if you are performing InputConnection proxying
11374     * to them.
11375     * @param view The View that is making the InputMethodManager call.
11376     * @return Return true to allow the call, false to reject.
11377     */
11378    public boolean checkInputConnectionProxy(View view) {
11379        return false;
11380    }
11381
11382    /**
11383     * Show the context menu for this view. It is not safe to hold on to the
11384     * menu after returning from this method.
11385     *
11386     * You should normally not overload this method. Overload
11387     * {@link #onCreateContextMenu(ContextMenu)} or define an
11388     * {@link OnCreateContextMenuListener} to add items to the context menu.
11389     *
11390     * @param menu The context menu to populate
11391     */
11392    public void createContextMenu(ContextMenu menu) {
11393        ContextMenuInfo menuInfo = getContextMenuInfo();
11394
11395        // Sets the current menu info so all items added to menu will have
11396        // my extra info set.
11397        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
11398
11399        onCreateContextMenu(menu);
11400        ListenerInfo li = mListenerInfo;
11401        if (li != null && li.mOnCreateContextMenuListener != null) {
11402            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
11403        }
11404
11405        // Clear the extra information so subsequent items that aren't mine don't
11406        // have my extra info.
11407        ((MenuBuilder)menu).setCurrentMenuInfo(null);
11408
11409        if (mParent != null) {
11410            mParent.createContextMenu(menu);
11411        }
11412    }
11413
11414    /**
11415     * Views should implement this if they have extra information to associate
11416     * with the context menu. The return result is supplied as a parameter to
11417     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
11418     * callback.
11419     *
11420     * @return Extra information about the item for which the context menu
11421     *         should be shown. This information will vary across different
11422     *         subclasses of View.
11423     */
11424    protected ContextMenuInfo getContextMenuInfo() {
11425        return null;
11426    }
11427
11428    /**
11429     * Views should implement this if the view itself is going to add items to
11430     * the context menu.
11431     *
11432     * @param menu the context menu to populate
11433     */
11434    protected void onCreateContextMenu(ContextMenu menu) {
11435    }
11436
11437    /**
11438     * Implement this method to handle trackball motion events.  The
11439     * <em>relative</em> movement of the trackball since the last event
11440     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
11441     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
11442     * that a movement of 1 corresponds to the user pressing one DPAD key (so
11443     * they will often be fractional values, representing the more fine-grained
11444     * movement information available from a trackball).
11445     *
11446     * @param event The motion event.
11447     * @return True if the event was handled, false otherwise.
11448     */
11449    public boolean onTrackballEvent(MotionEvent event) {
11450        return false;
11451    }
11452
11453    /**
11454     * Implement this method to handle generic motion events.
11455     * <p>
11456     * Generic motion events describe joystick movements, mouse hovers, track pad
11457     * touches, scroll wheel movements and other input events.  The
11458     * {@link MotionEvent#getSource() source} of the motion event specifies
11459     * the class of input that was received.  Implementations of this method
11460     * must examine the bits in the source before processing the event.
11461     * The following code example shows how this is done.
11462     * </p><p>
11463     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11464     * are delivered to the view under the pointer.  All other generic motion events are
11465     * delivered to the focused view.
11466     * </p>
11467     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
11468     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
11469     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
11470     *             // process the joystick movement...
11471     *             return true;
11472     *         }
11473     *     }
11474     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
11475     *         switch (event.getAction()) {
11476     *             case MotionEvent.ACTION_HOVER_MOVE:
11477     *                 // process the mouse hover movement...
11478     *                 return true;
11479     *             case MotionEvent.ACTION_SCROLL:
11480     *                 // process the scroll wheel movement...
11481     *                 return true;
11482     *         }
11483     *     }
11484     *     return super.onGenericMotionEvent(event);
11485     * }</pre>
11486     *
11487     * @param event The generic motion event being processed.
11488     * @return True if the event was handled, false otherwise.
11489     */
11490    public boolean onGenericMotionEvent(MotionEvent event) {
11491        return false;
11492    }
11493
11494    /**
11495     * Implement this method to handle hover events.
11496     * <p>
11497     * This method is called whenever a pointer is hovering into, over, or out of the
11498     * bounds of a view and the view is not currently being touched.
11499     * Hover events are represented as pointer events with action
11500     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
11501     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
11502     * </p>
11503     * <ul>
11504     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
11505     * when the pointer enters the bounds of the view.</li>
11506     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
11507     * when the pointer has already entered the bounds of the view and has moved.</li>
11508     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
11509     * when the pointer has exited the bounds of the view or when the pointer is
11510     * about to go down due to a button click, tap, or similar user action that
11511     * causes the view to be touched.</li>
11512     * </ul>
11513     * <p>
11514     * The view should implement this method to return true to indicate that it is
11515     * handling the hover event, such as by changing its drawable state.
11516     * </p><p>
11517     * The default implementation calls {@link #setHovered} to update the hovered state
11518     * of the view when a hover enter or hover exit event is received, if the view
11519     * is enabled and is clickable.  The default implementation also sends hover
11520     * accessibility events.
11521     * </p>
11522     *
11523     * @param event The motion event that describes the hover.
11524     * @return True if the view handled the hover event.
11525     *
11526     * @see #isHovered
11527     * @see #setHovered
11528     * @see #onHoverChanged
11529     */
11530    public boolean onHoverEvent(MotionEvent event) {
11531        // The root view may receive hover (or touch) events that are outside the bounds of
11532        // the window.  This code ensures that we only send accessibility events for
11533        // hovers that are actually within the bounds of the root view.
11534        final int action = event.getActionMasked();
11535        if (!mSendingHoverAccessibilityEvents) {
11536            if ((action == MotionEvent.ACTION_HOVER_ENTER
11537                    || action == MotionEvent.ACTION_HOVER_MOVE)
11538                    && !hasHoveredChild()
11539                    && pointInView(event.getX(), event.getY())) {
11540                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
11541                mSendingHoverAccessibilityEvents = true;
11542            }
11543        } else {
11544            if (action == MotionEvent.ACTION_HOVER_EXIT
11545                    || (action == MotionEvent.ACTION_MOVE
11546                            && !pointInView(event.getX(), event.getY()))) {
11547                mSendingHoverAccessibilityEvents = false;
11548                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
11549            }
11550        }
11551
11552        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
11553                && event.isFromSource(InputDevice.SOURCE_MOUSE)
11554                && isOnScrollbar(event.getX(), event.getY())) {
11555            awakenScrollBars();
11556        }
11557        if (isHoverable()) {
11558            switch (action) {
11559                case MotionEvent.ACTION_HOVER_ENTER:
11560                    setHovered(true);
11561                    break;
11562                case MotionEvent.ACTION_HOVER_EXIT:
11563                    setHovered(false);
11564                    break;
11565            }
11566
11567            // Dispatch the event to onGenericMotionEvent before returning true.
11568            // This is to provide compatibility with existing applications that
11569            // handled HOVER_MOVE events in onGenericMotionEvent and that would
11570            // break because of the new default handling for hoverable views
11571            // in onHoverEvent.
11572            // Note that onGenericMotionEvent will be called by default when
11573            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
11574            dispatchGenericMotionEventInternal(event);
11575            // The event was already handled by calling setHovered(), so always
11576            // return true.
11577            return true;
11578        }
11579
11580        return false;
11581    }
11582
11583    /**
11584     * Returns true if the view should handle {@link #onHoverEvent}
11585     * by calling {@link #setHovered} to change its hovered state.
11586     *
11587     * @return True if the view is hoverable.
11588     */
11589    private boolean isHoverable() {
11590        final int viewFlags = mViewFlags;
11591        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11592            return false;
11593        }
11594
11595        return (viewFlags & CLICKABLE) == CLICKABLE
11596                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
11597                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11598    }
11599
11600    /**
11601     * Returns true if the view is currently hovered.
11602     *
11603     * @return True if the view is currently hovered.
11604     *
11605     * @see #setHovered
11606     * @see #onHoverChanged
11607     */
11608    @ViewDebug.ExportedProperty
11609    public boolean isHovered() {
11610        return (mPrivateFlags & PFLAG_HOVERED) != 0;
11611    }
11612
11613    /**
11614     * Sets whether the view is currently hovered.
11615     * <p>
11616     * Calling this method also changes the drawable state of the view.  This
11617     * enables the view to react to hover by using different drawable resources
11618     * to change its appearance.
11619     * </p><p>
11620     * The {@link #onHoverChanged} method is called when the hovered state changes.
11621     * </p>
11622     *
11623     * @param hovered True if the view is hovered.
11624     *
11625     * @see #isHovered
11626     * @see #onHoverChanged
11627     */
11628    public void setHovered(boolean hovered) {
11629        if (hovered) {
11630            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11631                mPrivateFlags |= PFLAG_HOVERED;
11632                refreshDrawableState();
11633                onHoverChanged(true);
11634            }
11635        } else {
11636            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11637                mPrivateFlags &= ~PFLAG_HOVERED;
11638                refreshDrawableState();
11639                onHoverChanged(false);
11640            }
11641        }
11642    }
11643
11644    /**
11645     * Implement this method to handle hover state changes.
11646     * <p>
11647     * This method is called whenever the hover state changes as a result of a
11648     * call to {@link #setHovered}.
11649     * </p>
11650     *
11651     * @param hovered The current hover state, as returned by {@link #isHovered}.
11652     *
11653     * @see #isHovered
11654     * @see #setHovered
11655     */
11656    public void onHoverChanged(boolean hovered) {
11657    }
11658
11659    /**
11660     * Handles scroll bar dragging by mouse input.
11661     *
11662     * @hide
11663     * @param event The motion event.
11664     *
11665     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11666     */
11667    protected boolean handleScrollBarDragging(MotionEvent event) {
11668        if (mScrollCache == null) {
11669            return false;
11670        }
11671        final float x = event.getX();
11672        final float y = event.getY();
11673        final int action = event.getAction();
11674        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11675                && action != MotionEvent.ACTION_DOWN)
11676                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11677                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11678            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11679            return false;
11680        }
11681
11682        switch (action) {
11683            case MotionEvent.ACTION_MOVE:
11684                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11685                    return false;
11686                }
11687                if (mScrollCache.mScrollBarDraggingState
11688                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11689                    final Rect bounds = mScrollCache.mScrollBarBounds;
11690                    getVerticalScrollBarBounds(bounds);
11691                    final int range = computeVerticalScrollRange();
11692                    final int offset = computeVerticalScrollOffset();
11693                    final int extent = computeVerticalScrollExtent();
11694
11695                    final int thumbLength = ScrollBarUtils.getThumbLength(
11696                            bounds.height(), bounds.width(), extent, range);
11697                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11698                            bounds.height(), thumbLength, extent, range, offset);
11699
11700                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11701                    final float maxThumbOffset = bounds.height() - thumbLength;
11702                    final float newThumbOffset =
11703                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11704                    final int height = getHeight();
11705                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11706                            && height > 0 && extent > 0) {
11707                        final int newY = Math.round((range - extent)
11708                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11709                        if (newY != getScrollY()) {
11710                            mScrollCache.mScrollBarDraggingPos = y;
11711                            setScrollY(newY);
11712                        }
11713                    }
11714                    return true;
11715                }
11716                if (mScrollCache.mScrollBarDraggingState
11717                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11718                    final Rect bounds = mScrollCache.mScrollBarBounds;
11719                    getHorizontalScrollBarBounds(bounds);
11720                    final int range = computeHorizontalScrollRange();
11721                    final int offset = computeHorizontalScrollOffset();
11722                    final int extent = computeHorizontalScrollExtent();
11723
11724                    final int thumbLength = ScrollBarUtils.getThumbLength(
11725                            bounds.width(), bounds.height(), extent, range);
11726                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11727                            bounds.width(), thumbLength, extent, range, offset);
11728
11729                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11730                    final float maxThumbOffset = bounds.width() - thumbLength;
11731                    final float newThumbOffset =
11732                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11733                    final int width = getWidth();
11734                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11735                            && width > 0 && extent > 0) {
11736                        final int newX = Math.round((range - extent)
11737                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11738                        if (newX != getScrollX()) {
11739                            mScrollCache.mScrollBarDraggingPos = x;
11740                            setScrollX(newX);
11741                        }
11742                    }
11743                    return true;
11744                }
11745            case MotionEvent.ACTION_DOWN:
11746                if (mScrollCache.state == ScrollabilityCache.OFF) {
11747                    return false;
11748                }
11749                if (isOnVerticalScrollbarThumb(x, y)) {
11750                    mScrollCache.mScrollBarDraggingState =
11751                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11752                    mScrollCache.mScrollBarDraggingPos = y;
11753                    return true;
11754                }
11755                if (isOnHorizontalScrollbarThumb(x, y)) {
11756                    mScrollCache.mScrollBarDraggingState =
11757                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11758                    mScrollCache.mScrollBarDraggingPos = x;
11759                    return true;
11760                }
11761        }
11762        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11763        return false;
11764    }
11765
11766    /**
11767     * Implement this method to handle touch screen motion events.
11768     * <p>
11769     * If this method is used to detect click actions, it is recommended that
11770     * the actions be performed by implementing and calling
11771     * {@link #performClick()}. This will ensure consistent system behavior,
11772     * including:
11773     * <ul>
11774     * <li>obeying click sound preferences
11775     * <li>dispatching OnClickListener calls
11776     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11777     * accessibility features are enabled
11778     * </ul>
11779     *
11780     * @param event The motion event.
11781     * @return True if the event was handled, false otherwise.
11782     */
11783    public boolean onTouchEvent(MotionEvent event) {
11784        final float x = event.getX();
11785        final float y = event.getY();
11786        final int viewFlags = mViewFlags;
11787        final int action = event.getAction();
11788
11789        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
11790                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11791                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
11792
11793        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11794            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11795                setPressed(false);
11796            }
11797            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11798            // A disabled view that is clickable still consumes the touch
11799            // events, it just doesn't respond to them.
11800            return clickable;
11801        }
11802        if (mTouchDelegate != null) {
11803            if (mTouchDelegate.onTouchEvent(event)) {
11804                return true;
11805            }
11806        }
11807
11808        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
11809            switch (action) {
11810                case MotionEvent.ACTION_UP:
11811                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11812                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
11813                        handleTooltipUp();
11814                    }
11815                    if (!clickable) {
11816                        removeTapCallback();
11817                        removeLongPressCallback();
11818                        mInContextButtonPress = false;
11819                        mHasPerformedLongPress = false;
11820                        mIgnoreNextUpEvent = false;
11821                        break;
11822                    }
11823                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11824                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11825                        // take focus if we don't have it already and we should in
11826                        // touch mode.
11827                        boolean focusTaken = false;
11828                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11829                            focusTaken = requestFocus();
11830                        }
11831
11832                        if (prepressed) {
11833                            // The button is being released before we actually
11834                            // showed it as pressed.  Make it show the pressed
11835                            // state now (before scheduling the click) to ensure
11836                            // the user sees it.
11837                            setPressed(true, x, y);
11838                        }
11839
11840                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11841                            // This is a tap, so remove the longpress check
11842                            removeLongPressCallback();
11843
11844                            // Only perform take click actions if we were in the pressed state
11845                            if (!focusTaken) {
11846                                // Use a Runnable and post this rather than calling
11847                                // performClick directly. This lets other visual state
11848                                // of the view update before click actions start.
11849                                if (mPerformClick == null) {
11850                                    mPerformClick = new PerformClick();
11851                                }
11852                                if (!post(mPerformClick)) {
11853                                    performClick();
11854                                }
11855                            }
11856                        }
11857
11858                        if (mUnsetPressedState == null) {
11859                            mUnsetPressedState = new UnsetPressedState();
11860                        }
11861
11862                        if (prepressed) {
11863                            postDelayed(mUnsetPressedState,
11864                                    ViewConfiguration.getPressedStateDuration());
11865                        } else if (!post(mUnsetPressedState)) {
11866                            // If the post failed, unpress right now
11867                            mUnsetPressedState.run();
11868                        }
11869
11870                        removeTapCallback();
11871                    }
11872                    mIgnoreNextUpEvent = false;
11873                    break;
11874
11875                case MotionEvent.ACTION_DOWN:
11876                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
11877                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
11878                    }
11879                    mHasPerformedLongPress = false;
11880
11881                    if (!clickable) {
11882                        checkForLongClick(0, x, y);
11883                        break;
11884                    }
11885
11886                    if (performButtonActionOnTouchDown(event)) {
11887                        break;
11888                    }
11889
11890                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11891                    boolean isInScrollingContainer = isInScrollingContainer();
11892
11893                    // For views inside a scrolling container, delay the pressed feedback for
11894                    // a short period in case this is a scroll.
11895                    if (isInScrollingContainer) {
11896                        mPrivateFlags |= PFLAG_PREPRESSED;
11897                        if (mPendingCheckForTap == null) {
11898                            mPendingCheckForTap = new CheckForTap();
11899                        }
11900                        mPendingCheckForTap.x = event.getX();
11901                        mPendingCheckForTap.y = event.getY();
11902                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11903                    } else {
11904                        // Not inside a scrolling container, so show the feedback right away
11905                        setPressed(true, x, y);
11906                        checkForLongClick(0, x, y);
11907                    }
11908                    break;
11909
11910                case MotionEvent.ACTION_CANCEL:
11911                    if (clickable) {
11912                        setPressed(false);
11913                    }
11914                    removeTapCallback();
11915                    removeLongPressCallback();
11916                    mInContextButtonPress = false;
11917                    mHasPerformedLongPress = false;
11918                    mIgnoreNextUpEvent = false;
11919                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11920                    break;
11921
11922                case MotionEvent.ACTION_MOVE:
11923                    if (clickable) {
11924                        drawableHotspotChanged(x, y);
11925                    }
11926
11927                    // Be lenient about moving outside of buttons
11928                    if (!pointInView(x, y, mTouchSlop)) {
11929                        // Outside button
11930                        // Remove any future long press/tap checks
11931                        removeTapCallback();
11932                        removeLongPressCallback();
11933                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11934                            setPressed(false);
11935                        }
11936                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11937                    }
11938                    break;
11939            }
11940
11941            return true;
11942        }
11943
11944        return false;
11945    }
11946
11947    /**
11948     * @hide
11949     */
11950    public boolean isInScrollingContainer() {
11951        ViewParent p = getParent();
11952        while (p != null && p instanceof ViewGroup) {
11953            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11954                return true;
11955            }
11956            p = p.getParent();
11957        }
11958        return false;
11959    }
11960
11961    /**
11962     * Remove the longpress detection timer.
11963     */
11964    private void removeLongPressCallback() {
11965        if (mPendingCheckForLongPress != null) {
11966            removeCallbacks(mPendingCheckForLongPress);
11967        }
11968    }
11969
11970    /**
11971     * Remove the pending click action
11972     */
11973    private void removePerformClickCallback() {
11974        if (mPerformClick != null) {
11975            removeCallbacks(mPerformClick);
11976        }
11977    }
11978
11979    /**
11980     * Remove the prepress detection timer.
11981     */
11982    private void removeUnsetPressCallback() {
11983        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11984            setPressed(false);
11985            removeCallbacks(mUnsetPressedState);
11986        }
11987    }
11988
11989    /**
11990     * Remove the tap detection timer.
11991     */
11992    private void removeTapCallback() {
11993        if (mPendingCheckForTap != null) {
11994            mPrivateFlags &= ~PFLAG_PREPRESSED;
11995            removeCallbacks(mPendingCheckForTap);
11996        }
11997    }
11998
11999    /**
12000     * Cancels a pending long press.  Your subclass can use this if you
12001     * want the context menu to come up if the user presses and holds
12002     * at the same place, but you don't want it to come up if they press
12003     * and then move around enough to cause scrolling.
12004     */
12005    public void cancelLongPress() {
12006        removeLongPressCallback();
12007
12008        /*
12009         * The prepressed state handled by the tap callback is a display
12010         * construct, but the tap callback will post a long press callback
12011         * less its own timeout. Remove it here.
12012         */
12013        removeTapCallback();
12014    }
12015
12016    /**
12017     * Remove the pending callback for sending a
12018     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
12019     */
12020    private void removeSendViewScrolledAccessibilityEventCallback() {
12021        if (mSendViewScrolledAccessibilityEvent != null) {
12022            removeCallbacks(mSendViewScrolledAccessibilityEvent);
12023            mSendViewScrolledAccessibilityEvent.mIsPending = false;
12024        }
12025    }
12026
12027    /**
12028     * Sets the TouchDelegate for this View.
12029     */
12030    public void setTouchDelegate(TouchDelegate delegate) {
12031        mTouchDelegate = delegate;
12032    }
12033
12034    /**
12035     * Gets the TouchDelegate for this View.
12036     */
12037    public TouchDelegate getTouchDelegate() {
12038        return mTouchDelegate;
12039    }
12040
12041    /**
12042     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
12043     *
12044     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
12045     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
12046     * available. This method should only be called for touch events.
12047     *
12048     * <p class="note">This api is not intended for most applications. Buffered dispatch
12049     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
12050     * streams will not improve your input latency. Side effects include: increased latency,
12051     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
12052     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
12053     * you.</p>
12054     */
12055    public final void requestUnbufferedDispatch(MotionEvent event) {
12056        final int action = event.getAction();
12057        if (mAttachInfo == null
12058                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
12059                || !event.isTouchEvent()) {
12060            return;
12061        }
12062        mAttachInfo.mUnbufferedDispatchRequested = true;
12063    }
12064
12065    /**
12066     * Set flags controlling behavior of this view.
12067     *
12068     * @param flags Constant indicating the value which should be set
12069     * @param mask Constant indicating the bit range that should be changed
12070     */
12071    void setFlags(int flags, int mask) {
12072        final boolean accessibilityEnabled =
12073                AccessibilityManager.getInstance(mContext).isEnabled();
12074        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
12075
12076        int old = mViewFlags;
12077        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
12078
12079        int changed = mViewFlags ^ old;
12080        if (changed == 0) {
12081            return;
12082        }
12083        int privateFlags = mPrivateFlags;
12084
12085        /* Check if the FOCUSABLE bit has changed */
12086        if (((changed & FOCUSABLE_MASK) != 0) &&
12087                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
12088            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
12089                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
12090                /* Give up focus if we are no longer focusable */
12091                clearFocus();
12092            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
12093                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
12094                /*
12095                 * Tell the view system that we are now available to take focus
12096                 * if no one else already has it.
12097                 */
12098                if (mParent != null) mParent.focusableViewAvailable(this);
12099            }
12100        }
12101
12102        final int newVisibility = flags & VISIBILITY_MASK;
12103        if (newVisibility == VISIBLE) {
12104            if ((changed & VISIBILITY_MASK) != 0) {
12105                /*
12106                 * If this view is becoming visible, invalidate it in case it changed while
12107                 * it was not visible. Marking it drawn ensures that the invalidation will
12108                 * go through.
12109                 */
12110                mPrivateFlags |= PFLAG_DRAWN;
12111                invalidate(true);
12112
12113                needGlobalAttributesUpdate(true);
12114
12115                // a view becoming visible is worth notifying the parent
12116                // about in case nothing has focus.  even if this specific view
12117                // isn't focusable, it may contain something that is, so let
12118                // the root view try to give this focus if nothing else does.
12119                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
12120                    mParent.focusableViewAvailable(this);
12121                }
12122            }
12123        }
12124
12125        /* Check if the GONE bit has changed */
12126        if ((changed & GONE) != 0) {
12127            needGlobalAttributesUpdate(false);
12128            requestLayout();
12129
12130            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
12131                if (hasFocus()) clearFocus();
12132                clearAccessibilityFocus();
12133                destroyDrawingCache();
12134                if (mParent instanceof View) {
12135                    // GONE views noop invalidation, so invalidate the parent
12136                    ((View) mParent).invalidate(true);
12137                }
12138                // Mark the view drawn to ensure that it gets invalidated properly the next
12139                // time it is visible and gets invalidated
12140                mPrivateFlags |= PFLAG_DRAWN;
12141            }
12142            if (mAttachInfo != null) {
12143                mAttachInfo.mViewVisibilityChanged = true;
12144            }
12145        }
12146
12147        /* Check if the VISIBLE bit has changed */
12148        if ((changed & INVISIBLE) != 0) {
12149            needGlobalAttributesUpdate(false);
12150            /*
12151             * If this view is becoming invisible, set the DRAWN flag so that
12152             * the next invalidate() will not be skipped.
12153             */
12154            mPrivateFlags |= PFLAG_DRAWN;
12155
12156            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
12157                // root view becoming invisible shouldn't clear focus and accessibility focus
12158                if (getRootView() != this) {
12159                    if (hasFocus()) clearFocus();
12160                    clearAccessibilityFocus();
12161                }
12162            }
12163            if (mAttachInfo != null) {
12164                mAttachInfo.mViewVisibilityChanged = true;
12165            }
12166        }
12167
12168        if ((changed & VISIBILITY_MASK) != 0) {
12169            // If the view is invisible, cleanup its display list to free up resources
12170            if (newVisibility != VISIBLE && mAttachInfo != null) {
12171                cleanupDraw();
12172            }
12173
12174            if (mParent instanceof ViewGroup) {
12175                ((ViewGroup) mParent).onChildVisibilityChanged(this,
12176                        (changed & VISIBILITY_MASK), newVisibility);
12177                ((View) mParent).invalidate(true);
12178            } else if (mParent != null) {
12179                mParent.invalidateChild(this, null);
12180            }
12181
12182            if (mAttachInfo != null) {
12183                dispatchVisibilityChanged(this, newVisibility);
12184
12185                // Aggregated visibility changes are dispatched to attached views
12186                // in visible windows where the parent is currently shown/drawn
12187                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
12188                // discounting clipping or overlapping. This makes it a good place
12189                // to change animation states.
12190                if (mParent != null && getWindowVisibility() == VISIBLE &&
12191                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
12192                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
12193                }
12194                notifySubtreeAccessibilityStateChangedIfNeeded();
12195            }
12196        }
12197
12198        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
12199            destroyDrawingCache();
12200        }
12201
12202        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
12203            destroyDrawingCache();
12204            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12205            invalidateParentCaches();
12206        }
12207
12208        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
12209            destroyDrawingCache();
12210            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12211        }
12212
12213        if ((changed & DRAW_MASK) != 0) {
12214            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
12215                if (mBackground != null
12216                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
12217                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12218                } else {
12219                    mPrivateFlags |= PFLAG_SKIP_DRAW;
12220                }
12221            } else {
12222                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12223            }
12224            requestLayout();
12225            invalidate(true);
12226        }
12227
12228        if ((changed & KEEP_SCREEN_ON) != 0) {
12229            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12230                mParent.recomputeViewAttributes(this);
12231            }
12232        }
12233
12234        if (accessibilityEnabled) {
12235            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
12236                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
12237                    || (changed & CONTEXT_CLICKABLE) != 0) {
12238                if (oldIncludeForAccessibility != includeForAccessibility()) {
12239                    notifySubtreeAccessibilityStateChangedIfNeeded();
12240                } else {
12241                    notifyViewAccessibilityStateChangedIfNeeded(
12242                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12243                }
12244            } else if ((changed & ENABLED_MASK) != 0) {
12245                notifyViewAccessibilityStateChangedIfNeeded(
12246                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12247            }
12248        }
12249    }
12250
12251    /**
12252     * Change the view's z order in the tree, so it's on top of other sibling
12253     * views. This ordering change may affect layout, if the parent container
12254     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
12255     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
12256     * method should be followed by calls to {@link #requestLayout()} and
12257     * {@link View#invalidate()} on the view's parent to force the parent to redraw
12258     * with the new child ordering.
12259     *
12260     * @see ViewGroup#bringChildToFront(View)
12261     */
12262    public void bringToFront() {
12263        if (mParent != null) {
12264            mParent.bringChildToFront(this);
12265        }
12266    }
12267
12268    /**
12269     * This is called in response to an internal scroll in this view (i.e., the
12270     * view scrolled its own contents). This is typically as a result of
12271     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
12272     * called.
12273     *
12274     * @param l Current horizontal scroll origin.
12275     * @param t Current vertical scroll origin.
12276     * @param oldl Previous horizontal scroll origin.
12277     * @param oldt Previous vertical scroll origin.
12278     */
12279    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
12280        notifySubtreeAccessibilityStateChangedIfNeeded();
12281
12282        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
12283            postSendViewScrolledAccessibilityEventCallback();
12284        }
12285
12286        mBackgroundSizeChanged = true;
12287        if (mForegroundInfo != null) {
12288            mForegroundInfo.mBoundsChanged = true;
12289        }
12290
12291        final AttachInfo ai = mAttachInfo;
12292        if (ai != null) {
12293            ai.mViewScrollChanged = true;
12294        }
12295
12296        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
12297            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
12298        }
12299    }
12300
12301    /**
12302     * Interface definition for a callback to be invoked when the scroll
12303     * X or Y positions of a view change.
12304     * <p>
12305     * <b>Note:</b> Some views handle scrolling independently from View and may
12306     * have their own separate listeners for scroll-type events. For example,
12307     * {@link android.widget.ListView ListView} allows clients to register an
12308     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
12309     * to listen for changes in list scroll position.
12310     *
12311     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
12312     */
12313    public interface OnScrollChangeListener {
12314        /**
12315         * Called when the scroll position of a view changes.
12316         *
12317         * @param v The view whose scroll position has changed.
12318         * @param scrollX Current horizontal scroll origin.
12319         * @param scrollY Current vertical scroll origin.
12320         * @param oldScrollX Previous horizontal scroll origin.
12321         * @param oldScrollY Previous vertical scroll origin.
12322         */
12323        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
12324    }
12325
12326    /**
12327     * Interface definition for a callback to be invoked when the layout bounds of a view
12328     * changes due to layout processing.
12329     */
12330    public interface OnLayoutChangeListener {
12331        /**
12332         * Called when the layout bounds of a view changes due to layout processing.
12333         *
12334         * @param v The view whose bounds have changed.
12335         * @param left The new value of the view's left property.
12336         * @param top The new value of the view's top property.
12337         * @param right The new value of the view's right property.
12338         * @param bottom The new value of the view's bottom property.
12339         * @param oldLeft The previous value of the view's left property.
12340         * @param oldTop The previous value of the view's top property.
12341         * @param oldRight The previous value of the view's right property.
12342         * @param oldBottom The previous value of the view's bottom property.
12343         */
12344        void onLayoutChange(View v, int left, int top, int right, int bottom,
12345            int oldLeft, int oldTop, int oldRight, int oldBottom);
12346    }
12347
12348    /**
12349     * This is called during layout when the size of this view has changed. If
12350     * you were just added to the view hierarchy, you're called with the old
12351     * values of 0.
12352     *
12353     * @param w Current width of this view.
12354     * @param h Current height of this view.
12355     * @param oldw Old width of this view.
12356     * @param oldh Old height of this view.
12357     */
12358    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
12359    }
12360
12361    /**
12362     * Called by draw to draw the child views. This may be overridden
12363     * by derived classes to gain control just before its children are drawn
12364     * (but after its own view has been drawn).
12365     * @param canvas the canvas on which to draw the view
12366     */
12367    protected void dispatchDraw(Canvas canvas) {
12368
12369    }
12370
12371    /**
12372     * Gets the parent of this view. Note that the parent is a
12373     * ViewParent and not necessarily a View.
12374     *
12375     * @return Parent of this view.
12376     */
12377    public final ViewParent getParent() {
12378        return mParent;
12379    }
12380
12381    /**
12382     * Set the horizontal scrolled position of your view. This will cause a call to
12383     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12384     * invalidated.
12385     * @param value the x position to scroll to
12386     */
12387    public void setScrollX(int value) {
12388        scrollTo(value, mScrollY);
12389    }
12390
12391    /**
12392     * Set the vertical scrolled position of your view. This will cause a call to
12393     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12394     * invalidated.
12395     * @param value the y position to scroll to
12396     */
12397    public void setScrollY(int value) {
12398        scrollTo(mScrollX, value);
12399    }
12400
12401    /**
12402     * Return the scrolled left position of this view. This is the left edge of
12403     * the displayed part of your view. You do not need to draw any pixels
12404     * farther left, since those are outside of the frame of your view on
12405     * screen.
12406     *
12407     * @return The left edge of the displayed part of your view, in pixels.
12408     */
12409    public final int getScrollX() {
12410        return mScrollX;
12411    }
12412
12413    /**
12414     * Return the scrolled top position of this view. This is the top edge of
12415     * the displayed part of your view. You do not need to draw any pixels above
12416     * it, since those are outside of the frame of your view on screen.
12417     *
12418     * @return The top edge of the displayed part of your view, in pixels.
12419     */
12420    public final int getScrollY() {
12421        return mScrollY;
12422    }
12423
12424    /**
12425     * Return the width of the your view.
12426     *
12427     * @return The width of your view, in pixels.
12428     */
12429    @ViewDebug.ExportedProperty(category = "layout")
12430    public final int getWidth() {
12431        return mRight - mLeft;
12432    }
12433
12434    /**
12435     * Return the height of your view.
12436     *
12437     * @return The height of your view, in pixels.
12438     */
12439    @ViewDebug.ExportedProperty(category = "layout")
12440    public final int getHeight() {
12441        return mBottom - mTop;
12442    }
12443
12444    /**
12445     * Return the visible drawing bounds of your view. Fills in the output
12446     * rectangle with the values from getScrollX(), getScrollY(),
12447     * getWidth(), and getHeight(). These bounds do not account for any
12448     * transformation properties currently set on the view, such as
12449     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
12450     *
12451     * @param outRect The (scrolled) drawing bounds of the view.
12452     */
12453    public void getDrawingRect(Rect outRect) {
12454        outRect.left = mScrollX;
12455        outRect.top = mScrollY;
12456        outRect.right = mScrollX + (mRight - mLeft);
12457        outRect.bottom = mScrollY + (mBottom - mTop);
12458    }
12459
12460    /**
12461     * Like {@link #getMeasuredWidthAndState()}, but only returns the
12462     * raw width component (that is the result is masked by
12463     * {@link #MEASURED_SIZE_MASK}).
12464     *
12465     * @return The raw measured width of this view.
12466     */
12467    public final int getMeasuredWidth() {
12468        return mMeasuredWidth & MEASURED_SIZE_MASK;
12469    }
12470
12471    /**
12472     * Return the full width measurement information for this view as computed
12473     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12474     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12475     * This should be used during measurement and layout calculations only. Use
12476     * {@link #getWidth()} to see how wide a view is after layout.
12477     *
12478     * @return The measured width of this view as a bit mask.
12479     */
12480    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12481            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12482                    name = "MEASURED_STATE_TOO_SMALL"),
12483    })
12484    public final int getMeasuredWidthAndState() {
12485        return mMeasuredWidth;
12486    }
12487
12488    /**
12489     * Like {@link #getMeasuredHeightAndState()}, but only returns the
12490     * raw height component (that is the result is masked by
12491     * {@link #MEASURED_SIZE_MASK}).
12492     *
12493     * @return The raw measured height of this view.
12494     */
12495    public final int getMeasuredHeight() {
12496        return mMeasuredHeight & MEASURED_SIZE_MASK;
12497    }
12498
12499    /**
12500     * Return the full height measurement information for this view as computed
12501     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
12502     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12503     * This should be used during measurement and layout calculations only. Use
12504     * {@link #getHeight()} to see how wide a view is after layout.
12505     *
12506     * @return The measured height of this view as a bit mask.
12507     */
12508    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
12509            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
12510                    name = "MEASURED_STATE_TOO_SMALL"),
12511    })
12512    public final int getMeasuredHeightAndState() {
12513        return mMeasuredHeight;
12514    }
12515
12516    /**
12517     * Return only the state bits of {@link #getMeasuredWidthAndState()}
12518     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
12519     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
12520     * and the height component is at the shifted bits
12521     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
12522     */
12523    public final int getMeasuredState() {
12524        return (mMeasuredWidth&MEASURED_STATE_MASK)
12525                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
12526                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
12527    }
12528
12529    /**
12530     * The transform matrix of this view, which is calculated based on the current
12531     * rotation, scale, and pivot properties.
12532     *
12533     * @see #getRotation()
12534     * @see #getScaleX()
12535     * @see #getScaleY()
12536     * @see #getPivotX()
12537     * @see #getPivotY()
12538     * @return The current transform matrix for the view
12539     */
12540    public Matrix getMatrix() {
12541        ensureTransformationInfo();
12542        final Matrix matrix = mTransformationInfo.mMatrix;
12543        mRenderNode.getMatrix(matrix);
12544        return matrix;
12545    }
12546
12547    /**
12548     * Returns true if the transform matrix is the identity matrix.
12549     * Recomputes the matrix if necessary.
12550     *
12551     * @return True if the transform matrix is the identity matrix, false otherwise.
12552     */
12553    final boolean hasIdentityMatrix() {
12554        return mRenderNode.hasIdentityMatrix();
12555    }
12556
12557    void ensureTransformationInfo() {
12558        if (mTransformationInfo == null) {
12559            mTransformationInfo = new TransformationInfo();
12560        }
12561    }
12562
12563    /**
12564     * Utility method to retrieve the inverse of the current mMatrix property.
12565     * We cache the matrix to avoid recalculating it when transform properties
12566     * have not changed.
12567     *
12568     * @return The inverse of the current matrix of this view.
12569     * @hide
12570     */
12571    public final Matrix getInverseMatrix() {
12572        ensureTransformationInfo();
12573        if (mTransformationInfo.mInverseMatrix == null) {
12574            mTransformationInfo.mInverseMatrix = new Matrix();
12575        }
12576        final Matrix matrix = mTransformationInfo.mInverseMatrix;
12577        mRenderNode.getInverseMatrix(matrix);
12578        return matrix;
12579    }
12580
12581    /**
12582     * Gets the distance along the Z axis from the camera to this view.
12583     *
12584     * @see #setCameraDistance(float)
12585     *
12586     * @return The distance along the Z axis.
12587     */
12588    public float getCameraDistance() {
12589        final float dpi = mResources.getDisplayMetrics().densityDpi;
12590        return -(mRenderNode.getCameraDistance() * dpi);
12591    }
12592
12593    /**
12594     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
12595     * views are drawn) from the camera to this view. The camera's distance
12596     * affects 3D transformations, for instance rotations around the X and Y
12597     * axis. If the rotationX or rotationY properties are changed and this view is
12598     * large (more than half the size of the screen), it is recommended to always
12599     * use a camera distance that's greater than the height (X axis rotation) or
12600     * the width (Y axis rotation) of this view.</p>
12601     *
12602     * <p>The distance of the camera from the view plane can have an affect on the
12603     * perspective distortion of the view when it is rotated around the x or y axis.
12604     * For example, a large distance will result in a large viewing angle, and there
12605     * will not be much perspective distortion of the view as it rotates. A short
12606     * distance may cause much more perspective distortion upon rotation, and can
12607     * also result in some drawing artifacts if the rotated view ends up partially
12608     * behind the camera (which is why the recommendation is to use a distance at
12609     * least as far as the size of the view, if the view is to be rotated.)</p>
12610     *
12611     * <p>The distance is expressed in "depth pixels." The default distance depends
12612     * on the screen density. For instance, on a medium density display, the
12613     * default distance is 1280. On a high density display, the default distance
12614     * is 1920.</p>
12615     *
12616     * <p>If you want to specify a distance that leads to visually consistent
12617     * results across various densities, use the following formula:</p>
12618     * <pre>
12619     * float scale = context.getResources().getDisplayMetrics().density;
12620     * view.setCameraDistance(distance * scale);
12621     * </pre>
12622     *
12623     * <p>The density scale factor of a high density display is 1.5,
12624     * and 1920 = 1280 * 1.5.</p>
12625     *
12626     * @param distance The distance in "depth pixels", if negative the opposite
12627     *        value is used
12628     *
12629     * @see #setRotationX(float)
12630     * @see #setRotationY(float)
12631     */
12632    public void setCameraDistance(float distance) {
12633        final float dpi = mResources.getDisplayMetrics().densityDpi;
12634
12635        invalidateViewProperty(true, false);
12636        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
12637        invalidateViewProperty(false, false);
12638
12639        invalidateParentIfNeededAndWasQuickRejected();
12640    }
12641
12642    /**
12643     * The degrees that the view is rotated around the pivot point.
12644     *
12645     * @see #setRotation(float)
12646     * @see #getPivotX()
12647     * @see #getPivotY()
12648     *
12649     * @return The degrees of rotation.
12650     */
12651    @ViewDebug.ExportedProperty(category = "drawing")
12652    public float getRotation() {
12653        return mRenderNode.getRotation();
12654    }
12655
12656    /**
12657     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12658     * result in clockwise rotation.
12659     *
12660     * @param rotation The degrees of rotation.
12661     *
12662     * @see #getRotation()
12663     * @see #getPivotX()
12664     * @see #getPivotY()
12665     * @see #setRotationX(float)
12666     * @see #setRotationY(float)
12667     *
12668     * @attr ref android.R.styleable#View_rotation
12669     */
12670    public void setRotation(float rotation) {
12671        if (rotation != getRotation()) {
12672            // Double-invalidation is necessary to capture view's old and new areas
12673            invalidateViewProperty(true, false);
12674            mRenderNode.setRotation(rotation);
12675            invalidateViewProperty(false, true);
12676
12677            invalidateParentIfNeededAndWasQuickRejected();
12678            notifySubtreeAccessibilityStateChangedIfNeeded();
12679        }
12680    }
12681
12682    /**
12683     * The degrees that the view is rotated around the vertical axis through the pivot point.
12684     *
12685     * @see #getPivotX()
12686     * @see #getPivotY()
12687     * @see #setRotationY(float)
12688     *
12689     * @return The degrees of Y rotation.
12690     */
12691    @ViewDebug.ExportedProperty(category = "drawing")
12692    public float getRotationY() {
12693        return mRenderNode.getRotationY();
12694    }
12695
12696    /**
12697     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12698     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12699     * down the y axis.
12700     *
12701     * When rotating large views, it is recommended to adjust the camera distance
12702     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12703     *
12704     * @param rotationY The degrees of Y rotation.
12705     *
12706     * @see #getRotationY()
12707     * @see #getPivotX()
12708     * @see #getPivotY()
12709     * @see #setRotation(float)
12710     * @see #setRotationX(float)
12711     * @see #setCameraDistance(float)
12712     *
12713     * @attr ref android.R.styleable#View_rotationY
12714     */
12715    public void setRotationY(float rotationY) {
12716        if (rotationY != getRotationY()) {
12717            invalidateViewProperty(true, false);
12718            mRenderNode.setRotationY(rotationY);
12719            invalidateViewProperty(false, true);
12720
12721            invalidateParentIfNeededAndWasQuickRejected();
12722            notifySubtreeAccessibilityStateChangedIfNeeded();
12723        }
12724    }
12725
12726    /**
12727     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12728     *
12729     * @see #getPivotX()
12730     * @see #getPivotY()
12731     * @see #setRotationX(float)
12732     *
12733     * @return The degrees of X rotation.
12734     */
12735    @ViewDebug.ExportedProperty(category = "drawing")
12736    public float getRotationX() {
12737        return mRenderNode.getRotationX();
12738    }
12739
12740    /**
12741     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12742     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12743     * x axis.
12744     *
12745     * When rotating large views, it is recommended to adjust the camera distance
12746     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12747     *
12748     * @param rotationX The degrees of X rotation.
12749     *
12750     * @see #getRotationX()
12751     * @see #getPivotX()
12752     * @see #getPivotY()
12753     * @see #setRotation(float)
12754     * @see #setRotationY(float)
12755     * @see #setCameraDistance(float)
12756     *
12757     * @attr ref android.R.styleable#View_rotationX
12758     */
12759    public void setRotationX(float rotationX) {
12760        if (rotationX != getRotationX()) {
12761            invalidateViewProperty(true, false);
12762            mRenderNode.setRotationX(rotationX);
12763            invalidateViewProperty(false, true);
12764
12765            invalidateParentIfNeededAndWasQuickRejected();
12766            notifySubtreeAccessibilityStateChangedIfNeeded();
12767        }
12768    }
12769
12770    /**
12771     * The amount that the view is scaled in x around the pivot point, as a proportion of
12772     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12773     *
12774     * <p>By default, this is 1.0f.
12775     *
12776     * @see #getPivotX()
12777     * @see #getPivotY()
12778     * @return The scaling factor.
12779     */
12780    @ViewDebug.ExportedProperty(category = "drawing")
12781    public float getScaleX() {
12782        return mRenderNode.getScaleX();
12783    }
12784
12785    /**
12786     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12787     * the view's unscaled width. A value of 1 means that no scaling is applied.
12788     *
12789     * @param scaleX The scaling factor.
12790     * @see #getPivotX()
12791     * @see #getPivotY()
12792     *
12793     * @attr ref android.R.styleable#View_scaleX
12794     */
12795    public void setScaleX(float scaleX) {
12796        if (scaleX != getScaleX()) {
12797            invalidateViewProperty(true, false);
12798            mRenderNode.setScaleX(scaleX);
12799            invalidateViewProperty(false, true);
12800
12801            invalidateParentIfNeededAndWasQuickRejected();
12802            notifySubtreeAccessibilityStateChangedIfNeeded();
12803        }
12804    }
12805
12806    /**
12807     * The amount that the view is scaled in y around the pivot point, as a proportion of
12808     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12809     *
12810     * <p>By default, this is 1.0f.
12811     *
12812     * @see #getPivotX()
12813     * @see #getPivotY()
12814     * @return The scaling factor.
12815     */
12816    @ViewDebug.ExportedProperty(category = "drawing")
12817    public float getScaleY() {
12818        return mRenderNode.getScaleY();
12819    }
12820
12821    /**
12822     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12823     * the view's unscaled width. A value of 1 means that no scaling is applied.
12824     *
12825     * @param scaleY The scaling factor.
12826     * @see #getPivotX()
12827     * @see #getPivotY()
12828     *
12829     * @attr ref android.R.styleable#View_scaleY
12830     */
12831    public void setScaleY(float scaleY) {
12832        if (scaleY != getScaleY()) {
12833            invalidateViewProperty(true, false);
12834            mRenderNode.setScaleY(scaleY);
12835            invalidateViewProperty(false, true);
12836
12837            invalidateParentIfNeededAndWasQuickRejected();
12838            notifySubtreeAccessibilityStateChangedIfNeeded();
12839        }
12840    }
12841
12842    /**
12843     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12844     * and {@link #setScaleX(float) scaled}.
12845     *
12846     * @see #getRotation()
12847     * @see #getScaleX()
12848     * @see #getScaleY()
12849     * @see #getPivotY()
12850     * @return The x location of the pivot point.
12851     *
12852     * @attr ref android.R.styleable#View_transformPivotX
12853     */
12854    @ViewDebug.ExportedProperty(category = "drawing")
12855    public float getPivotX() {
12856        return mRenderNode.getPivotX();
12857    }
12858
12859    /**
12860     * Sets the x location of the point around which the view is
12861     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12862     * By default, the pivot point is centered on the object.
12863     * Setting this property disables this behavior and causes the view to use only the
12864     * explicitly set pivotX and pivotY values.
12865     *
12866     * @param pivotX The x location of the pivot point.
12867     * @see #getRotation()
12868     * @see #getScaleX()
12869     * @see #getScaleY()
12870     * @see #getPivotY()
12871     *
12872     * @attr ref android.R.styleable#View_transformPivotX
12873     */
12874    public void setPivotX(float pivotX) {
12875        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12876            invalidateViewProperty(true, false);
12877            mRenderNode.setPivotX(pivotX);
12878            invalidateViewProperty(false, true);
12879
12880            invalidateParentIfNeededAndWasQuickRejected();
12881        }
12882    }
12883
12884    /**
12885     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12886     * and {@link #setScaleY(float) scaled}.
12887     *
12888     * @see #getRotation()
12889     * @see #getScaleX()
12890     * @see #getScaleY()
12891     * @see #getPivotY()
12892     * @return The y location of the pivot point.
12893     *
12894     * @attr ref android.R.styleable#View_transformPivotY
12895     */
12896    @ViewDebug.ExportedProperty(category = "drawing")
12897    public float getPivotY() {
12898        return mRenderNode.getPivotY();
12899    }
12900
12901    /**
12902     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12903     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12904     * Setting this property disables this behavior and causes the view to use only the
12905     * explicitly set pivotX and pivotY values.
12906     *
12907     * @param pivotY The y location of the pivot point.
12908     * @see #getRotation()
12909     * @see #getScaleX()
12910     * @see #getScaleY()
12911     * @see #getPivotY()
12912     *
12913     * @attr ref android.R.styleable#View_transformPivotY
12914     */
12915    public void setPivotY(float pivotY) {
12916        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12917            invalidateViewProperty(true, false);
12918            mRenderNode.setPivotY(pivotY);
12919            invalidateViewProperty(false, true);
12920
12921            invalidateParentIfNeededAndWasQuickRejected();
12922        }
12923    }
12924
12925    /**
12926     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12927     * completely transparent and 1 means the view is completely opaque.
12928     *
12929     * <p>By default this is 1.0f.
12930     * @return The opacity of the view.
12931     */
12932    @ViewDebug.ExportedProperty(category = "drawing")
12933    public float getAlpha() {
12934        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12935    }
12936
12937    /**
12938     * Sets the behavior for overlapping rendering for this view (see {@link
12939     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12940     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12941     * providing the value which is then used internally. That is, when {@link
12942     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12943     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12944     * instead.
12945     *
12946     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12947     * instead of that returned by {@link #hasOverlappingRendering()}.
12948     *
12949     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12950     */
12951    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12952        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12953        if (hasOverlappingRendering) {
12954            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12955        } else {
12956            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12957        }
12958    }
12959
12960    /**
12961     * Returns the value for overlapping rendering that is used internally. This is either
12962     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12963     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12964     *
12965     * @return The value for overlapping rendering being used internally.
12966     */
12967    public final boolean getHasOverlappingRendering() {
12968        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12969                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12970                hasOverlappingRendering();
12971    }
12972
12973    /**
12974     * Returns whether this View has content which overlaps.
12975     *
12976     * <p>This function, intended to be overridden by specific View types, is an optimization when
12977     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12978     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12979     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12980     * directly. An example of overlapping rendering is a TextView with a background image, such as
12981     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12982     * ImageView with only the foreground image. The default implementation returns true; subclasses
12983     * should override if they have cases which can be optimized.</p>
12984     *
12985     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12986     * necessitates that a View return true if it uses the methods internally without passing the
12987     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12988     *
12989     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12990     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12991     *
12992     * @return true if the content in this view might overlap, false otherwise.
12993     */
12994    @ViewDebug.ExportedProperty(category = "drawing")
12995    public boolean hasOverlappingRendering() {
12996        return true;
12997    }
12998
12999    /**
13000     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
13001     * completely transparent and 1 means the view is completely opaque.
13002     *
13003     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
13004     * can have significant performance implications, especially for large views. It is best to use
13005     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
13006     *
13007     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
13008     * strongly recommended for performance reasons to either override
13009     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
13010     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
13011     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
13012     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
13013     * of rendering cost, even for simple or small views. Starting with
13014     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
13015     * applied to the view at the rendering level.</p>
13016     *
13017     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
13018     * responsible for applying the opacity itself.</p>
13019     *
13020     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
13021     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
13022     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
13023     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
13024     *
13025     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
13026     * value will clip a View to its bounds, unless the View returns <code>false</code> from
13027     * {@link #hasOverlappingRendering}.</p>
13028     *
13029     * @param alpha The opacity of the view.
13030     *
13031     * @see #hasOverlappingRendering()
13032     * @see #setLayerType(int, android.graphics.Paint)
13033     *
13034     * @attr ref android.R.styleable#View_alpha
13035     */
13036    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
13037        ensureTransformationInfo();
13038        if (mTransformationInfo.mAlpha != alpha) {
13039            // Report visibility changes, which can affect children, to accessibility
13040            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
13041                notifySubtreeAccessibilityStateChangedIfNeeded();
13042            }
13043            mTransformationInfo.mAlpha = alpha;
13044            if (onSetAlpha((int) (alpha * 255))) {
13045                mPrivateFlags |= PFLAG_ALPHA_SET;
13046                // subclass is handling alpha - don't optimize rendering cache invalidation
13047                invalidateParentCaches();
13048                invalidate(true);
13049            } else {
13050                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13051                invalidateViewProperty(true, false);
13052                mRenderNode.setAlpha(getFinalAlpha());
13053            }
13054        }
13055    }
13056
13057    /**
13058     * Faster version of setAlpha() which performs the same steps except there are
13059     * no calls to invalidate(). The caller of this function should perform proper invalidation
13060     * on the parent and this object. The return value indicates whether the subclass handles
13061     * alpha (the return value for onSetAlpha()).
13062     *
13063     * @param alpha The new value for the alpha property
13064     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
13065     *         the new value for the alpha property is different from the old value
13066     */
13067    boolean setAlphaNoInvalidation(float alpha) {
13068        ensureTransformationInfo();
13069        if (mTransformationInfo.mAlpha != alpha) {
13070            mTransformationInfo.mAlpha = alpha;
13071            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
13072            if (subclassHandlesAlpha) {
13073                mPrivateFlags |= PFLAG_ALPHA_SET;
13074                return true;
13075            } else {
13076                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13077                mRenderNode.setAlpha(getFinalAlpha());
13078            }
13079        }
13080        return false;
13081    }
13082
13083    /**
13084     * This property is hidden and intended only for use by the Fade transition, which
13085     * animates it to produce a visual translucency that does not side-effect (or get
13086     * affected by) the real alpha property. This value is composited with the other
13087     * alpha value (and the AlphaAnimation value, when that is present) to produce
13088     * a final visual translucency result, which is what is passed into the DisplayList.
13089     *
13090     * @hide
13091     */
13092    public void setTransitionAlpha(float alpha) {
13093        ensureTransformationInfo();
13094        if (mTransformationInfo.mTransitionAlpha != alpha) {
13095            mTransformationInfo.mTransitionAlpha = alpha;
13096            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13097            invalidateViewProperty(true, false);
13098            mRenderNode.setAlpha(getFinalAlpha());
13099        }
13100    }
13101
13102    /**
13103     * Calculates the visual alpha of this view, which is a combination of the actual
13104     * alpha value and the transitionAlpha value (if set).
13105     */
13106    private float getFinalAlpha() {
13107        if (mTransformationInfo != null) {
13108            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
13109        }
13110        return 1;
13111    }
13112
13113    /**
13114     * This property is hidden and intended only for use by the Fade transition, which
13115     * animates it to produce a visual translucency that does not side-effect (or get
13116     * affected by) the real alpha property. This value is composited with the other
13117     * alpha value (and the AlphaAnimation value, when that is present) to produce
13118     * a final visual translucency result, which is what is passed into the DisplayList.
13119     *
13120     * @hide
13121     */
13122    @ViewDebug.ExportedProperty(category = "drawing")
13123    public float getTransitionAlpha() {
13124        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
13125    }
13126
13127    /**
13128     * Top position of this view relative to its parent.
13129     *
13130     * @return The top of this view, in pixels.
13131     */
13132    @ViewDebug.CapturedViewProperty
13133    public final int getTop() {
13134        return mTop;
13135    }
13136
13137    /**
13138     * Sets the top position of this view relative to its parent. This method is meant to be called
13139     * by the layout system and should not generally be called otherwise, because the property
13140     * may be changed at any time by the layout.
13141     *
13142     * @param top The top of this view, in pixels.
13143     */
13144    public final void setTop(int top) {
13145        if (top != mTop) {
13146            final boolean matrixIsIdentity = hasIdentityMatrix();
13147            if (matrixIsIdentity) {
13148                if (mAttachInfo != null) {
13149                    int minTop;
13150                    int yLoc;
13151                    if (top < mTop) {
13152                        minTop = top;
13153                        yLoc = top - mTop;
13154                    } else {
13155                        minTop = mTop;
13156                        yLoc = 0;
13157                    }
13158                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
13159                }
13160            } else {
13161                // Double-invalidation is necessary to capture view's old and new areas
13162                invalidate(true);
13163            }
13164
13165            int width = mRight - mLeft;
13166            int oldHeight = mBottom - mTop;
13167
13168            mTop = top;
13169            mRenderNode.setTop(mTop);
13170
13171            sizeChange(width, mBottom - mTop, width, oldHeight);
13172
13173            if (!matrixIsIdentity) {
13174                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13175                invalidate(true);
13176            }
13177            mBackgroundSizeChanged = true;
13178            if (mForegroundInfo != null) {
13179                mForegroundInfo.mBoundsChanged = true;
13180            }
13181            invalidateParentIfNeeded();
13182            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13183                // View was rejected last time it was drawn by its parent; this may have changed
13184                invalidateParentIfNeeded();
13185            }
13186        }
13187    }
13188
13189    /**
13190     * Bottom position of this view relative to its parent.
13191     *
13192     * @return The bottom of this view, in pixels.
13193     */
13194    @ViewDebug.CapturedViewProperty
13195    public final int getBottom() {
13196        return mBottom;
13197    }
13198
13199    /**
13200     * True if this view has changed since the last time being drawn.
13201     *
13202     * @return The dirty state of this view.
13203     */
13204    public boolean isDirty() {
13205        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
13206    }
13207
13208    /**
13209     * Sets the bottom position of this view relative to its parent. This method is meant to be
13210     * called by the layout system and should not generally be called otherwise, because the
13211     * property may be changed at any time by the layout.
13212     *
13213     * @param bottom The bottom of this view, in pixels.
13214     */
13215    public final void setBottom(int bottom) {
13216        if (bottom != mBottom) {
13217            final boolean matrixIsIdentity = hasIdentityMatrix();
13218            if (matrixIsIdentity) {
13219                if (mAttachInfo != null) {
13220                    int maxBottom;
13221                    if (bottom < mBottom) {
13222                        maxBottom = mBottom;
13223                    } else {
13224                        maxBottom = bottom;
13225                    }
13226                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
13227                }
13228            } else {
13229                // Double-invalidation is necessary to capture view's old and new areas
13230                invalidate(true);
13231            }
13232
13233            int width = mRight - mLeft;
13234            int oldHeight = mBottom - mTop;
13235
13236            mBottom = bottom;
13237            mRenderNode.setBottom(mBottom);
13238
13239            sizeChange(width, mBottom - mTop, width, oldHeight);
13240
13241            if (!matrixIsIdentity) {
13242                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13243                invalidate(true);
13244            }
13245            mBackgroundSizeChanged = true;
13246            if (mForegroundInfo != null) {
13247                mForegroundInfo.mBoundsChanged = true;
13248            }
13249            invalidateParentIfNeeded();
13250            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13251                // View was rejected last time it was drawn by its parent; this may have changed
13252                invalidateParentIfNeeded();
13253            }
13254        }
13255    }
13256
13257    /**
13258     * Left position of this view relative to its parent.
13259     *
13260     * @return The left edge of this view, in pixels.
13261     */
13262    @ViewDebug.CapturedViewProperty
13263    public final int getLeft() {
13264        return mLeft;
13265    }
13266
13267    /**
13268     * Sets the left position of this view relative to its parent. This method is meant to be called
13269     * by the layout system and should not generally be called otherwise, because the property
13270     * may be changed at any time by the layout.
13271     *
13272     * @param left The left of this view, in pixels.
13273     */
13274    public final void setLeft(int left) {
13275        if (left != mLeft) {
13276            final boolean matrixIsIdentity = hasIdentityMatrix();
13277            if (matrixIsIdentity) {
13278                if (mAttachInfo != null) {
13279                    int minLeft;
13280                    int xLoc;
13281                    if (left < mLeft) {
13282                        minLeft = left;
13283                        xLoc = left - mLeft;
13284                    } else {
13285                        minLeft = mLeft;
13286                        xLoc = 0;
13287                    }
13288                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
13289                }
13290            } else {
13291                // Double-invalidation is necessary to capture view's old and new areas
13292                invalidate(true);
13293            }
13294
13295            int oldWidth = mRight - mLeft;
13296            int height = mBottom - mTop;
13297
13298            mLeft = left;
13299            mRenderNode.setLeft(left);
13300
13301            sizeChange(mRight - mLeft, height, oldWidth, height);
13302
13303            if (!matrixIsIdentity) {
13304                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13305                invalidate(true);
13306            }
13307            mBackgroundSizeChanged = true;
13308            if (mForegroundInfo != null) {
13309                mForegroundInfo.mBoundsChanged = true;
13310            }
13311            invalidateParentIfNeeded();
13312            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13313                // View was rejected last time it was drawn by its parent; this may have changed
13314                invalidateParentIfNeeded();
13315            }
13316        }
13317    }
13318
13319    /**
13320     * Right position of this view relative to its parent.
13321     *
13322     * @return The right edge of this view, in pixels.
13323     */
13324    @ViewDebug.CapturedViewProperty
13325    public final int getRight() {
13326        return mRight;
13327    }
13328
13329    /**
13330     * Sets the right position of this view relative to its parent. This method is meant to be called
13331     * by the layout system and should not generally be called otherwise, because the property
13332     * may be changed at any time by the layout.
13333     *
13334     * @param right The right of this view, in pixels.
13335     */
13336    public final void setRight(int right) {
13337        if (right != mRight) {
13338            final boolean matrixIsIdentity = hasIdentityMatrix();
13339            if (matrixIsIdentity) {
13340                if (mAttachInfo != null) {
13341                    int maxRight;
13342                    if (right < mRight) {
13343                        maxRight = mRight;
13344                    } else {
13345                        maxRight = right;
13346                    }
13347                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
13348                }
13349            } else {
13350                // Double-invalidation is necessary to capture view's old and new areas
13351                invalidate(true);
13352            }
13353
13354            int oldWidth = mRight - mLeft;
13355            int height = mBottom - mTop;
13356
13357            mRight = right;
13358            mRenderNode.setRight(mRight);
13359
13360            sizeChange(mRight - mLeft, height, oldWidth, height);
13361
13362            if (!matrixIsIdentity) {
13363                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13364                invalidate(true);
13365            }
13366            mBackgroundSizeChanged = true;
13367            if (mForegroundInfo != null) {
13368                mForegroundInfo.mBoundsChanged = true;
13369            }
13370            invalidateParentIfNeeded();
13371            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13372                // View was rejected last time it was drawn by its parent; this may have changed
13373                invalidateParentIfNeeded();
13374            }
13375        }
13376    }
13377
13378    /**
13379     * The visual x position of this view, in pixels. This is equivalent to the
13380     * {@link #setTranslationX(float) translationX} property plus the current
13381     * {@link #getLeft() left} property.
13382     *
13383     * @return The visual x position of this view, in pixels.
13384     */
13385    @ViewDebug.ExportedProperty(category = "drawing")
13386    public float getX() {
13387        return mLeft + getTranslationX();
13388    }
13389
13390    /**
13391     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
13392     * {@link #setTranslationX(float) translationX} property to be the difference between
13393     * the x value passed in and the current {@link #getLeft() left} property.
13394     *
13395     * @param x The visual x position of this view, in pixels.
13396     */
13397    public void setX(float x) {
13398        setTranslationX(x - mLeft);
13399    }
13400
13401    /**
13402     * The visual y position of this view, in pixels. This is equivalent to the
13403     * {@link #setTranslationY(float) translationY} property plus the current
13404     * {@link #getTop() top} property.
13405     *
13406     * @return The visual y position of this view, in pixels.
13407     */
13408    @ViewDebug.ExportedProperty(category = "drawing")
13409    public float getY() {
13410        return mTop + getTranslationY();
13411    }
13412
13413    /**
13414     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
13415     * {@link #setTranslationY(float) translationY} property to be the difference between
13416     * the y value passed in and the current {@link #getTop() top} property.
13417     *
13418     * @param y The visual y position of this view, in pixels.
13419     */
13420    public void setY(float y) {
13421        setTranslationY(y - mTop);
13422    }
13423
13424    /**
13425     * The visual z position of this view, in pixels. This is equivalent to the
13426     * {@link #setTranslationZ(float) translationZ} property plus the current
13427     * {@link #getElevation() elevation} property.
13428     *
13429     * @return The visual z position of this view, in pixels.
13430     */
13431    @ViewDebug.ExportedProperty(category = "drawing")
13432    public float getZ() {
13433        return getElevation() + getTranslationZ();
13434    }
13435
13436    /**
13437     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
13438     * {@link #setTranslationZ(float) translationZ} property to be the difference between
13439     * the x value passed in and the current {@link #getElevation() elevation} property.
13440     *
13441     * @param z The visual z position of this view, in pixels.
13442     */
13443    public void setZ(float z) {
13444        setTranslationZ(z - getElevation());
13445    }
13446
13447    /**
13448     * The base elevation of this view relative to its parent, in pixels.
13449     *
13450     * @return The base depth position of the view, in pixels.
13451     */
13452    @ViewDebug.ExportedProperty(category = "drawing")
13453    public float getElevation() {
13454        return mRenderNode.getElevation();
13455    }
13456
13457    /**
13458     * Sets the base elevation of this view, in pixels.
13459     *
13460     * @attr ref android.R.styleable#View_elevation
13461     */
13462    public void setElevation(float elevation) {
13463        if (elevation != getElevation()) {
13464            invalidateViewProperty(true, false);
13465            mRenderNode.setElevation(elevation);
13466            invalidateViewProperty(false, true);
13467
13468            invalidateParentIfNeededAndWasQuickRejected();
13469        }
13470    }
13471
13472    /**
13473     * The horizontal location of this view relative to its {@link #getLeft() left} position.
13474     * This position is post-layout, in addition to wherever the object's
13475     * layout placed it.
13476     *
13477     * @return The horizontal position of this view relative to its left position, in pixels.
13478     */
13479    @ViewDebug.ExportedProperty(category = "drawing")
13480    public float getTranslationX() {
13481        return mRenderNode.getTranslationX();
13482    }
13483
13484    /**
13485     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
13486     * This effectively positions the object post-layout, in addition to wherever the object's
13487     * layout placed it.
13488     *
13489     * @param translationX The horizontal position of this view relative to its left position,
13490     * in pixels.
13491     *
13492     * @attr ref android.R.styleable#View_translationX
13493     */
13494    public void setTranslationX(float translationX) {
13495        if (translationX != getTranslationX()) {
13496            invalidateViewProperty(true, false);
13497            mRenderNode.setTranslationX(translationX);
13498            invalidateViewProperty(false, true);
13499
13500            invalidateParentIfNeededAndWasQuickRejected();
13501            notifySubtreeAccessibilityStateChangedIfNeeded();
13502        }
13503    }
13504
13505    /**
13506     * The vertical location of this view relative to its {@link #getTop() top} position.
13507     * This position is post-layout, in addition to wherever the object's
13508     * layout placed it.
13509     *
13510     * @return The vertical position of this view relative to its top position,
13511     * in pixels.
13512     */
13513    @ViewDebug.ExportedProperty(category = "drawing")
13514    public float getTranslationY() {
13515        return mRenderNode.getTranslationY();
13516    }
13517
13518    /**
13519     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
13520     * This effectively positions the object post-layout, in addition to wherever the object's
13521     * layout placed it.
13522     *
13523     * @param translationY The vertical position of this view relative to its top position,
13524     * in pixels.
13525     *
13526     * @attr ref android.R.styleable#View_translationY
13527     */
13528    public void setTranslationY(float translationY) {
13529        if (translationY != getTranslationY()) {
13530            invalidateViewProperty(true, false);
13531            mRenderNode.setTranslationY(translationY);
13532            invalidateViewProperty(false, true);
13533
13534            invalidateParentIfNeededAndWasQuickRejected();
13535            notifySubtreeAccessibilityStateChangedIfNeeded();
13536        }
13537    }
13538
13539    /**
13540     * The depth location of this view relative to its {@link #getElevation() elevation}.
13541     *
13542     * @return The depth of this view relative to its elevation.
13543     */
13544    @ViewDebug.ExportedProperty(category = "drawing")
13545    public float getTranslationZ() {
13546        return mRenderNode.getTranslationZ();
13547    }
13548
13549    /**
13550     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
13551     *
13552     * @attr ref android.R.styleable#View_translationZ
13553     */
13554    public void setTranslationZ(float translationZ) {
13555        if (translationZ != getTranslationZ()) {
13556            invalidateViewProperty(true, false);
13557            mRenderNode.setTranslationZ(translationZ);
13558            invalidateViewProperty(false, true);
13559
13560            invalidateParentIfNeededAndWasQuickRejected();
13561        }
13562    }
13563
13564    /** @hide */
13565    public void setAnimationMatrix(Matrix matrix) {
13566        invalidateViewProperty(true, false);
13567        mRenderNode.setAnimationMatrix(matrix);
13568        invalidateViewProperty(false, true);
13569
13570        invalidateParentIfNeededAndWasQuickRejected();
13571    }
13572
13573    /**
13574     * Returns the current StateListAnimator if exists.
13575     *
13576     * @return StateListAnimator or null if it does not exists
13577     * @see    #setStateListAnimator(android.animation.StateListAnimator)
13578     */
13579    public StateListAnimator getStateListAnimator() {
13580        return mStateListAnimator;
13581    }
13582
13583    /**
13584     * Attaches the provided StateListAnimator to this View.
13585     * <p>
13586     * Any previously attached StateListAnimator will be detached.
13587     *
13588     * @param stateListAnimator The StateListAnimator to update the view
13589     * @see {@link android.animation.StateListAnimator}
13590     */
13591    public void setStateListAnimator(StateListAnimator stateListAnimator) {
13592        if (mStateListAnimator == stateListAnimator) {
13593            return;
13594        }
13595        if (mStateListAnimator != null) {
13596            mStateListAnimator.setTarget(null);
13597        }
13598        mStateListAnimator = stateListAnimator;
13599        if (stateListAnimator != null) {
13600            stateListAnimator.setTarget(this);
13601            if (isAttachedToWindow()) {
13602                stateListAnimator.setState(getDrawableState());
13603            }
13604        }
13605    }
13606
13607    /**
13608     * Returns whether the Outline should be used to clip the contents of the View.
13609     * <p>
13610     * Note that this flag will only be respected if the View's Outline returns true from
13611     * {@link Outline#canClip()}.
13612     *
13613     * @see #setOutlineProvider(ViewOutlineProvider)
13614     * @see #setClipToOutline(boolean)
13615     */
13616    public final boolean getClipToOutline() {
13617        return mRenderNode.getClipToOutline();
13618    }
13619
13620    /**
13621     * Sets whether the View's Outline should be used to clip the contents of the View.
13622     * <p>
13623     * Only a single non-rectangular clip can be applied on a View at any time.
13624     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
13625     * circular reveal} animation take priority over Outline clipping, and
13626     * child Outline clipping takes priority over Outline clipping done by a
13627     * parent.
13628     * <p>
13629     * Note that this flag will only be respected if the View's Outline returns true from
13630     * {@link Outline#canClip()}.
13631     *
13632     * @see #setOutlineProvider(ViewOutlineProvider)
13633     * @see #getClipToOutline()
13634     */
13635    public void setClipToOutline(boolean clipToOutline) {
13636        damageInParent();
13637        if (getClipToOutline() != clipToOutline) {
13638            mRenderNode.setClipToOutline(clipToOutline);
13639        }
13640    }
13641
13642    // correspond to the enum values of View_outlineProvider
13643    private static final int PROVIDER_BACKGROUND = 0;
13644    private static final int PROVIDER_NONE = 1;
13645    private static final int PROVIDER_BOUNDS = 2;
13646    private static final int PROVIDER_PADDED_BOUNDS = 3;
13647    private void setOutlineProviderFromAttribute(int providerInt) {
13648        switch (providerInt) {
13649            case PROVIDER_BACKGROUND:
13650                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
13651                break;
13652            case PROVIDER_NONE:
13653                setOutlineProvider(null);
13654                break;
13655            case PROVIDER_BOUNDS:
13656                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13657                break;
13658            case PROVIDER_PADDED_BOUNDS:
13659                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13660                break;
13661        }
13662    }
13663
13664    /**
13665     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13666     * the shape of the shadow it casts, and enables outline clipping.
13667     * <p>
13668     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13669     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13670     * outline provider with this method allows this behavior to be overridden.
13671     * <p>
13672     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13673     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13674     * <p>
13675     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13676     *
13677     * @see #setClipToOutline(boolean)
13678     * @see #getClipToOutline()
13679     * @see #getOutlineProvider()
13680     */
13681    public void setOutlineProvider(ViewOutlineProvider provider) {
13682        mOutlineProvider = provider;
13683        invalidateOutline();
13684    }
13685
13686    /**
13687     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13688     * that defines the shape of the shadow it casts, and enables outline clipping.
13689     *
13690     * @see #setOutlineProvider(ViewOutlineProvider)
13691     */
13692    public ViewOutlineProvider getOutlineProvider() {
13693        return mOutlineProvider;
13694    }
13695
13696    /**
13697     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13698     *
13699     * @see #setOutlineProvider(ViewOutlineProvider)
13700     */
13701    public void invalidateOutline() {
13702        rebuildOutline();
13703
13704        notifySubtreeAccessibilityStateChangedIfNeeded();
13705        invalidateViewProperty(false, false);
13706    }
13707
13708    /**
13709     * Internal version of {@link #invalidateOutline()} which invalidates the
13710     * outline without invalidating the view itself. This is intended to be called from
13711     * within methods in the View class itself which are the result of the view being
13712     * invalidated already. For example, when we are drawing the background of a View,
13713     * we invalidate the outline in case it changed in the meantime, but we do not
13714     * need to invalidate the view because we're already drawing the background as part
13715     * of drawing the view in response to an earlier invalidation of the view.
13716     */
13717    private void rebuildOutline() {
13718        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13719        if (mAttachInfo == null) return;
13720
13721        if (mOutlineProvider == null) {
13722            // no provider, remove outline
13723            mRenderNode.setOutline(null);
13724        } else {
13725            final Outline outline = mAttachInfo.mTmpOutline;
13726            outline.setEmpty();
13727            outline.setAlpha(1.0f);
13728
13729            mOutlineProvider.getOutline(this, outline);
13730            mRenderNode.setOutline(outline);
13731        }
13732    }
13733
13734    /**
13735     * HierarchyViewer only
13736     *
13737     * @hide
13738     */
13739    @ViewDebug.ExportedProperty(category = "drawing")
13740    public boolean hasShadow() {
13741        return mRenderNode.hasShadow();
13742    }
13743
13744
13745    /** @hide */
13746    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13747        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13748        invalidateViewProperty(false, false);
13749    }
13750
13751    /**
13752     * Hit rectangle in parent's coordinates
13753     *
13754     * @param outRect The hit rectangle of the view.
13755     */
13756    public void getHitRect(Rect outRect) {
13757        if (hasIdentityMatrix() || mAttachInfo == null) {
13758            outRect.set(mLeft, mTop, mRight, mBottom);
13759        } else {
13760            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13761            tmpRect.set(0, 0, getWidth(), getHeight());
13762            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13763            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13764                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13765        }
13766    }
13767
13768    /**
13769     * Determines whether the given point, in local coordinates is inside the view.
13770     */
13771    /*package*/ final boolean pointInView(float localX, float localY) {
13772        return pointInView(localX, localY, 0);
13773    }
13774
13775    /**
13776     * Utility method to determine whether the given point, in local coordinates,
13777     * is inside the view, where the area of the view is expanded by the slop factor.
13778     * This method is called while processing touch-move events to determine if the event
13779     * is still within the view.
13780     *
13781     * @hide
13782     */
13783    public boolean pointInView(float localX, float localY, float slop) {
13784        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13785                localY < ((mBottom - mTop) + slop);
13786    }
13787
13788    /**
13789     * When a view has focus and the user navigates away from it, the next view is searched for
13790     * starting from the rectangle filled in by this method.
13791     *
13792     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13793     * of the view.  However, if your view maintains some idea of internal selection,
13794     * such as a cursor, or a selected row or column, you should override this method and
13795     * fill in a more specific rectangle.
13796     *
13797     * @param r The rectangle to fill in, in this view's coordinates.
13798     */
13799    public void getFocusedRect(Rect r) {
13800        getDrawingRect(r);
13801    }
13802
13803    /**
13804     * If some part of this view is not clipped by any of its parents, then
13805     * return that area in r in global (root) coordinates. To convert r to local
13806     * coordinates (without taking possible View rotations into account), offset
13807     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13808     * If the view is completely clipped or translated out, return false.
13809     *
13810     * @param r If true is returned, r holds the global coordinates of the
13811     *        visible portion of this view.
13812     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13813     *        between this view and its root. globalOffet may be null.
13814     * @return true if r is non-empty (i.e. part of the view is visible at the
13815     *         root level.
13816     */
13817    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13818        int width = mRight - mLeft;
13819        int height = mBottom - mTop;
13820        if (width > 0 && height > 0) {
13821            r.set(0, 0, width, height);
13822            if (globalOffset != null) {
13823                globalOffset.set(-mScrollX, -mScrollY);
13824            }
13825            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13826        }
13827        return false;
13828    }
13829
13830    public final boolean getGlobalVisibleRect(Rect r) {
13831        return getGlobalVisibleRect(r, null);
13832    }
13833
13834    public final boolean getLocalVisibleRect(Rect r) {
13835        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13836        if (getGlobalVisibleRect(r, offset)) {
13837            r.offset(-offset.x, -offset.y); // make r local
13838            return true;
13839        }
13840        return false;
13841    }
13842
13843    /**
13844     * Offset this view's vertical location by the specified number of pixels.
13845     *
13846     * @param offset the number of pixels to offset the view by
13847     */
13848    public void offsetTopAndBottom(int offset) {
13849        if (offset != 0) {
13850            final boolean matrixIsIdentity = hasIdentityMatrix();
13851            if (matrixIsIdentity) {
13852                if (isHardwareAccelerated()) {
13853                    invalidateViewProperty(false, false);
13854                } else {
13855                    final ViewParent p = mParent;
13856                    if (p != null && mAttachInfo != null) {
13857                        final Rect r = mAttachInfo.mTmpInvalRect;
13858                        int minTop;
13859                        int maxBottom;
13860                        int yLoc;
13861                        if (offset < 0) {
13862                            minTop = mTop + offset;
13863                            maxBottom = mBottom;
13864                            yLoc = offset;
13865                        } else {
13866                            minTop = mTop;
13867                            maxBottom = mBottom + offset;
13868                            yLoc = 0;
13869                        }
13870                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13871                        p.invalidateChild(this, r);
13872                    }
13873                }
13874            } else {
13875                invalidateViewProperty(false, false);
13876            }
13877
13878            mTop += offset;
13879            mBottom += offset;
13880            mRenderNode.offsetTopAndBottom(offset);
13881            if (isHardwareAccelerated()) {
13882                invalidateViewProperty(false, false);
13883                invalidateParentIfNeededAndWasQuickRejected();
13884            } else {
13885                if (!matrixIsIdentity) {
13886                    invalidateViewProperty(false, true);
13887                }
13888                invalidateParentIfNeeded();
13889            }
13890            notifySubtreeAccessibilityStateChangedIfNeeded();
13891        }
13892    }
13893
13894    /**
13895     * Offset this view's horizontal location by the specified amount of pixels.
13896     *
13897     * @param offset the number of pixels to offset the view by
13898     */
13899    public void offsetLeftAndRight(int offset) {
13900        if (offset != 0) {
13901            final boolean matrixIsIdentity = hasIdentityMatrix();
13902            if (matrixIsIdentity) {
13903                if (isHardwareAccelerated()) {
13904                    invalidateViewProperty(false, false);
13905                } else {
13906                    final ViewParent p = mParent;
13907                    if (p != null && mAttachInfo != null) {
13908                        final Rect r = mAttachInfo.mTmpInvalRect;
13909                        int minLeft;
13910                        int maxRight;
13911                        if (offset < 0) {
13912                            minLeft = mLeft + offset;
13913                            maxRight = mRight;
13914                        } else {
13915                            minLeft = mLeft;
13916                            maxRight = mRight + offset;
13917                        }
13918                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13919                        p.invalidateChild(this, r);
13920                    }
13921                }
13922            } else {
13923                invalidateViewProperty(false, false);
13924            }
13925
13926            mLeft += offset;
13927            mRight += offset;
13928            mRenderNode.offsetLeftAndRight(offset);
13929            if (isHardwareAccelerated()) {
13930                invalidateViewProperty(false, false);
13931                invalidateParentIfNeededAndWasQuickRejected();
13932            } else {
13933                if (!matrixIsIdentity) {
13934                    invalidateViewProperty(false, true);
13935                }
13936                invalidateParentIfNeeded();
13937            }
13938            notifySubtreeAccessibilityStateChangedIfNeeded();
13939        }
13940    }
13941
13942    /**
13943     * Get the LayoutParams associated with this view. All views should have
13944     * layout parameters. These supply parameters to the <i>parent</i> of this
13945     * view specifying how it should be arranged. There are many subclasses of
13946     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13947     * of ViewGroup that are responsible for arranging their children.
13948     *
13949     * This method may return null if this View is not attached to a parent
13950     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13951     * was not invoked successfully. When a View is attached to a parent
13952     * ViewGroup, this method must not return null.
13953     *
13954     * @return The LayoutParams associated with this view, or null if no
13955     *         parameters have been set yet
13956     */
13957    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13958    public ViewGroup.LayoutParams getLayoutParams() {
13959        return mLayoutParams;
13960    }
13961
13962    /**
13963     * Set the layout parameters associated with this view. These supply
13964     * parameters to the <i>parent</i> of this view specifying how it should be
13965     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13966     * correspond to the different subclasses of ViewGroup that are responsible
13967     * for arranging their children.
13968     *
13969     * @param params The layout parameters for this view, cannot be null
13970     */
13971    public void setLayoutParams(ViewGroup.LayoutParams params) {
13972        if (params == null) {
13973            throw new NullPointerException("Layout parameters cannot be null");
13974        }
13975        mLayoutParams = params;
13976        resolveLayoutParams();
13977        if (mParent instanceof ViewGroup) {
13978            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13979        }
13980        requestLayout();
13981    }
13982
13983    /**
13984     * Resolve the layout parameters depending on the resolved layout direction
13985     *
13986     * @hide
13987     */
13988    public void resolveLayoutParams() {
13989        if (mLayoutParams != null) {
13990            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13991        }
13992    }
13993
13994    /**
13995     * Set the scrolled position of your view. This will cause a call to
13996     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13997     * invalidated.
13998     * @param x the x position to scroll to
13999     * @param y the y position to scroll to
14000     */
14001    public void scrollTo(int x, int y) {
14002        if (mScrollX != x || mScrollY != y) {
14003            int oldX = mScrollX;
14004            int oldY = mScrollY;
14005            mScrollX = x;
14006            mScrollY = y;
14007            invalidateParentCaches();
14008            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
14009            if (!awakenScrollBars()) {
14010                postInvalidateOnAnimation();
14011            }
14012        }
14013    }
14014
14015    /**
14016     * Move the scrolled position of your view. This will cause a call to
14017     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14018     * invalidated.
14019     * @param x the amount of pixels to scroll by horizontally
14020     * @param y the amount of pixels to scroll by vertically
14021     */
14022    public void scrollBy(int x, int y) {
14023        scrollTo(mScrollX + x, mScrollY + y);
14024    }
14025
14026    /**
14027     * <p>Trigger the scrollbars to draw. When invoked this method starts an
14028     * animation to fade the scrollbars out after a default delay. If a subclass
14029     * provides animated scrolling, the start delay should equal the duration
14030     * of the scrolling animation.</p>
14031     *
14032     * <p>The animation starts only if at least one of the scrollbars is
14033     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
14034     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14035     * this method returns true, and false otherwise. If the animation is
14036     * started, this method calls {@link #invalidate()}; in that case the
14037     * caller should not call {@link #invalidate()}.</p>
14038     *
14039     * <p>This method should be invoked every time a subclass directly updates
14040     * the scroll parameters.</p>
14041     *
14042     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
14043     * and {@link #scrollTo(int, int)}.</p>
14044     *
14045     * @return true if the animation is played, false otherwise
14046     *
14047     * @see #awakenScrollBars(int)
14048     * @see #scrollBy(int, int)
14049     * @see #scrollTo(int, int)
14050     * @see #isHorizontalScrollBarEnabled()
14051     * @see #isVerticalScrollBarEnabled()
14052     * @see #setHorizontalScrollBarEnabled(boolean)
14053     * @see #setVerticalScrollBarEnabled(boolean)
14054     */
14055    protected boolean awakenScrollBars() {
14056        return mScrollCache != null &&
14057                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
14058    }
14059
14060    /**
14061     * Trigger the scrollbars to draw.
14062     * This method differs from awakenScrollBars() only in its default duration.
14063     * initialAwakenScrollBars() will show the scroll bars for longer than
14064     * usual to give the user more of a chance to notice them.
14065     *
14066     * @return true if the animation is played, false otherwise.
14067     */
14068    private boolean initialAwakenScrollBars() {
14069        return mScrollCache != null &&
14070                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
14071    }
14072
14073    /**
14074     * <p>
14075     * Trigger the scrollbars to draw. When invoked this method starts an
14076     * animation to fade the scrollbars out after a fixed delay. If a subclass
14077     * provides animated scrolling, the start delay should equal the duration of
14078     * the scrolling animation.
14079     * </p>
14080     *
14081     * <p>
14082     * The animation starts only if at least one of the scrollbars is enabled,
14083     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14084     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14085     * this method returns true, and false otherwise. If the animation is
14086     * started, this method calls {@link #invalidate()}; in that case the caller
14087     * should not call {@link #invalidate()}.
14088     * </p>
14089     *
14090     * <p>
14091     * This method should be invoked every time a subclass directly updates the
14092     * scroll parameters.
14093     * </p>
14094     *
14095     * @param startDelay the delay, in milliseconds, after which the animation
14096     *        should start; when the delay is 0, the animation starts
14097     *        immediately
14098     * @return true if the animation is played, false otherwise
14099     *
14100     * @see #scrollBy(int, int)
14101     * @see #scrollTo(int, int)
14102     * @see #isHorizontalScrollBarEnabled()
14103     * @see #isVerticalScrollBarEnabled()
14104     * @see #setHorizontalScrollBarEnabled(boolean)
14105     * @see #setVerticalScrollBarEnabled(boolean)
14106     */
14107    protected boolean awakenScrollBars(int startDelay) {
14108        return awakenScrollBars(startDelay, true);
14109    }
14110
14111    /**
14112     * <p>
14113     * Trigger the scrollbars to draw. When invoked this method starts an
14114     * animation to fade the scrollbars out after a fixed delay. If a subclass
14115     * provides animated scrolling, the start delay should equal the duration of
14116     * the scrolling animation.
14117     * </p>
14118     *
14119     * <p>
14120     * The animation starts only if at least one of the scrollbars is enabled,
14121     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14122     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14123     * this method returns true, and false otherwise. If the animation is
14124     * started, this method calls {@link #invalidate()} if the invalidate parameter
14125     * is set to true; in that case the caller
14126     * should not call {@link #invalidate()}.
14127     * </p>
14128     *
14129     * <p>
14130     * This method should be invoked every time a subclass directly updates the
14131     * scroll parameters.
14132     * </p>
14133     *
14134     * @param startDelay the delay, in milliseconds, after which the animation
14135     *        should start; when the delay is 0, the animation starts
14136     *        immediately
14137     *
14138     * @param invalidate Whether this method should call invalidate
14139     *
14140     * @return true if the animation is played, false otherwise
14141     *
14142     * @see #scrollBy(int, int)
14143     * @see #scrollTo(int, int)
14144     * @see #isHorizontalScrollBarEnabled()
14145     * @see #isVerticalScrollBarEnabled()
14146     * @see #setHorizontalScrollBarEnabled(boolean)
14147     * @see #setVerticalScrollBarEnabled(boolean)
14148     */
14149    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
14150        final ScrollabilityCache scrollCache = mScrollCache;
14151
14152        if (scrollCache == null || !scrollCache.fadeScrollBars) {
14153            return false;
14154        }
14155
14156        if (scrollCache.scrollBar == null) {
14157            scrollCache.scrollBar = new ScrollBarDrawable();
14158            scrollCache.scrollBar.setState(getDrawableState());
14159            scrollCache.scrollBar.setCallback(this);
14160        }
14161
14162        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
14163
14164            if (invalidate) {
14165                // Invalidate to show the scrollbars
14166                postInvalidateOnAnimation();
14167            }
14168
14169            if (scrollCache.state == ScrollabilityCache.OFF) {
14170                // FIXME: this is copied from WindowManagerService.
14171                // We should get this value from the system when it
14172                // is possible to do so.
14173                final int KEY_REPEAT_FIRST_DELAY = 750;
14174                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
14175            }
14176
14177            // Tell mScrollCache when we should start fading. This may
14178            // extend the fade start time if one was already scheduled
14179            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
14180            scrollCache.fadeStartTime = fadeStartTime;
14181            scrollCache.state = ScrollabilityCache.ON;
14182
14183            // Schedule our fader to run, unscheduling any old ones first
14184            if (mAttachInfo != null) {
14185                mAttachInfo.mHandler.removeCallbacks(scrollCache);
14186                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
14187            }
14188
14189            return true;
14190        }
14191
14192        return false;
14193    }
14194
14195    /**
14196     * Do not invalidate views which are not visible and which are not running an animation. They
14197     * will not get drawn and they should not set dirty flags as if they will be drawn
14198     */
14199    private boolean skipInvalidate() {
14200        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
14201                (!(mParent instanceof ViewGroup) ||
14202                        !((ViewGroup) mParent).isViewTransitioning(this));
14203    }
14204
14205    /**
14206     * Mark the area defined by dirty as needing to be drawn. If the view is
14207     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14208     * point in the future.
14209     * <p>
14210     * This must be called from a UI thread. To call from a non-UI thread, call
14211     * {@link #postInvalidate()}.
14212     * <p>
14213     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
14214     * {@code dirty}.
14215     *
14216     * @param dirty the rectangle representing the bounds of the dirty region
14217     */
14218    public void invalidate(Rect dirty) {
14219        final int scrollX = mScrollX;
14220        final int scrollY = mScrollY;
14221        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
14222                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
14223    }
14224
14225    /**
14226     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
14227     * coordinates of the dirty rect are relative to the view. If the view is
14228     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14229     * point in the future.
14230     * <p>
14231     * This must be called from a UI thread. To call from a non-UI thread, call
14232     * {@link #postInvalidate()}.
14233     *
14234     * @param l the left position of the dirty region
14235     * @param t the top position of the dirty region
14236     * @param r the right position of the dirty region
14237     * @param b the bottom position of the dirty region
14238     */
14239    public void invalidate(int l, int t, int r, int b) {
14240        final int scrollX = mScrollX;
14241        final int scrollY = mScrollY;
14242        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
14243    }
14244
14245    /**
14246     * Invalidate the whole view. If the view is visible,
14247     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
14248     * the future.
14249     * <p>
14250     * This must be called from a UI thread. To call from a non-UI thread, call
14251     * {@link #postInvalidate()}.
14252     */
14253    public void invalidate() {
14254        invalidate(true);
14255    }
14256
14257    /**
14258     * This is where the invalidate() work actually happens. A full invalidate()
14259     * causes the drawing cache to be invalidated, but this function can be
14260     * called with invalidateCache set to false to skip that invalidation step
14261     * for cases that do not need it (for example, a component that remains at
14262     * the same dimensions with the same content).
14263     *
14264     * @param invalidateCache Whether the drawing cache for this view should be
14265     *            invalidated as well. This is usually true for a full
14266     *            invalidate, but may be set to false if the View's contents or
14267     *            dimensions have not changed.
14268     * @hide
14269     */
14270    public void invalidate(boolean invalidateCache) {
14271        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
14272    }
14273
14274    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
14275            boolean fullInvalidate) {
14276        if (mGhostView != null) {
14277            mGhostView.invalidate(true);
14278            return;
14279        }
14280
14281        if (skipInvalidate()) {
14282            return;
14283        }
14284
14285        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
14286                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
14287                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
14288                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
14289            if (fullInvalidate) {
14290                mLastIsOpaque = isOpaque();
14291                mPrivateFlags &= ~PFLAG_DRAWN;
14292            }
14293
14294            mPrivateFlags |= PFLAG_DIRTY;
14295
14296            if (invalidateCache) {
14297                mPrivateFlags |= PFLAG_INVALIDATED;
14298                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14299            }
14300
14301            // Propagate the damage rectangle to the parent view.
14302            final AttachInfo ai = mAttachInfo;
14303            final ViewParent p = mParent;
14304            if (p != null && ai != null && l < r && t < b) {
14305                final Rect damage = ai.mTmpInvalRect;
14306                damage.set(l, t, r, b);
14307                p.invalidateChild(this, damage);
14308            }
14309
14310            // Damage the entire projection receiver, if necessary.
14311            if (mBackground != null && mBackground.isProjected()) {
14312                final View receiver = getProjectionReceiver();
14313                if (receiver != null) {
14314                    receiver.damageInParent();
14315                }
14316            }
14317        }
14318    }
14319
14320    /**
14321     * @return this view's projection receiver, or {@code null} if none exists
14322     */
14323    private View getProjectionReceiver() {
14324        ViewParent p = getParent();
14325        while (p != null && p instanceof View) {
14326            final View v = (View) p;
14327            if (v.isProjectionReceiver()) {
14328                return v;
14329            }
14330            p = p.getParent();
14331        }
14332
14333        return null;
14334    }
14335
14336    /**
14337     * @return whether the view is a projection receiver
14338     */
14339    private boolean isProjectionReceiver() {
14340        return mBackground != null;
14341    }
14342
14343    /**
14344     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
14345     * set any flags or handle all of the cases handled by the default invalidation methods.
14346     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
14347     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
14348     * walk up the hierarchy, transforming the dirty rect as necessary.
14349     *
14350     * The method also handles normal invalidation logic if display list properties are not
14351     * being used in this view. The invalidateParent and forceRedraw flags are used by that
14352     * backup approach, to handle these cases used in the various property-setting methods.
14353     *
14354     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
14355     * are not being used in this view
14356     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
14357     * list properties are not being used in this view
14358     */
14359    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
14360        if (!isHardwareAccelerated()
14361                || !mRenderNode.isValid()
14362                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
14363            if (invalidateParent) {
14364                invalidateParentCaches();
14365            }
14366            if (forceRedraw) {
14367                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14368            }
14369            invalidate(false);
14370        } else {
14371            damageInParent();
14372        }
14373    }
14374
14375    /**
14376     * Tells the parent view to damage this view's bounds.
14377     *
14378     * @hide
14379     */
14380    protected void damageInParent() {
14381        final AttachInfo ai = mAttachInfo;
14382        final ViewParent p = mParent;
14383        if (p != null && ai != null) {
14384            final Rect r = ai.mTmpInvalRect;
14385            r.set(0, 0, mRight - mLeft, mBottom - mTop);
14386            if (mParent instanceof ViewGroup) {
14387                ((ViewGroup) mParent).damageChild(this, r);
14388            } else {
14389                mParent.invalidateChild(this, r);
14390            }
14391        }
14392    }
14393
14394    /**
14395     * Utility method to transform a given Rect by the current matrix of this view.
14396     */
14397    void transformRect(final Rect rect) {
14398        if (!getMatrix().isIdentity()) {
14399            RectF boundingRect = mAttachInfo.mTmpTransformRect;
14400            boundingRect.set(rect);
14401            getMatrix().mapRect(boundingRect);
14402            rect.set((int) Math.floor(boundingRect.left),
14403                    (int) Math.floor(boundingRect.top),
14404                    (int) Math.ceil(boundingRect.right),
14405                    (int) Math.ceil(boundingRect.bottom));
14406        }
14407    }
14408
14409    /**
14410     * Used to indicate that the parent of this view should clear its caches. This functionality
14411     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14412     * which is necessary when various parent-managed properties of the view change, such as
14413     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
14414     * clears the parent caches and does not causes an invalidate event.
14415     *
14416     * @hide
14417     */
14418    protected void invalidateParentCaches() {
14419        if (mParent instanceof View) {
14420            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
14421        }
14422    }
14423
14424    /**
14425     * Used to indicate that the parent of this view should be invalidated. This functionality
14426     * is used to force the parent to rebuild its display list (when hardware-accelerated),
14427     * which is necessary when various parent-managed properties of the view change, such as
14428     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
14429     * an invalidation event to the parent.
14430     *
14431     * @hide
14432     */
14433    protected void invalidateParentIfNeeded() {
14434        if (isHardwareAccelerated() && mParent instanceof View) {
14435            ((View) mParent).invalidate(true);
14436        }
14437    }
14438
14439    /**
14440     * @hide
14441     */
14442    protected void invalidateParentIfNeededAndWasQuickRejected() {
14443        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
14444            // View was rejected last time it was drawn by its parent; this may have changed
14445            invalidateParentIfNeeded();
14446        }
14447    }
14448
14449    /**
14450     * Indicates whether this View is opaque. An opaque View guarantees that it will
14451     * draw all the pixels overlapping its bounds using a fully opaque color.
14452     *
14453     * Subclasses of View should override this method whenever possible to indicate
14454     * whether an instance is opaque. Opaque Views are treated in a special way by
14455     * the View hierarchy, possibly allowing it to perform optimizations during
14456     * invalidate/draw passes.
14457     *
14458     * @return True if this View is guaranteed to be fully opaque, false otherwise.
14459     */
14460    @ViewDebug.ExportedProperty(category = "drawing")
14461    public boolean isOpaque() {
14462        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
14463                getFinalAlpha() >= 1.0f;
14464    }
14465
14466    /**
14467     * @hide
14468     */
14469    protected void computeOpaqueFlags() {
14470        // Opaque if:
14471        //   - Has a background
14472        //   - Background is opaque
14473        //   - Doesn't have scrollbars or scrollbars overlay
14474
14475        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
14476            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
14477        } else {
14478            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
14479        }
14480
14481        final int flags = mViewFlags;
14482        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
14483                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
14484                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
14485            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
14486        } else {
14487            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
14488        }
14489    }
14490
14491    /**
14492     * @hide
14493     */
14494    protected boolean hasOpaqueScrollbars() {
14495        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
14496    }
14497
14498    /**
14499     * @return A handler associated with the thread running the View. This
14500     * handler can be used to pump events in the UI events queue.
14501     */
14502    public Handler getHandler() {
14503        final AttachInfo attachInfo = mAttachInfo;
14504        if (attachInfo != null) {
14505            return attachInfo.mHandler;
14506        }
14507        return null;
14508    }
14509
14510    /**
14511     * Returns the queue of runnable for this view.
14512     *
14513     * @return the queue of runnables for this view
14514     */
14515    private HandlerActionQueue getRunQueue() {
14516        if (mRunQueue == null) {
14517            mRunQueue = new HandlerActionQueue();
14518        }
14519        return mRunQueue;
14520    }
14521
14522    /**
14523     * Gets the view root associated with the View.
14524     * @return The view root, or null if none.
14525     * @hide
14526     */
14527    public ViewRootImpl getViewRootImpl() {
14528        if (mAttachInfo != null) {
14529            return mAttachInfo.mViewRootImpl;
14530        }
14531        return null;
14532    }
14533
14534    /**
14535     * @hide
14536     */
14537    public ThreadedRenderer getThreadedRenderer() {
14538        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
14539    }
14540
14541    /**
14542     * <p>Causes the Runnable to be added to the message queue.
14543     * The runnable will be run on the user interface thread.</p>
14544     *
14545     * @param action The Runnable that will be executed.
14546     *
14547     * @return Returns true if the Runnable was successfully placed in to the
14548     *         message queue.  Returns false on failure, usually because the
14549     *         looper processing the message queue is exiting.
14550     *
14551     * @see #postDelayed
14552     * @see #removeCallbacks
14553     */
14554    public boolean post(Runnable action) {
14555        final AttachInfo attachInfo = mAttachInfo;
14556        if (attachInfo != null) {
14557            return attachInfo.mHandler.post(action);
14558        }
14559
14560        // Postpone the runnable until we know on which thread it needs to run.
14561        // Assume that the runnable will be successfully placed after attach.
14562        getRunQueue().post(action);
14563        return true;
14564    }
14565
14566    /**
14567     * <p>Causes the Runnable to be added to the message queue, to be run
14568     * after the specified amount of time elapses.
14569     * The runnable will be run on the user interface thread.</p>
14570     *
14571     * @param action The Runnable that will be executed.
14572     * @param delayMillis The delay (in milliseconds) until the Runnable
14573     *        will be executed.
14574     *
14575     * @return true if the Runnable was successfully placed in to the
14576     *         message queue.  Returns false on failure, usually because the
14577     *         looper processing the message queue is exiting.  Note that a
14578     *         result of true does not mean the Runnable will be processed --
14579     *         if the looper is quit before the delivery time of the message
14580     *         occurs then the message will be dropped.
14581     *
14582     * @see #post
14583     * @see #removeCallbacks
14584     */
14585    public boolean postDelayed(Runnable action, long delayMillis) {
14586        final AttachInfo attachInfo = mAttachInfo;
14587        if (attachInfo != null) {
14588            return attachInfo.mHandler.postDelayed(action, delayMillis);
14589        }
14590
14591        // Postpone the runnable until we know on which thread it needs to run.
14592        // Assume that the runnable will be successfully placed after attach.
14593        getRunQueue().postDelayed(action, delayMillis);
14594        return true;
14595    }
14596
14597    /**
14598     * <p>Causes the Runnable to execute on the next animation time step.
14599     * The runnable will be run on the user interface thread.</p>
14600     *
14601     * @param action The Runnable that will be executed.
14602     *
14603     * @see #postOnAnimationDelayed
14604     * @see #removeCallbacks
14605     */
14606    public void postOnAnimation(Runnable action) {
14607        final AttachInfo attachInfo = mAttachInfo;
14608        if (attachInfo != null) {
14609            attachInfo.mViewRootImpl.mChoreographer.postCallback(
14610                    Choreographer.CALLBACK_ANIMATION, action, null);
14611        } else {
14612            // Postpone the runnable until we know
14613            // on which thread it needs to run.
14614            getRunQueue().post(action);
14615        }
14616    }
14617
14618    /**
14619     * <p>Causes the Runnable to execute on the next animation time step,
14620     * after the specified amount of time elapses.
14621     * The runnable will be run on the user interface thread.</p>
14622     *
14623     * @param action The Runnable that will be executed.
14624     * @param delayMillis The delay (in milliseconds) until the Runnable
14625     *        will be executed.
14626     *
14627     * @see #postOnAnimation
14628     * @see #removeCallbacks
14629     */
14630    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14631        final AttachInfo attachInfo = mAttachInfo;
14632        if (attachInfo != null) {
14633            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14634                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14635        } else {
14636            // Postpone the runnable until we know
14637            // on which thread it needs to run.
14638            getRunQueue().postDelayed(action, delayMillis);
14639        }
14640    }
14641
14642    /**
14643     * <p>Removes the specified Runnable from the message queue.</p>
14644     *
14645     * @param action The Runnable to remove from the message handling queue
14646     *
14647     * @return true if this view could ask the Handler to remove the Runnable,
14648     *         false otherwise. When the returned value is true, the Runnable
14649     *         may or may not have been actually removed from the message queue
14650     *         (for instance, if the Runnable was not in the queue already.)
14651     *
14652     * @see #post
14653     * @see #postDelayed
14654     * @see #postOnAnimation
14655     * @see #postOnAnimationDelayed
14656     */
14657    public boolean removeCallbacks(Runnable action) {
14658        if (action != null) {
14659            final AttachInfo attachInfo = mAttachInfo;
14660            if (attachInfo != null) {
14661                attachInfo.mHandler.removeCallbacks(action);
14662                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14663                        Choreographer.CALLBACK_ANIMATION, action, null);
14664            }
14665            getRunQueue().removeCallbacks(action);
14666        }
14667        return true;
14668    }
14669
14670    /**
14671     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14672     * Use this to invalidate the View from a non-UI thread.</p>
14673     *
14674     * <p>This method can be invoked from outside of the UI thread
14675     * only when this View is attached to a window.</p>
14676     *
14677     * @see #invalidate()
14678     * @see #postInvalidateDelayed(long)
14679     */
14680    public void postInvalidate() {
14681        postInvalidateDelayed(0);
14682    }
14683
14684    /**
14685     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14686     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14687     *
14688     * <p>This method can be invoked from outside of the UI thread
14689     * only when this View is attached to a window.</p>
14690     *
14691     * @param left The left coordinate of the rectangle to invalidate.
14692     * @param top The top coordinate of the rectangle to invalidate.
14693     * @param right The right coordinate of the rectangle to invalidate.
14694     * @param bottom The bottom coordinate of the rectangle to invalidate.
14695     *
14696     * @see #invalidate(int, int, int, int)
14697     * @see #invalidate(Rect)
14698     * @see #postInvalidateDelayed(long, int, int, int, int)
14699     */
14700    public void postInvalidate(int left, int top, int right, int bottom) {
14701        postInvalidateDelayed(0, left, top, right, bottom);
14702    }
14703
14704    /**
14705     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14706     * loop. Waits for the specified amount of time.</p>
14707     *
14708     * <p>This method can be invoked from outside of the UI thread
14709     * only when this View is attached to a window.</p>
14710     *
14711     * @param delayMilliseconds the duration in milliseconds to delay the
14712     *         invalidation by
14713     *
14714     * @see #invalidate()
14715     * @see #postInvalidate()
14716     */
14717    public void postInvalidateDelayed(long delayMilliseconds) {
14718        // We try only with the AttachInfo because there's no point in invalidating
14719        // if we are not attached to our window
14720        final AttachInfo attachInfo = mAttachInfo;
14721        if (attachInfo != null) {
14722            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14723        }
14724    }
14725
14726    /**
14727     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14728     * through the event loop. Waits for the specified amount of time.</p>
14729     *
14730     * <p>This method can be invoked from outside of the UI thread
14731     * only when this View is attached to a window.</p>
14732     *
14733     * @param delayMilliseconds the duration in milliseconds to delay the
14734     *         invalidation by
14735     * @param left The left coordinate of the rectangle to invalidate.
14736     * @param top The top coordinate of the rectangle to invalidate.
14737     * @param right The right coordinate of the rectangle to invalidate.
14738     * @param bottom The bottom coordinate of the rectangle to invalidate.
14739     *
14740     * @see #invalidate(int, int, int, int)
14741     * @see #invalidate(Rect)
14742     * @see #postInvalidate(int, int, int, int)
14743     */
14744    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14745            int right, int bottom) {
14746
14747        // We try only with the AttachInfo because there's no point in invalidating
14748        // if we are not attached to our window
14749        final AttachInfo attachInfo = mAttachInfo;
14750        if (attachInfo != null) {
14751            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14752            info.target = this;
14753            info.left = left;
14754            info.top = top;
14755            info.right = right;
14756            info.bottom = bottom;
14757
14758            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14759        }
14760    }
14761
14762    /**
14763     * <p>Cause an invalidate to happen on the next animation time step, typically the
14764     * next display frame.</p>
14765     *
14766     * <p>This method can be invoked from outside of the UI thread
14767     * only when this View is attached to a window.</p>
14768     *
14769     * @see #invalidate()
14770     */
14771    public void postInvalidateOnAnimation() {
14772        // We try only with the AttachInfo because there's no point in invalidating
14773        // if we are not attached to our window
14774        final AttachInfo attachInfo = mAttachInfo;
14775        if (attachInfo != null) {
14776            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14777        }
14778    }
14779
14780    /**
14781     * <p>Cause an invalidate of the specified area to happen on the next animation
14782     * time step, typically the next display frame.</p>
14783     *
14784     * <p>This method can be invoked from outside of the UI thread
14785     * only when this View is attached to a window.</p>
14786     *
14787     * @param left The left coordinate of the rectangle to invalidate.
14788     * @param top The top coordinate of the rectangle to invalidate.
14789     * @param right The right coordinate of the rectangle to invalidate.
14790     * @param bottom The bottom coordinate of the rectangle to invalidate.
14791     *
14792     * @see #invalidate(int, int, int, int)
14793     * @see #invalidate(Rect)
14794     */
14795    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14796        // We try only with the AttachInfo because there's no point in invalidating
14797        // if we are not attached to our window
14798        final AttachInfo attachInfo = mAttachInfo;
14799        if (attachInfo != null) {
14800            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14801            info.target = this;
14802            info.left = left;
14803            info.top = top;
14804            info.right = right;
14805            info.bottom = bottom;
14806
14807            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14808        }
14809    }
14810
14811    /**
14812     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14813     * This event is sent at most once every
14814     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14815     */
14816    private void postSendViewScrolledAccessibilityEventCallback() {
14817        if (mSendViewScrolledAccessibilityEvent == null) {
14818            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14819        }
14820        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14821            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14822            postDelayed(mSendViewScrolledAccessibilityEvent,
14823                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14824        }
14825    }
14826
14827    /**
14828     * Called by a parent to request that a child update its values for mScrollX
14829     * and mScrollY if necessary. This will typically be done if the child is
14830     * animating a scroll using a {@link android.widget.Scroller Scroller}
14831     * object.
14832     */
14833    public void computeScroll() {
14834    }
14835
14836    /**
14837     * <p>Indicate whether the horizontal edges are faded when the view is
14838     * scrolled horizontally.</p>
14839     *
14840     * @return true if the horizontal edges should are faded on scroll, false
14841     *         otherwise
14842     *
14843     * @see #setHorizontalFadingEdgeEnabled(boolean)
14844     *
14845     * @attr ref android.R.styleable#View_requiresFadingEdge
14846     */
14847    public boolean isHorizontalFadingEdgeEnabled() {
14848        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14849    }
14850
14851    /**
14852     * <p>Define whether the horizontal edges should be faded when this view
14853     * is scrolled horizontally.</p>
14854     *
14855     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14856     *                                    be faded when the view is scrolled
14857     *                                    horizontally
14858     *
14859     * @see #isHorizontalFadingEdgeEnabled()
14860     *
14861     * @attr ref android.R.styleable#View_requiresFadingEdge
14862     */
14863    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14864        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14865            if (horizontalFadingEdgeEnabled) {
14866                initScrollCache();
14867            }
14868
14869            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14870        }
14871    }
14872
14873    /**
14874     * <p>Indicate whether the vertical edges are faded when the view is
14875     * scrolled horizontally.</p>
14876     *
14877     * @return true if the vertical edges should are faded on scroll, false
14878     *         otherwise
14879     *
14880     * @see #setVerticalFadingEdgeEnabled(boolean)
14881     *
14882     * @attr ref android.R.styleable#View_requiresFadingEdge
14883     */
14884    public boolean isVerticalFadingEdgeEnabled() {
14885        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14886    }
14887
14888    /**
14889     * <p>Define whether the vertical edges should be faded when this view
14890     * is scrolled vertically.</p>
14891     *
14892     * @param verticalFadingEdgeEnabled true if the vertical edges should
14893     *                                  be faded when the view is scrolled
14894     *                                  vertically
14895     *
14896     * @see #isVerticalFadingEdgeEnabled()
14897     *
14898     * @attr ref android.R.styleable#View_requiresFadingEdge
14899     */
14900    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14901        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14902            if (verticalFadingEdgeEnabled) {
14903                initScrollCache();
14904            }
14905
14906            mViewFlags ^= FADING_EDGE_VERTICAL;
14907        }
14908    }
14909
14910    /**
14911     * Returns the strength, or intensity, of the top faded edge. The strength is
14912     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14913     * returns 0.0 or 1.0 but no value in between.
14914     *
14915     * Subclasses should override this method to provide a smoother fade transition
14916     * when scrolling occurs.
14917     *
14918     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14919     */
14920    protected float getTopFadingEdgeStrength() {
14921        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14922    }
14923
14924    /**
14925     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14926     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14927     * returns 0.0 or 1.0 but no value in between.
14928     *
14929     * Subclasses should override this method to provide a smoother fade transition
14930     * when scrolling occurs.
14931     *
14932     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14933     */
14934    protected float getBottomFadingEdgeStrength() {
14935        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14936                computeVerticalScrollRange() ? 1.0f : 0.0f;
14937    }
14938
14939    /**
14940     * Returns the strength, or intensity, of the left faded edge. The strength is
14941     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14942     * returns 0.0 or 1.0 but no value in between.
14943     *
14944     * Subclasses should override this method to provide a smoother fade transition
14945     * when scrolling occurs.
14946     *
14947     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14948     */
14949    protected float getLeftFadingEdgeStrength() {
14950        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14951    }
14952
14953    /**
14954     * Returns the strength, or intensity, of the right faded edge. The strength is
14955     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14956     * returns 0.0 or 1.0 but no value in between.
14957     *
14958     * Subclasses should override this method to provide a smoother fade transition
14959     * when scrolling occurs.
14960     *
14961     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14962     */
14963    protected float getRightFadingEdgeStrength() {
14964        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14965                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14966    }
14967
14968    /**
14969     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14970     * scrollbar is not drawn by default.</p>
14971     *
14972     * @return true if the horizontal scrollbar should be painted, false
14973     *         otherwise
14974     *
14975     * @see #setHorizontalScrollBarEnabled(boolean)
14976     */
14977    public boolean isHorizontalScrollBarEnabled() {
14978        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14979    }
14980
14981    /**
14982     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14983     * scrollbar is not drawn by default.</p>
14984     *
14985     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14986     *                                   be painted
14987     *
14988     * @see #isHorizontalScrollBarEnabled()
14989     */
14990    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14991        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14992            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14993            computeOpaqueFlags();
14994            resolvePadding();
14995        }
14996    }
14997
14998    /**
14999     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
15000     * scrollbar is not drawn by default.</p>
15001     *
15002     * @return true if the vertical scrollbar should be painted, false
15003     *         otherwise
15004     *
15005     * @see #setVerticalScrollBarEnabled(boolean)
15006     */
15007    public boolean isVerticalScrollBarEnabled() {
15008        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
15009    }
15010
15011    /**
15012     * <p>Define whether the vertical scrollbar should be drawn or not. The
15013     * scrollbar is not drawn by default.</p>
15014     *
15015     * @param verticalScrollBarEnabled true if the vertical scrollbar should
15016     *                                 be painted
15017     *
15018     * @see #isVerticalScrollBarEnabled()
15019     */
15020    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
15021        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
15022            mViewFlags ^= SCROLLBARS_VERTICAL;
15023            computeOpaqueFlags();
15024            resolvePadding();
15025        }
15026    }
15027
15028    /**
15029     * @hide
15030     */
15031    protected void recomputePadding() {
15032        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15033    }
15034
15035    /**
15036     * Define whether scrollbars will fade when the view is not scrolling.
15037     *
15038     * @param fadeScrollbars whether to enable fading
15039     *
15040     * @attr ref android.R.styleable#View_fadeScrollbars
15041     */
15042    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
15043        initScrollCache();
15044        final ScrollabilityCache scrollabilityCache = mScrollCache;
15045        scrollabilityCache.fadeScrollBars = fadeScrollbars;
15046        if (fadeScrollbars) {
15047            scrollabilityCache.state = ScrollabilityCache.OFF;
15048        } else {
15049            scrollabilityCache.state = ScrollabilityCache.ON;
15050        }
15051    }
15052
15053    /**
15054     *
15055     * Returns true if scrollbars will fade when this view is not scrolling
15056     *
15057     * @return true if scrollbar fading is enabled
15058     *
15059     * @attr ref android.R.styleable#View_fadeScrollbars
15060     */
15061    public boolean isScrollbarFadingEnabled() {
15062        return mScrollCache != null && mScrollCache.fadeScrollBars;
15063    }
15064
15065    /**
15066     *
15067     * Returns the delay before scrollbars fade.
15068     *
15069     * @return the delay before scrollbars fade
15070     *
15071     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15072     */
15073    public int getScrollBarDefaultDelayBeforeFade() {
15074        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
15075                mScrollCache.scrollBarDefaultDelayBeforeFade;
15076    }
15077
15078    /**
15079     * Define the delay before scrollbars fade.
15080     *
15081     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
15082     *
15083     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15084     */
15085    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
15086        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
15087    }
15088
15089    /**
15090     *
15091     * Returns the scrollbar fade duration.
15092     *
15093     * @return the scrollbar fade duration, in milliseconds
15094     *
15095     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15096     */
15097    public int getScrollBarFadeDuration() {
15098        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
15099                mScrollCache.scrollBarFadeDuration;
15100    }
15101
15102    /**
15103     * Define the scrollbar fade duration.
15104     *
15105     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
15106     *
15107     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15108     */
15109    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
15110        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
15111    }
15112
15113    /**
15114     *
15115     * Returns the scrollbar size.
15116     *
15117     * @return the scrollbar size
15118     *
15119     * @attr ref android.R.styleable#View_scrollbarSize
15120     */
15121    public int getScrollBarSize() {
15122        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
15123                mScrollCache.scrollBarSize;
15124    }
15125
15126    /**
15127     * Define the scrollbar size.
15128     *
15129     * @param scrollBarSize - the scrollbar size
15130     *
15131     * @attr ref android.R.styleable#View_scrollbarSize
15132     */
15133    public void setScrollBarSize(int scrollBarSize) {
15134        getScrollCache().scrollBarSize = scrollBarSize;
15135    }
15136
15137    /**
15138     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
15139     * inset. When inset, they add to the padding of the view. And the scrollbars
15140     * can be drawn inside the padding area or on the edge of the view. For example,
15141     * if a view has a background drawable and you want to draw the scrollbars
15142     * inside the padding specified by the drawable, you can use
15143     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
15144     * appear at the edge of the view, ignoring the padding, then you can use
15145     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
15146     * @param style the style of the scrollbars. Should be one of
15147     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
15148     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
15149     * @see #SCROLLBARS_INSIDE_OVERLAY
15150     * @see #SCROLLBARS_INSIDE_INSET
15151     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15152     * @see #SCROLLBARS_OUTSIDE_INSET
15153     *
15154     * @attr ref android.R.styleable#View_scrollbarStyle
15155     */
15156    public void setScrollBarStyle(@ScrollBarStyle int style) {
15157        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
15158            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
15159            computeOpaqueFlags();
15160            resolvePadding();
15161        }
15162    }
15163
15164    /**
15165     * <p>Returns the current scrollbar style.</p>
15166     * @return the current scrollbar style
15167     * @see #SCROLLBARS_INSIDE_OVERLAY
15168     * @see #SCROLLBARS_INSIDE_INSET
15169     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15170     * @see #SCROLLBARS_OUTSIDE_INSET
15171     *
15172     * @attr ref android.R.styleable#View_scrollbarStyle
15173     */
15174    @ViewDebug.ExportedProperty(mapping = {
15175            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
15176            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
15177            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
15178            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
15179    })
15180    @ScrollBarStyle
15181    public int getScrollBarStyle() {
15182        return mViewFlags & SCROLLBARS_STYLE_MASK;
15183    }
15184
15185    /**
15186     * <p>Compute the horizontal range that the horizontal scrollbar
15187     * represents.</p>
15188     *
15189     * <p>The range is expressed in arbitrary units that must be the same as the
15190     * units used by {@link #computeHorizontalScrollExtent()} and
15191     * {@link #computeHorizontalScrollOffset()}.</p>
15192     *
15193     * <p>The default range is the drawing width of this view.</p>
15194     *
15195     * @return the total horizontal range represented by the horizontal
15196     *         scrollbar
15197     *
15198     * @see #computeHorizontalScrollExtent()
15199     * @see #computeHorizontalScrollOffset()
15200     * @see android.widget.ScrollBarDrawable
15201     */
15202    protected int computeHorizontalScrollRange() {
15203        return getWidth();
15204    }
15205
15206    /**
15207     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
15208     * within the horizontal range. This value is used to compute the position
15209     * of the thumb within the scrollbar's track.</p>
15210     *
15211     * <p>The range is expressed in arbitrary units that must be the same as the
15212     * units used by {@link #computeHorizontalScrollRange()} and
15213     * {@link #computeHorizontalScrollExtent()}.</p>
15214     *
15215     * <p>The default offset is the scroll offset of this view.</p>
15216     *
15217     * @return the horizontal offset of the scrollbar's thumb
15218     *
15219     * @see #computeHorizontalScrollRange()
15220     * @see #computeHorizontalScrollExtent()
15221     * @see android.widget.ScrollBarDrawable
15222     */
15223    protected int computeHorizontalScrollOffset() {
15224        return mScrollX;
15225    }
15226
15227    /**
15228     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
15229     * within the horizontal range. This value is used to compute the length
15230     * of the thumb within the scrollbar's track.</p>
15231     *
15232     * <p>The range is expressed in arbitrary units that must be the same as the
15233     * units used by {@link #computeHorizontalScrollRange()} and
15234     * {@link #computeHorizontalScrollOffset()}.</p>
15235     *
15236     * <p>The default extent is the drawing width of this view.</p>
15237     *
15238     * @return the horizontal extent of the scrollbar's thumb
15239     *
15240     * @see #computeHorizontalScrollRange()
15241     * @see #computeHorizontalScrollOffset()
15242     * @see android.widget.ScrollBarDrawable
15243     */
15244    protected int computeHorizontalScrollExtent() {
15245        return getWidth();
15246    }
15247
15248    /**
15249     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
15250     *
15251     * <p>The range is expressed in arbitrary units that must be the same as the
15252     * units used by {@link #computeVerticalScrollExtent()} and
15253     * {@link #computeVerticalScrollOffset()}.</p>
15254     *
15255     * @return the total vertical range represented by the vertical scrollbar
15256     *
15257     * <p>The default range is the drawing height of this view.</p>
15258     *
15259     * @see #computeVerticalScrollExtent()
15260     * @see #computeVerticalScrollOffset()
15261     * @see android.widget.ScrollBarDrawable
15262     */
15263    protected int computeVerticalScrollRange() {
15264        return getHeight();
15265    }
15266
15267    /**
15268     * <p>Compute the vertical offset of the vertical scrollbar's thumb
15269     * within the horizontal range. This value is used to compute the position
15270     * of the thumb within the scrollbar's track.</p>
15271     *
15272     * <p>The range is expressed in arbitrary units that must be the same as the
15273     * units used by {@link #computeVerticalScrollRange()} and
15274     * {@link #computeVerticalScrollExtent()}.</p>
15275     *
15276     * <p>The default offset is the scroll offset of this view.</p>
15277     *
15278     * @return the vertical offset of the scrollbar's thumb
15279     *
15280     * @see #computeVerticalScrollRange()
15281     * @see #computeVerticalScrollExtent()
15282     * @see android.widget.ScrollBarDrawable
15283     */
15284    protected int computeVerticalScrollOffset() {
15285        return mScrollY;
15286    }
15287
15288    /**
15289     * <p>Compute the vertical extent of the vertical scrollbar's thumb
15290     * within the vertical range. This value is used to compute the length
15291     * of the thumb within the scrollbar's track.</p>
15292     *
15293     * <p>The range is expressed in arbitrary units that must be the same as the
15294     * units used by {@link #computeVerticalScrollRange()} and
15295     * {@link #computeVerticalScrollOffset()}.</p>
15296     *
15297     * <p>The default extent is the drawing height of this view.</p>
15298     *
15299     * @return the vertical extent of the scrollbar's thumb
15300     *
15301     * @see #computeVerticalScrollRange()
15302     * @see #computeVerticalScrollOffset()
15303     * @see android.widget.ScrollBarDrawable
15304     */
15305    protected int computeVerticalScrollExtent() {
15306        return getHeight();
15307    }
15308
15309    /**
15310     * Check if this view can be scrolled horizontally in a certain direction.
15311     *
15312     * @param direction Negative to check scrolling left, positive to check scrolling right.
15313     * @return true if this view can be scrolled in the specified direction, false otherwise.
15314     */
15315    public boolean canScrollHorizontally(int direction) {
15316        final int offset = computeHorizontalScrollOffset();
15317        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
15318        if (range == 0) return false;
15319        if (direction < 0) {
15320            return offset > 0;
15321        } else {
15322            return offset < range - 1;
15323        }
15324    }
15325
15326    /**
15327     * Check if this view can be scrolled vertically in a certain direction.
15328     *
15329     * @param direction Negative to check scrolling up, positive to check scrolling down.
15330     * @return true if this view can be scrolled in the specified direction, false otherwise.
15331     */
15332    public boolean canScrollVertically(int direction) {
15333        final int offset = computeVerticalScrollOffset();
15334        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
15335        if (range == 0) return false;
15336        if (direction < 0) {
15337            return offset > 0;
15338        } else {
15339            return offset < range - 1;
15340        }
15341    }
15342
15343    void getScrollIndicatorBounds(@NonNull Rect out) {
15344        out.left = mScrollX;
15345        out.right = mScrollX + mRight - mLeft;
15346        out.top = mScrollY;
15347        out.bottom = mScrollY + mBottom - mTop;
15348    }
15349
15350    private void onDrawScrollIndicators(Canvas c) {
15351        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
15352            // No scroll indicators enabled.
15353            return;
15354        }
15355
15356        final Drawable dr = mScrollIndicatorDrawable;
15357        if (dr == null) {
15358            // Scroll indicators aren't supported here.
15359            return;
15360        }
15361
15362        final int h = dr.getIntrinsicHeight();
15363        final int w = dr.getIntrinsicWidth();
15364        final Rect rect = mAttachInfo.mTmpInvalRect;
15365        getScrollIndicatorBounds(rect);
15366
15367        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
15368            final boolean canScrollUp = canScrollVertically(-1);
15369            if (canScrollUp) {
15370                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
15371                dr.draw(c);
15372            }
15373        }
15374
15375        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
15376            final boolean canScrollDown = canScrollVertically(1);
15377            if (canScrollDown) {
15378                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
15379                dr.draw(c);
15380            }
15381        }
15382
15383        final int leftRtl;
15384        final int rightRtl;
15385        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15386            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
15387            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
15388        } else {
15389            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
15390            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
15391        }
15392
15393        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
15394        if ((mPrivateFlags3 & leftMask) != 0) {
15395            final boolean canScrollLeft = canScrollHorizontally(-1);
15396            if (canScrollLeft) {
15397                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
15398                dr.draw(c);
15399            }
15400        }
15401
15402        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
15403        if ((mPrivateFlags3 & rightMask) != 0) {
15404            final boolean canScrollRight = canScrollHorizontally(1);
15405            if (canScrollRight) {
15406                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
15407                dr.draw(c);
15408            }
15409        }
15410    }
15411
15412    private void getHorizontalScrollBarBounds(Rect bounds) {
15413        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15414        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15415                && !isVerticalScrollBarHidden();
15416        final int size = getHorizontalScrollbarHeight();
15417        final int verticalScrollBarGap = drawVerticalScrollBar ?
15418                getVerticalScrollbarWidth() : 0;
15419        final int width = mRight - mLeft;
15420        final int height = mBottom - mTop;
15421        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
15422        bounds.left = mScrollX + (mPaddingLeft & inside);
15423        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
15424        bounds.bottom = bounds.top + size;
15425    }
15426
15427    private void getVerticalScrollBarBounds(Rect bounds) {
15428        if (mRoundScrollbarRenderer == null) {
15429            getStraightVerticalScrollBarBounds(bounds);
15430        } else {
15431            getRoundVerticalScrollBarBounds(bounds);
15432        }
15433    }
15434
15435    private void getRoundVerticalScrollBarBounds(Rect bounds) {
15436        final int width = mRight - mLeft;
15437        final int height = mBottom - mTop;
15438        // Do not take padding into account as we always want the scrollbars
15439        // to hug the screen for round wearable devices.
15440        bounds.left = mScrollX;
15441        bounds.top = mScrollY;
15442        bounds.right = bounds.left + width;
15443        bounds.bottom = mScrollY + height;
15444    }
15445
15446    private void getStraightVerticalScrollBarBounds(Rect bounds) {
15447        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
15448        final int size = getVerticalScrollbarWidth();
15449        int verticalScrollbarPosition = mVerticalScrollbarPosition;
15450        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
15451            verticalScrollbarPosition = isLayoutRtl() ?
15452                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
15453        }
15454        final int width = mRight - mLeft;
15455        final int height = mBottom - mTop;
15456        switch (verticalScrollbarPosition) {
15457            default:
15458            case SCROLLBAR_POSITION_RIGHT:
15459                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
15460                break;
15461            case SCROLLBAR_POSITION_LEFT:
15462                bounds.left = mScrollX + (mUserPaddingLeft & inside);
15463                break;
15464        }
15465        bounds.top = mScrollY + (mPaddingTop & inside);
15466        bounds.right = bounds.left + size;
15467        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
15468    }
15469
15470    /**
15471     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
15472     * scrollbars are painted only if they have been awakened first.</p>
15473     *
15474     * @param canvas the canvas on which to draw the scrollbars
15475     *
15476     * @see #awakenScrollBars(int)
15477     */
15478    protected final void onDrawScrollBars(Canvas canvas) {
15479        // scrollbars are drawn only when the animation is running
15480        final ScrollabilityCache cache = mScrollCache;
15481
15482        if (cache != null) {
15483
15484            int state = cache.state;
15485
15486            if (state == ScrollabilityCache.OFF) {
15487                return;
15488            }
15489
15490            boolean invalidate = false;
15491
15492            if (state == ScrollabilityCache.FADING) {
15493                // We're fading -- get our fade interpolation
15494                if (cache.interpolatorValues == null) {
15495                    cache.interpolatorValues = new float[1];
15496                }
15497
15498                float[] values = cache.interpolatorValues;
15499
15500                // Stops the animation if we're done
15501                if (cache.scrollBarInterpolator.timeToValues(values) ==
15502                        Interpolator.Result.FREEZE_END) {
15503                    cache.state = ScrollabilityCache.OFF;
15504                } else {
15505                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
15506                }
15507
15508                // This will make the scroll bars inval themselves after
15509                // drawing. We only want this when we're fading so that
15510                // we prevent excessive redraws
15511                invalidate = true;
15512            } else {
15513                // We're just on -- but we may have been fading before so
15514                // reset alpha
15515                cache.scrollBar.mutate().setAlpha(255);
15516            }
15517
15518            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
15519            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
15520                    && !isVerticalScrollBarHidden();
15521
15522            // Fork out the scroll bar drawing for round wearable devices.
15523            if (mRoundScrollbarRenderer != null) {
15524                if (drawVerticalScrollBar) {
15525                    final Rect bounds = cache.mScrollBarBounds;
15526                    getVerticalScrollBarBounds(bounds);
15527                    mRoundScrollbarRenderer.drawRoundScrollbars(
15528                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
15529                    if (invalidate) {
15530                        invalidate();
15531                    }
15532                }
15533                // Do not draw horizontal scroll bars for round wearable devices.
15534            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
15535                final ScrollBarDrawable scrollBar = cache.scrollBar;
15536
15537                if (drawHorizontalScrollBar) {
15538                    scrollBar.setParameters(computeHorizontalScrollRange(),
15539                            computeHorizontalScrollOffset(),
15540                            computeHorizontalScrollExtent(), false);
15541                    final Rect bounds = cache.mScrollBarBounds;
15542                    getHorizontalScrollBarBounds(bounds);
15543                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15544                            bounds.right, bounds.bottom);
15545                    if (invalidate) {
15546                        invalidate(bounds);
15547                    }
15548                }
15549
15550                if (drawVerticalScrollBar) {
15551                    scrollBar.setParameters(computeVerticalScrollRange(),
15552                            computeVerticalScrollOffset(),
15553                            computeVerticalScrollExtent(), true);
15554                    final Rect bounds = cache.mScrollBarBounds;
15555                    getVerticalScrollBarBounds(bounds);
15556                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
15557                            bounds.right, bounds.bottom);
15558                    if (invalidate) {
15559                        invalidate(bounds);
15560                    }
15561                }
15562            }
15563        }
15564    }
15565
15566    /**
15567     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
15568     * FastScroller is visible.
15569     * @return whether to temporarily hide the vertical scrollbar
15570     * @hide
15571     */
15572    protected boolean isVerticalScrollBarHidden() {
15573        return false;
15574    }
15575
15576    /**
15577     * <p>Draw the horizontal scrollbar if
15578     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
15579     *
15580     * @param canvas the canvas on which to draw the scrollbar
15581     * @param scrollBar the scrollbar's drawable
15582     *
15583     * @see #isHorizontalScrollBarEnabled()
15584     * @see #computeHorizontalScrollRange()
15585     * @see #computeHorizontalScrollExtent()
15586     * @see #computeHorizontalScrollOffset()
15587     * @see android.widget.ScrollBarDrawable
15588     * @hide
15589     */
15590    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
15591            int l, int t, int r, int b) {
15592        scrollBar.setBounds(l, t, r, b);
15593        scrollBar.draw(canvas);
15594    }
15595
15596    /**
15597     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
15598     * returns true.</p>
15599     *
15600     * @param canvas the canvas on which to draw the scrollbar
15601     * @param scrollBar the scrollbar's drawable
15602     *
15603     * @see #isVerticalScrollBarEnabled()
15604     * @see #computeVerticalScrollRange()
15605     * @see #computeVerticalScrollExtent()
15606     * @see #computeVerticalScrollOffset()
15607     * @see android.widget.ScrollBarDrawable
15608     * @hide
15609     */
15610    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
15611            int l, int t, int r, int b) {
15612        scrollBar.setBounds(l, t, r, b);
15613        scrollBar.draw(canvas);
15614    }
15615
15616    /**
15617     * Implement this to do your drawing.
15618     *
15619     * @param canvas the canvas on which the background will be drawn
15620     */
15621    protected void onDraw(Canvas canvas) {
15622    }
15623
15624    /*
15625     * Caller is responsible for calling requestLayout if necessary.
15626     * (This allows addViewInLayout to not request a new layout.)
15627     */
15628    void assignParent(ViewParent parent) {
15629        if (mParent == null) {
15630            mParent = parent;
15631        } else if (parent == null) {
15632            mParent = null;
15633        } else {
15634            throw new RuntimeException("view " + this + " being added, but"
15635                    + " it already has a parent");
15636        }
15637    }
15638
15639    /**
15640     * This is called when the view is attached to a window.  At this point it
15641     * has a Surface and will start drawing.  Note that this function is
15642     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15643     * however it may be called any time before the first onDraw -- including
15644     * before or after {@link #onMeasure(int, int)}.
15645     *
15646     * @see #onDetachedFromWindow()
15647     */
15648    @CallSuper
15649    protected void onAttachedToWindow() {
15650        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15651            mParent.requestTransparentRegion(this);
15652        }
15653
15654        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15655
15656        jumpDrawablesToCurrentState();
15657
15658        resetSubtreeAccessibilityStateChanged();
15659
15660        // rebuild, since Outline not maintained while View is detached
15661        rebuildOutline();
15662
15663        if (isFocused()) {
15664            InputMethodManager imm = InputMethodManager.peekInstance();
15665            if (imm != null) {
15666                imm.focusIn(this);
15667            }
15668        }
15669    }
15670
15671    /**
15672     * Resolve all RTL related properties.
15673     *
15674     * @return true if resolution of RTL properties has been done
15675     *
15676     * @hide
15677     */
15678    public boolean resolveRtlPropertiesIfNeeded() {
15679        if (!needRtlPropertiesResolution()) return false;
15680
15681        // Order is important here: LayoutDirection MUST be resolved first
15682        if (!isLayoutDirectionResolved()) {
15683            resolveLayoutDirection();
15684            resolveLayoutParams();
15685        }
15686        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15687        if (!isTextDirectionResolved()) {
15688            resolveTextDirection();
15689        }
15690        if (!isTextAlignmentResolved()) {
15691            resolveTextAlignment();
15692        }
15693        // Should resolve Drawables before Padding because we need the layout direction of the
15694        // Drawable to correctly resolve Padding.
15695        if (!areDrawablesResolved()) {
15696            resolveDrawables();
15697        }
15698        if (!isPaddingResolved()) {
15699            resolvePadding();
15700        }
15701        onRtlPropertiesChanged(getLayoutDirection());
15702        return true;
15703    }
15704
15705    /**
15706     * Reset resolution of all RTL related properties.
15707     *
15708     * @hide
15709     */
15710    public void resetRtlProperties() {
15711        resetResolvedLayoutDirection();
15712        resetResolvedTextDirection();
15713        resetResolvedTextAlignment();
15714        resetResolvedPadding();
15715        resetResolvedDrawables();
15716    }
15717
15718    /**
15719     * @see #onScreenStateChanged(int)
15720     */
15721    void dispatchScreenStateChanged(int screenState) {
15722        onScreenStateChanged(screenState);
15723    }
15724
15725    /**
15726     * This method is called whenever the state of the screen this view is
15727     * attached to changes. A state change will usually occurs when the screen
15728     * turns on or off (whether it happens automatically or the user does it
15729     * manually.)
15730     *
15731     * @param screenState The new state of the screen. Can be either
15732     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15733     */
15734    public void onScreenStateChanged(int screenState) {
15735    }
15736
15737    /**
15738     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15739     */
15740    private boolean hasRtlSupport() {
15741        return mContext.getApplicationInfo().hasRtlSupport();
15742    }
15743
15744    /**
15745     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15746     * RTL not supported)
15747     */
15748    private boolean isRtlCompatibilityMode() {
15749        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15750        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15751    }
15752
15753    /**
15754     * @return true if RTL properties need resolution.
15755     *
15756     */
15757    private boolean needRtlPropertiesResolution() {
15758        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15759    }
15760
15761    /**
15762     * Called when any RTL property (layout direction or text direction or text alignment) has
15763     * been changed.
15764     *
15765     * Subclasses need to override this method to take care of cached information that depends on the
15766     * resolved layout direction, or to inform child views that inherit their layout direction.
15767     *
15768     * The default implementation does nothing.
15769     *
15770     * @param layoutDirection the direction of the layout
15771     *
15772     * @see #LAYOUT_DIRECTION_LTR
15773     * @see #LAYOUT_DIRECTION_RTL
15774     */
15775    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15776    }
15777
15778    /**
15779     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15780     * that the parent directionality can and will be resolved before its children.
15781     *
15782     * @return true if resolution has been done, false otherwise.
15783     *
15784     * @hide
15785     */
15786    public boolean resolveLayoutDirection() {
15787        // Clear any previous layout direction resolution
15788        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15789
15790        if (hasRtlSupport()) {
15791            // Set resolved depending on layout direction
15792            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15793                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15794                case LAYOUT_DIRECTION_INHERIT:
15795                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15796                    // later to get the correct resolved value
15797                    if (!canResolveLayoutDirection()) return false;
15798
15799                    // Parent has not yet resolved, LTR is still the default
15800                    try {
15801                        if (!mParent.isLayoutDirectionResolved()) return false;
15802
15803                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15804                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15805                        }
15806                    } catch (AbstractMethodError e) {
15807                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15808                                " does not fully implement ViewParent", e);
15809                    }
15810                    break;
15811                case LAYOUT_DIRECTION_RTL:
15812                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15813                    break;
15814                case LAYOUT_DIRECTION_LOCALE:
15815                    if((LAYOUT_DIRECTION_RTL ==
15816                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15817                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15818                    }
15819                    break;
15820                default:
15821                    // Nothing to do, LTR by default
15822            }
15823        }
15824
15825        // Set to resolved
15826        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15827        return true;
15828    }
15829
15830    /**
15831     * Check if layout direction resolution can be done.
15832     *
15833     * @return true if layout direction resolution can be done otherwise return false.
15834     */
15835    public boolean canResolveLayoutDirection() {
15836        switch (getRawLayoutDirection()) {
15837            case LAYOUT_DIRECTION_INHERIT:
15838                if (mParent != null) {
15839                    try {
15840                        return mParent.canResolveLayoutDirection();
15841                    } catch (AbstractMethodError e) {
15842                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15843                                " does not fully implement ViewParent", e);
15844                    }
15845                }
15846                return false;
15847
15848            default:
15849                return true;
15850        }
15851    }
15852
15853    /**
15854     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15855     * {@link #onMeasure(int, int)}.
15856     *
15857     * @hide
15858     */
15859    public void resetResolvedLayoutDirection() {
15860        // Reset the current resolved bits
15861        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15862    }
15863
15864    /**
15865     * @return true if the layout direction is inherited.
15866     *
15867     * @hide
15868     */
15869    public boolean isLayoutDirectionInherited() {
15870        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15871    }
15872
15873    /**
15874     * @return true if layout direction has been resolved.
15875     */
15876    public boolean isLayoutDirectionResolved() {
15877        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15878    }
15879
15880    /**
15881     * Return if padding has been resolved
15882     *
15883     * @hide
15884     */
15885    boolean isPaddingResolved() {
15886        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15887    }
15888
15889    /**
15890     * Resolves padding depending on layout direction, if applicable, and
15891     * recomputes internal padding values to adjust for scroll bars.
15892     *
15893     * @hide
15894     */
15895    public void resolvePadding() {
15896        final int resolvedLayoutDirection = getLayoutDirection();
15897
15898        if (!isRtlCompatibilityMode()) {
15899            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15900            // If start / end padding are defined, they will be resolved (hence overriding) to
15901            // left / right or right / left depending on the resolved layout direction.
15902            // If start / end padding are not defined, use the left / right ones.
15903            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15904                Rect padding = sThreadLocal.get();
15905                if (padding == null) {
15906                    padding = new Rect();
15907                    sThreadLocal.set(padding);
15908                }
15909                mBackground.getPadding(padding);
15910                if (!mLeftPaddingDefined) {
15911                    mUserPaddingLeftInitial = padding.left;
15912                }
15913                if (!mRightPaddingDefined) {
15914                    mUserPaddingRightInitial = padding.right;
15915                }
15916            }
15917            switch (resolvedLayoutDirection) {
15918                case LAYOUT_DIRECTION_RTL:
15919                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15920                        mUserPaddingRight = mUserPaddingStart;
15921                    } else {
15922                        mUserPaddingRight = mUserPaddingRightInitial;
15923                    }
15924                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15925                        mUserPaddingLeft = mUserPaddingEnd;
15926                    } else {
15927                        mUserPaddingLeft = mUserPaddingLeftInitial;
15928                    }
15929                    break;
15930                case LAYOUT_DIRECTION_LTR:
15931                default:
15932                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15933                        mUserPaddingLeft = mUserPaddingStart;
15934                    } else {
15935                        mUserPaddingLeft = mUserPaddingLeftInitial;
15936                    }
15937                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15938                        mUserPaddingRight = mUserPaddingEnd;
15939                    } else {
15940                        mUserPaddingRight = mUserPaddingRightInitial;
15941                    }
15942            }
15943
15944            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15945        }
15946
15947        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15948        onRtlPropertiesChanged(resolvedLayoutDirection);
15949
15950        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15951    }
15952
15953    /**
15954     * Reset the resolved layout direction.
15955     *
15956     * @hide
15957     */
15958    public void resetResolvedPadding() {
15959        resetResolvedPaddingInternal();
15960    }
15961
15962    /**
15963     * Used when we only want to reset *this* view's padding and not trigger overrides
15964     * in ViewGroup that reset children too.
15965     */
15966    void resetResolvedPaddingInternal() {
15967        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15968    }
15969
15970    /**
15971     * This is called when the view is detached from a window.  At this point it
15972     * no longer has a surface for drawing.
15973     *
15974     * @see #onAttachedToWindow()
15975     */
15976    @CallSuper
15977    protected void onDetachedFromWindow() {
15978    }
15979
15980    /**
15981     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15982     * after onDetachedFromWindow().
15983     *
15984     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15985     * The super method should be called at the end of the overridden method to ensure
15986     * subclasses are destroyed first
15987     *
15988     * @hide
15989     */
15990    @CallSuper
15991    protected void onDetachedFromWindowInternal() {
15992        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15993        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15994        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15995
15996        removeUnsetPressCallback();
15997        removeLongPressCallback();
15998        removePerformClickCallback();
15999        removeSendViewScrolledAccessibilityEventCallback();
16000        stopNestedScroll();
16001
16002        // Anything that started animating right before detach should already
16003        // be in its final state when re-attached.
16004        jumpDrawablesToCurrentState();
16005
16006        destroyDrawingCache();
16007
16008        cleanupDraw();
16009        mCurrentAnimation = null;
16010
16011        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
16012            hideTooltip();
16013        }
16014    }
16015
16016    private void cleanupDraw() {
16017        resetDisplayList();
16018        if (mAttachInfo != null) {
16019            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
16020        }
16021    }
16022
16023    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
16024    }
16025
16026    /**
16027     * @return The number of times this view has been attached to a window
16028     */
16029    protected int getWindowAttachCount() {
16030        return mWindowAttachCount;
16031    }
16032
16033    /**
16034     * Retrieve a unique token identifying the window this view is attached to.
16035     * @return Return the window's token for use in
16036     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
16037     */
16038    public IBinder getWindowToken() {
16039        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
16040    }
16041
16042    /**
16043     * Retrieve the {@link WindowId} for the window this view is
16044     * currently attached to.
16045     */
16046    public WindowId getWindowId() {
16047        if (mAttachInfo == null) {
16048            return null;
16049        }
16050        if (mAttachInfo.mWindowId == null) {
16051            try {
16052                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
16053                        mAttachInfo.mWindowToken);
16054                mAttachInfo.mWindowId = new WindowId(
16055                        mAttachInfo.mIWindowId);
16056            } catch (RemoteException e) {
16057            }
16058        }
16059        return mAttachInfo.mWindowId;
16060    }
16061
16062    /**
16063     * Retrieve a unique token identifying the top-level "real" window of
16064     * the window that this view is attached to.  That is, this is like
16065     * {@link #getWindowToken}, except if the window this view in is a panel
16066     * window (attached to another containing window), then the token of
16067     * the containing window is returned instead.
16068     *
16069     * @return Returns the associated window token, either
16070     * {@link #getWindowToken()} or the containing window's token.
16071     */
16072    public IBinder getApplicationWindowToken() {
16073        AttachInfo ai = mAttachInfo;
16074        if (ai != null) {
16075            IBinder appWindowToken = ai.mPanelParentWindowToken;
16076            if (appWindowToken == null) {
16077                appWindowToken = ai.mWindowToken;
16078            }
16079            return appWindowToken;
16080        }
16081        return null;
16082    }
16083
16084    /**
16085     * Gets the logical display to which the view's window has been attached.
16086     *
16087     * @return The logical display, or null if the view is not currently attached to a window.
16088     */
16089    public Display getDisplay() {
16090        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
16091    }
16092
16093    /**
16094     * Retrieve private session object this view hierarchy is using to
16095     * communicate with the window manager.
16096     * @return the session object to communicate with the window manager
16097     */
16098    /*package*/ IWindowSession getWindowSession() {
16099        return mAttachInfo != null ? mAttachInfo.mSession : null;
16100    }
16101
16102    /**
16103     * Return the visibility value of the least visible component passed.
16104     */
16105    int combineVisibility(int vis1, int vis2) {
16106        // This works because VISIBLE < INVISIBLE < GONE.
16107        return Math.max(vis1, vis2);
16108    }
16109
16110    /**
16111     * @param info the {@link android.view.View.AttachInfo} to associated with
16112     *        this view
16113     */
16114    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
16115        mAttachInfo = info;
16116        if (mOverlay != null) {
16117            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
16118        }
16119        mWindowAttachCount++;
16120        // We will need to evaluate the drawable state at least once.
16121        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16122        if (mFloatingTreeObserver != null) {
16123            info.mTreeObserver.merge(mFloatingTreeObserver);
16124            mFloatingTreeObserver = null;
16125        }
16126
16127        registerPendingFrameMetricsObservers();
16128
16129        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
16130            mAttachInfo.mScrollContainers.add(this);
16131            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
16132        }
16133        // Transfer all pending runnables.
16134        if (mRunQueue != null) {
16135            mRunQueue.executeActions(info.mHandler);
16136            mRunQueue = null;
16137        }
16138        performCollectViewAttributes(mAttachInfo, visibility);
16139        onAttachedToWindow();
16140
16141        ListenerInfo li = mListenerInfo;
16142        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16143                li != null ? li.mOnAttachStateChangeListeners : null;
16144        if (listeners != null && listeners.size() > 0) {
16145            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16146            // perform the dispatching. The iterator is a safe guard against listeners that
16147            // could mutate the list by calling the various add/remove methods. This prevents
16148            // the array from being modified while we iterate it.
16149            for (OnAttachStateChangeListener listener : listeners) {
16150                listener.onViewAttachedToWindow(this);
16151            }
16152        }
16153
16154        int vis = info.mWindowVisibility;
16155        if (vis != GONE) {
16156            onWindowVisibilityChanged(vis);
16157            if (isShown()) {
16158                // Calling onVisibilityAggregated directly here since the subtree will also
16159                // receive dispatchAttachedToWindow and this same call
16160                onVisibilityAggregated(vis == VISIBLE);
16161            }
16162        }
16163
16164        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
16165        // As all views in the subtree will already receive dispatchAttachedToWindow
16166        // traversing the subtree again here is not desired.
16167        onVisibilityChanged(this, visibility);
16168
16169        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
16170            // If nobody has evaluated the drawable state yet, then do it now.
16171            refreshDrawableState();
16172        }
16173        needGlobalAttributesUpdate(false);
16174    }
16175
16176    void dispatchDetachedFromWindow() {
16177        AttachInfo info = mAttachInfo;
16178        if (info != null) {
16179            int vis = info.mWindowVisibility;
16180            if (vis != GONE) {
16181                onWindowVisibilityChanged(GONE);
16182                if (isShown()) {
16183                    // Invoking onVisibilityAggregated directly here since the subtree
16184                    // will also receive detached from window
16185                    onVisibilityAggregated(false);
16186                }
16187            }
16188        }
16189
16190        onDetachedFromWindow();
16191        onDetachedFromWindowInternal();
16192
16193        InputMethodManager imm = InputMethodManager.peekInstance();
16194        if (imm != null) {
16195            imm.onViewDetachedFromWindow(this);
16196        }
16197
16198        ListenerInfo li = mListenerInfo;
16199        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16200                li != null ? li.mOnAttachStateChangeListeners : null;
16201        if (listeners != null && listeners.size() > 0) {
16202            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16203            // perform the dispatching. The iterator is a safe guard against listeners that
16204            // could mutate the list by calling the various add/remove methods. This prevents
16205            // the array from being modified while we iterate it.
16206            for (OnAttachStateChangeListener listener : listeners) {
16207                listener.onViewDetachedFromWindow(this);
16208            }
16209        }
16210
16211        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
16212            mAttachInfo.mScrollContainers.remove(this);
16213            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
16214        }
16215
16216        mAttachInfo = null;
16217        if (mOverlay != null) {
16218            mOverlay.getOverlayView().dispatchDetachedFromWindow();
16219        }
16220    }
16221
16222    /**
16223     * Cancel any deferred high-level input events that were previously posted to the event queue.
16224     *
16225     * <p>Many views post high-level events such as click handlers to the event queue
16226     * to run deferred in order to preserve a desired user experience - clearing visible
16227     * pressed states before executing, etc. This method will abort any events of this nature
16228     * that are currently in flight.</p>
16229     *
16230     * <p>Custom views that generate their own high-level deferred input events should override
16231     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
16232     *
16233     * <p>This will also cancel pending input events for any child views.</p>
16234     *
16235     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
16236     * This will not impact newer events posted after this call that may occur as a result of
16237     * lower-level input events still waiting in the queue. If you are trying to prevent
16238     * double-submitted  events for the duration of some sort of asynchronous transaction
16239     * you should also take other steps to protect against unexpected double inputs e.g. calling
16240     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
16241     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
16242     */
16243    public final void cancelPendingInputEvents() {
16244        dispatchCancelPendingInputEvents();
16245    }
16246
16247    /**
16248     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
16249     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
16250     */
16251    void dispatchCancelPendingInputEvents() {
16252        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
16253        onCancelPendingInputEvents();
16254        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
16255            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
16256                    " did not call through to super.onCancelPendingInputEvents()");
16257        }
16258    }
16259
16260    /**
16261     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
16262     * a parent view.
16263     *
16264     * <p>This method is responsible for removing any pending high-level input events that were
16265     * posted to the event queue to run later. Custom view classes that post their own deferred
16266     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
16267     * {@link android.os.Handler} should override this method, call
16268     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
16269     * </p>
16270     */
16271    public void onCancelPendingInputEvents() {
16272        removePerformClickCallback();
16273        cancelLongPress();
16274        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
16275    }
16276
16277    /**
16278     * Store this view hierarchy's frozen state into the given container.
16279     *
16280     * @param container The SparseArray in which to save the view's state.
16281     *
16282     * @see #restoreHierarchyState(android.util.SparseArray)
16283     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16284     * @see #onSaveInstanceState()
16285     */
16286    public void saveHierarchyState(SparseArray<Parcelable> container) {
16287        dispatchSaveInstanceState(container);
16288    }
16289
16290    /**
16291     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
16292     * this view and its children. May be overridden to modify how freezing happens to a
16293     * view's children; for example, some views may want to not store state for their children.
16294     *
16295     * @param container The SparseArray in which to save the view's state.
16296     *
16297     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16298     * @see #saveHierarchyState(android.util.SparseArray)
16299     * @see #onSaveInstanceState()
16300     */
16301    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
16302        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
16303            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16304            Parcelable state = onSaveInstanceState();
16305            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16306                throw new IllegalStateException(
16307                        "Derived class did not call super.onSaveInstanceState()");
16308            }
16309            if (state != null) {
16310                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
16311                // + ": " + state);
16312                container.put(mID, state);
16313            }
16314        }
16315    }
16316
16317    /**
16318     * Hook allowing a view to generate a representation of its internal state
16319     * that can later be used to create a new instance with that same state.
16320     * This state should only contain information that is not persistent or can
16321     * not be reconstructed later. For example, you will never store your
16322     * current position on screen because that will be computed again when a
16323     * new instance of the view is placed in its view hierarchy.
16324     * <p>
16325     * Some examples of things you may store here: the current cursor position
16326     * in a text view (but usually not the text itself since that is stored in a
16327     * content provider or other persistent storage), the currently selected
16328     * item in a list view.
16329     *
16330     * @return Returns a Parcelable object containing the view's current dynamic
16331     *         state, or null if there is nothing interesting to save. The
16332     *         default implementation returns null.
16333     * @see #onRestoreInstanceState(android.os.Parcelable)
16334     * @see #saveHierarchyState(android.util.SparseArray)
16335     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16336     * @see #setSaveEnabled(boolean)
16337     */
16338    @CallSuper
16339    protected Parcelable onSaveInstanceState() {
16340        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16341        if (mStartActivityRequestWho != null) {
16342            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
16343            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
16344            return state;
16345        }
16346        return BaseSavedState.EMPTY_STATE;
16347    }
16348
16349    /**
16350     * Restore this view hierarchy's frozen state from the given container.
16351     *
16352     * @param container The SparseArray which holds previously frozen states.
16353     *
16354     * @see #saveHierarchyState(android.util.SparseArray)
16355     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16356     * @see #onRestoreInstanceState(android.os.Parcelable)
16357     */
16358    public void restoreHierarchyState(SparseArray<Parcelable> container) {
16359        dispatchRestoreInstanceState(container);
16360    }
16361
16362    /**
16363     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
16364     * state for this view and its children. May be overridden to modify how restoring
16365     * happens to a view's children; for example, some views may want to not store state
16366     * for their children.
16367     *
16368     * @param container The SparseArray which holds previously saved state.
16369     *
16370     * @see #dispatchSaveInstanceState(android.util.SparseArray)
16371     * @see #restoreHierarchyState(android.util.SparseArray)
16372     * @see #onRestoreInstanceState(android.os.Parcelable)
16373     */
16374    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
16375        if (mID != NO_ID) {
16376            Parcelable state = container.get(mID);
16377            if (state != null) {
16378                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
16379                // + ": " + state);
16380                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
16381                onRestoreInstanceState(state);
16382                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
16383                    throw new IllegalStateException(
16384                            "Derived class did not call super.onRestoreInstanceState()");
16385                }
16386            }
16387        }
16388    }
16389
16390    /**
16391     * Hook allowing a view to re-apply a representation of its internal state that had previously
16392     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
16393     * null state.
16394     *
16395     * @param state The frozen state that had previously been returned by
16396     *        {@link #onSaveInstanceState}.
16397     *
16398     * @see #onSaveInstanceState()
16399     * @see #restoreHierarchyState(android.util.SparseArray)
16400     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
16401     */
16402    @CallSuper
16403    protected void onRestoreInstanceState(Parcelable state) {
16404        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
16405        if (state != null && !(state instanceof AbsSavedState)) {
16406            throw new IllegalArgumentException("Wrong state class, expecting View State but "
16407                    + "received " + state.getClass().toString() + " instead. This usually happens "
16408                    + "when two views of different type have the same id in the same hierarchy. "
16409                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
16410                    + "other views do not use the same id.");
16411        }
16412        if (state != null && state instanceof BaseSavedState) {
16413            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
16414        }
16415    }
16416
16417    /**
16418     * <p>Return the time at which the drawing of the view hierarchy started.</p>
16419     *
16420     * @return the drawing start time in milliseconds
16421     */
16422    public long getDrawingTime() {
16423        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
16424    }
16425
16426    /**
16427     * <p>Enables or disables the duplication of the parent's state into this view. When
16428     * duplication is enabled, this view gets its drawable state from its parent rather
16429     * than from its own internal properties.</p>
16430     *
16431     * <p>Note: in the current implementation, setting this property to true after the
16432     * view was added to a ViewGroup might have no effect at all. This property should
16433     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
16434     *
16435     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
16436     * property is enabled, an exception will be thrown.</p>
16437     *
16438     * <p>Note: if the child view uses and updates additional states which are unknown to the
16439     * parent, these states should not be affected by this method.</p>
16440     *
16441     * @param enabled True to enable duplication of the parent's drawable state, false
16442     *                to disable it.
16443     *
16444     * @see #getDrawableState()
16445     * @see #isDuplicateParentStateEnabled()
16446     */
16447    public void setDuplicateParentStateEnabled(boolean enabled) {
16448        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
16449    }
16450
16451    /**
16452     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
16453     *
16454     * @return True if this view's drawable state is duplicated from the parent,
16455     *         false otherwise
16456     *
16457     * @see #getDrawableState()
16458     * @see #setDuplicateParentStateEnabled(boolean)
16459     */
16460    public boolean isDuplicateParentStateEnabled() {
16461        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
16462    }
16463
16464    /**
16465     * <p>Specifies the type of layer backing this view. The layer can be
16466     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16467     * {@link #LAYER_TYPE_HARDWARE}.</p>
16468     *
16469     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16470     * instance that controls how the layer is composed on screen. The following
16471     * properties of the paint are taken into account when composing the layer:</p>
16472     * <ul>
16473     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16474     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16475     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16476     * </ul>
16477     *
16478     * <p>If this view has an alpha value set to < 1.0 by calling
16479     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
16480     * by this view's alpha value.</p>
16481     *
16482     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
16483     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
16484     * for more information on when and how to use layers.</p>
16485     *
16486     * @param layerType The type of layer to use with this view, must be one of
16487     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16488     *        {@link #LAYER_TYPE_HARDWARE}
16489     * @param paint The paint used to compose the layer. This argument is optional
16490     *        and can be null. It is ignored when the layer type is
16491     *        {@link #LAYER_TYPE_NONE}
16492     *
16493     * @see #getLayerType()
16494     * @see #LAYER_TYPE_NONE
16495     * @see #LAYER_TYPE_SOFTWARE
16496     * @see #LAYER_TYPE_HARDWARE
16497     * @see #setAlpha(float)
16498     *
16499     * @attr ref android.R.styleable#View_layerType
16500     */
16501    public void setLayerType(int layerType, @Nullable Paint paint) {
16502        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
16503            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
16504                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
16505        }
16506
16507        boolean typeChanged = mRenderNode.setLayerType(layerType);
16508
16509        if (!typeChanged) {
16510            setLayerPaint(paint);
16511            return;
16512        }
16513
16514        if (layerType != LAYER_TYPE_SOFTWARE) {
16515            // Destroy any previous software drawing cache if present
16516            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
16517            // drawing cache created in View#draw when drawing to a SW canvas.
16518            destroyDrawingCache();
16519        }
16520
16521        mLayerType = layerType;
16522        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
16523        mRenderNode.setLayerPaint(mLayerPaint);
16524
16525        // draw() behaves differently if we are on a layer, so we need to
16526        // invalidate() here
16527        invalidateParentCaches();
16528        invalidate(true);
16529    }
16530
16531    /**
16532     * Updates the {@link Paint} object used with the current layer (used only if the current
16533     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
16534     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
16535     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
16536     * ensure that the view gets redrawn immediately.
16537     *
16538     * <p>A layer is associated with an optional {@link android.graphics.Paint}
16539     * instance that controls how the layer is composed on screen. The following
16540     * properties of the paint are taken into account when composing the layer:</p>
16541     * <ul>
16542     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
16543     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
16544     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
16545     * </ul>
16546     *
16547     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
16548     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
16549     *
16550     * @param paint The paint used to compose the layer. This argument is optional
16551     *        and can be null. It is ignored when the layer type is
16552     *        {@link #LAYER_TYPE_NONE}
16553     *
16554     * @see #setLayerType(int, android.graphics.Paint)
16555     */
16556    public void setLayerPaint(@Nullable Paint paint) {
16557        int layerType = getLayerType();
16558        if (layerType != LAYER_TYPE_NONE) {
16559            mLayerPaint = paint;
16560            if (layerType == LAYER_TYPE_HARDWARE) {
16561                if (mRenderNode.setLayerPaint(paint)) {
16562                    invalidateViewProperty(false, false);
16563                }
16564            } else {
16565                invalidate();
16566            }
16567        }
16568    }
16569
16570    /**
16571     * Indicates what type of layer is currently associated with this view. By default
16572     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
16573     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
16574     * for more information on the different types of layers.
16575     *
16576     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
16577     *         {@link #LAYER_TYPE_HARDWARE}
16578     *
16579     * @see #setLayerType(int, android.graphics.Paint)
16580     * @see #buildLayer()
16581     * @see #LAYER_TYPE_NONE
16582     * @see #LAYER_TYPE_SOFTWARE
16583     * @see #LAYER_TYPE_HARDWARE
16584     */
16585    public int getLayerType() {
16586        return mLayerType;
16587    }
16588
16589    /**
16590     * Forces this view's layer to be created and this view to be rendered
16591     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
16592     * invoking this method will have no effect.
16593     *
16594     * This method can for instance be used to render a view into its layer before
16595     * starting an animation. If this view is complex, rendering into the layer
16596     * before starting the animation will avoid skipping frames.
16597     *
16598     * @throws IllegalStateException If this view is not attached to a window
16599     *
16600     * @see #setLayerType(int, android.graphics.Paint)
16601     */
16602    public void buildLayer() {
16603        if (mLayerType == LAYER_TYPE_NONE) return;
16604
16605        final AttachInfo attachInfo = mAttachInfo;
16606        if (attachInfo == null) {
16607            throw new IllegalStateException("This view must be attached to a window first");
16608        }
16609
16610        if (getWidth() == 0 || getHeight() == 0) {
16611            return;
16612        }
16613
16614        switch (mLayerType) {
16615            case LAYER_TYPE_HARDWARE:
16616                updateDisplayListIfDirty();
16617                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
16618                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
16619                }
16620                break;
16621            case LAYER_TYPE_SOFTWARE:
16622                buildDrawingCache(true);
16623                break;
16624        }
16625    }
16626
16627    /**
16628     * Destroys all hardware rendering resources. This method is invoked
16629     * when the system needs to reclaim resources. Upon execution of this
16630     * method, you should free any OpenGL resources created by the view.
16631     *
16632     * Note: you <strong>must</strong> call
16633     * <code>super.destroyHardwareResources()</code> when overriding
16634     * this method.
16635     *
16636     * @hide
16637     */
16638    @CallSuper
16639    protected void destroyHardwareResources() {
16640        // Although the Layer will be destroyed by RenderNode, we want to release
16641        // the staging display list, which is also a signal to RenderNode that it's
16642        // safe to free its copy of the display list as it knows that we will
16643        // push an updated DisplayList if we try to draw again
16644        resetDisplayList();
16645        if (mOverlay != null) {
16646            mOverlay.getOverlayView().destroyHardwareResources();
16647        }
16648        if (mGhostView != null) {
16649            mGhostView.destroyHardwareResources();
16650        }
16651    }
16652
16653    /**
16654     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16655     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16656     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16657     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16658     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16659     * null.</p>
16660     *
16661     * <p>Enabling the drawing cache is similar to
16662     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16663     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16664     * drawing cache has no effect on rendering because the system uses a different mechanism
16665     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16666     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16667     * for information on how to enable software and hardware layers.</p>
16668     *
16669     * <p>This API can be used to manually generate
16670     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16671     * {@link #getDrawingCache()}.</p>
16672     *
16673     * @param enabled true to enable the drawing cache, false otherwise
16674     *
16675     * @see #isDrawingCacheEnabled()
16676     * @see #getDrawingCache()
16677     * @see #buildDrawingCache()
16678     * @see #setLayerType(int, android.graphics.Paint)
16679     */
16680    public void setDrawingCacheEnabled(boolean enabled) {
16681        mCachingFailed = false;
16682        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16683    }
16684
16685    /**
16686     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16687     *
16688     * @return true if the drawing cache is enabled
16689     *
16690     * @see #setDrawingCacheEnabled(boolean)
16691     * @see #getDrawingCache()
16692     */
16693    @ViewDebug.ExportedProperty(category = "drawing")
16694    public boolean isDrawingCacheEnabled() {
16695        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16696    }
16697
16698    /**
16699     * Debugging utility which recursively outputs the dirty state of a view and its
16700     * descendants.
16701     *
16702     * @hide
16703     */
16704    @SuppressWarnings({"UnusedDeclaration"})
16705    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16706        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16707                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16708                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16709                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16710        if (clear) {
16711            mPrivateFlags &= clearMask;
16712        }
16713        if (this instanceof ViewGroup) {
16714            ViewGroup parent = (ViewGroup) this;
16715            final int count = parent.getChildCount();
16716            for (int i = 0; i < count; i++) {
16717                final View child = parent.getChildAt(i);
16718                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16719            }
16720        }
16721    }
16722
16723    /**
16724     * This method is used by ViewGroup to cause its children to restore or recreate their
16725     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16726     * to recreate its own display list, which would happen if it went through the normal
16727     * draw/dispatchDraw mechanisms.
16728     *
16729     * @hide
16730     */
16731    protected void dispatchGetDisplayList() {}
16732
16733    /**
16734     * A view that is not attached or hardware accelerated cannot create a display list.
16735     * This method checks these conditions and returns the appropriate result.
16736     *
16737     * @return true if view has the ability to create a display list, false otherwise.
16738     *
16739     * @hide
16740     */
16741    public boolean canHaveDisplayList() {
16742        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
16743    }
16744
16745    /**
16746     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
16747     * @hide
16748     */
16749    @NonNull
16750    public RenderNode updateDisplayListIfDirty() {
16751        final RenderNode renderNode = mRenderNode;
16752        if (!canHaveDisplayList()) {
16753            // can't populate RenderNode, don't try
16754            return renderNode;
16755        }
16756
16757        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16758                || !renderNode.isValid()
16759                || (mRecreateDisplayList)) {
16760            // Don't need to recreate the display list, just need to tell our
16761            // children to restore/recreate theirs
16762            if (renderNode.isValid()
16763                    && !mRecreateDisplayList) {
16764                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16765                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16766                dispatchGetDisplayList();
16767
16768                return renderNode; // no work needed
16769            }
16770
16771            // If we got here, we're recreating it. Mark it as such to ensure that
16772            // we copy in child display lists into ours in drawChild()
16773            mRecreateDisplayList = true;
16774
16775            int width = mRight - mLeft;
16776            int height = mBottom - mTop;
16777            int layerType = getLayerType();
16778
16779            final DisplayListCanvas canvas = renderNode.start(width, height);
16780            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16781
16782            try {
16783                if (layerType == LAYER_TYPE_SOFTWARE) {
16784                    buildDrawingCache(true);
16785                    Bitmap cache = getDrawingCache(true);
16786                    if (cache != null) {
16787                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16788                    }
16789                } else {
16790                    computeScroll();
16791
16792                    canvas.translate(-mScrollX, -mScrollY);
16793                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16794                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16795
16796                    // Fast path for layouts with no backgrounds
16797                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16798                        dispatchDraw(canvas);
16799                        if (mOverlay != null && !mOverlay.isEmpty()) {
16800                            mOverlay.getOverlayView().draw(canvas);
16801                        }
16802                        if (debugDraw()) {
16803                            debugDrawFocus(canvas);
16804                        }
16805                    } else {
16806                        draw(canvas);
16807                    }
16808                }
16809            } finally {
16810                renderNode.end(canvas);
16811                setDisplayListProperties(renderNode);
16812            }
16813        } else {
16814            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16815            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16816        }
16817        return renderNode;
16818    }
16819
16820    private void resetDisplayList() {
16821        mRenderNode.discardDisplayList();
16822
16823        if (mBackgroundRenderNode != null) {
16824            mBackgroundRenderNode.discardDisplayList();
16825        }
16826    }
16827
16828    /**
16829     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16830     *
16831     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16832     *
16833     * @see #getDrawingCache(boolean)
16834     */
16835    public Bitmap getDrawingCache() {
16836        return getDrawingCache(false);
16837    }
16838
16839    /**
16840     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16841     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16842     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16843     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16844     * request the drawing cache by calling this method and draw it on screen if the
16845     * returned bitmap is not null.</p>
16846     *
16847     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16848     * this method will create a bitmap of the same size as this view. Because this bitmap
16849     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16850     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16851     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16852     * size than the view. This implies that your application must be able to handle this
16853     * size.</p>
16854     *
16855     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16856     *        the current density of the screen when the application is in compatibility
16857     *        mode.
16858     *
16859     * @return A bitmap representing this view or null if cache is disabled.
16860     *
16861     * @see #setDrawingCacheEnabled(boolean)
16862     * @see #isDrawingCacheEnabled()
16863     * @see #buildDrawingCache(boolean)
16864     * @see #destroyDrawingCache()
16865     */
16866    public Bitmap getDrawingCache(boolean autoScale) {
16867        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16868            return null;
16869        }
16870        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16871            buildDrawingCache(autoScale);
16872        }
16873        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16874    }
16875
16876    /**
16877     * <p>Frees the resources used by the drawing cache. If you call
16878     * {@link #buildDrawingCache()} manually without calling
16879     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16880     * should cleanup the cache with this method afterwards.</p>
16881     *
16882     * @see #setDrawingCacheEnabled(boolean)
16883     * @see #buildDrawingCache()
16884     * @see #getDrawingCache()
16885     */
16886    public void destroyDrawingCache() {
16887        if (mDrawingCache != null) {
16888            mDrawingCache.recycle();
16889            mDrawingCache = null;
16890        }
16891        if (mUnscaledDrawingCache != null) {
16892            mUnscaledDrawingCache.recycle();
16893            mUnscaledDrawingCache = null;
16894        }
16895    }
16896
16897    /**
16898     * Setting a solid background color for the drawing cache's bitmaps will improve
16899     * performance and memory usage. Note, though that this should only be used if this
16900     * view will always be drawn on top of a solid color.
16901     *
16902     * @param color The background color to use for the drawing cache's bitmap
16903     *
16904     * @see #setDrawingCacheEnabled(boolean)
16905     * @see #buildDrawingCache()
16906     * @see #getDrawingCache()
16907     */
16908    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16909        if (color != mDrawingCacheBackgroundColor) {
16910            mDrawingCacheBackgroundColor = color;
16911            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16912        }
16913    }
16914
16915    /**
16916     * @see #setDrawingCacheBackgroundColor(int)
16917     *
16918     * @return The background color to used for the drawing cache's bitmap
16919     */
16920    @ColorInt
16921    public int getDrawingCacheBackgroundColor() {
16922        return mDrawingCacheBackgroundColor;
16923    }
16924
16925    /**
16926     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16927     *
16928     * @see #buildDrawingCache(boolean)
16929     */
16930    public void buildDrawingCache() {
16931        buildDrawingCache(false);
16932    }
16933
16934    /**
16935     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16936     *
16937     * <p>If you call {@link #buildDrawingCache()} manually without calling
16938     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16939     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16940     *
16941     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16942     * this method will create a bitmap of the same size as this view. Because this bitmap
16943     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16944     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16945     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16946     * size than the view. This implies that your application must be able to handle this
16947     * size.</p>
16948     *
16949     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16950     * you do not need the drawing cache bitmap, calling this method will increase memory
16951     * usage and cause the view to be rendered in software once, thus negatively impacting
16952     * performance.</p>
16953     *
16954     * @see #getDrawingCache()
16955     * @see #destroyDrawingCache()
16956     */
16957    public void buildDrawingCache(boolean autoScale) {
16958        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16959                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16960            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16961                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16962                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16963            }
16964            try {
16965                buildDrawingCacheImpl(autoScale);
16966            } finally {
16967                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16968            }
16969        }
16970    }
16971
16972    /**
16973     * private, internal implementation of buildDrawingCache, used to enable tracing
16974     */
16975    private void buildDrawingCacheImpl(boolean autoScale) {
16976        mCachingFailed = false;
16977
16978        int width = mRight - mLeft;
16979        int height = mBottom - mTop;
16980
16981        final AttachInfo attachInfo = mAttachInfo;
16982        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16983
16984        if (autoScale && scalingRequired) {
16985            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16986            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16987        }
16988
16989        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16990        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16991        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16992
16993        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16994        final long drawingCacheSize =
16995                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16996        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16997            if (width > 0 && height > 0) {
16998                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16999                        + " too large to fit into a software layer (or drawing cache), needs "
17000                        + projectedBitmapSize + " bytes, only "
17001                        + drawingCacheSize + " available");
17002            }
17003            destroyDrawingCache();
17004            mCachingFailed = true;
17005            return;
17006        }
17007
17008        boolean clear = true;
17009        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
17010
17011        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
17012            Bitmap.Config quality;
17013            if (!opaque) {
17014                // Never pick ARGB_4444 because it looks awful
17015                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
17016                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
17017                    case DRAWING_CACHE_QUALITY_AUTO:
17018                    case DRAWING_CACHE_QUALITY_LOW:
17019                    case DRAWING_CACHE_QUALITY_HIGH:
17020                    default:
17021                        quality = Bitmap.Config.ARGB_8888;
17022                        break;
17023                }
17024            } else {
17025                // Optimization for translucent windows
17026                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
17027                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
17028            }
17029
17030            // Try to cleanup memory
17031            if (bitmap != null) bitmap.recycle();
17032
17033            try {
17034                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17035                        width, height, quality);
17036                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
17037                if (autoScale) {
17038                    mDrawingCache = bitmap;
17039                } else {
17040                    mUnscaledDrawingCache = bitmap;
17041                }
17042                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
17043            } catch (OutOfMemoryError e) {
17044                // If there is not enough memory to create the bitmap cache, just
17045                // ignore the issue as bitmap caches are not required to draw the
17046                // view hierarchy
17047                if (autoScale) {
17048                    mDrawingCache = null;
17049                } else {
17050                    mUnscaledDrawingCache = null;
17051                }
17052                mCachingFailed = true;
17053                return;
17054            }
17055
17056            clear = drawingCacheBackgroundColor != 0;
17057        }
17058
17059        Canvas canvas;
17060        if (attachInfo != null) {
17061            canvas = attachInfo.mCanvas;
17062            if (canvas == null) {
17063                canvas = new Canvas();
17064            }
17065            canvas.setBitmap(bitmap);
17066            // Temporarily clobber the cached Canvas in case one of our children
17067            // is also using a drawing cache. Without this, the children would
17068            // steal the canvas by attaching their own bitmap to it and bad, bad
17069            // thing would happen (invisible views, corrupted drawings, etc.)
17070            attachInfo.mCanvas = null;
17071        } else {
17072            // This case should hopefully never or seldom happen
17073            canvas = new Canvas(bitmap);
17074        }
17075
17076        if (clear) {
17077            bitmap.eraseColor(drawingCacheBackgroundColor);
17078        }
17079
17080        computeScroll();
17081        final int restoreCount = canvas.save();
17082
17083        if (autoScale && scalingRequired) {
17084            final float scale = attachInfo.mApplicationScale;
17085            canvas.scale(scale, scale);
17086        }
17087
17088        canvas.translate(-mScrollX, -mScrollY);
17089
17090        mPrivateFlags |= PFLAG_DRAWN;
17091        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
17092                mLayerType != LAYER_TYPE_NONE) {
17093            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
17094        }
17095
17096        // Fast path for layouts with no backgrounds
17097        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17098            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17099            dispatchDraw(canvas);
17100            if (mOverlay != null && !mOverlay.isEmpty()) {
17101                mOverlay.getOverlayView().draw(canvas);
17102            }
17103        } else {
17104            draw(canvas);
17105        }
17106
17107        canvas.restoreToCount(restoreCount);
17108        canvas.setBitmap(null);
17109
17110        if (attachInfo != null) {
17111            // Restore the cached Canvas for our siblings
17112            attachInfo.mCanvas = canvas;
17113        }
17114    }
17115
17116    /**
17117     * Create a snapshot of the view into a bitmap.  We should probably make
17118     * some form of this public, but should think about the API.
17119     *
17120     * @hide
17121     */
17122    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
17123        int width = mRight - mLeft;
17124        int height = mBottom - mTop;
17125
17126        final AttachInfo attachInfo = mAttachInfo;
17127        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
17128        width = (int) ((width * scale) + 0.5f);
17129        height = (int) ((height * scale) + 0.5f);
17130
17131        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17132                width > 0 ? width : 1, height > 0 ? height : 1, quality);
17133        if (bitmap == null) {
17134            throw new OutOfMemoryError();
17135        }
17136
17137        Resources resources = getResources();
17138        if (resources != null) {
17139            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
17140        }
17141
17142        Canvas canvas;
17143        if (attachInfo != null) {
17144            canvas = attachInfo.mCanvas;
17145            if (canvas == null) {
17146                canvas = new Canvas();
17147            }
17148            canvas.setBitmap(bitmap);
17149            // Temporarily clobber the cached Canvas in case one of our children
17150            // is also using a drawing cache. Without this, the children would
17151            // steal the canvas by attaching their own bitmap to it and bad, bad
17152            // things would happen (invisible views, corrupted drawings, etc.)
17153            attachInfo.mCanvas = null;
17154        } else {
17155            // This case should hopefully never or seldom happen
17156            canvas = new Canvas(bitmap);
17157        }
17158
17159        if ((backgroundColor & 0xff000000) != 0) {
17160            bitmap.eraseColor(backgroundColor);
17161        }
17162
17163        computeScroll();
17164        final int restoreCount = canvas.save();
17165        canvas.scale(scale, scale);
17166        canvas.translate(-mScrollX, -mScrollY);
17167
17168        // Temporarily remove the dirty mask
17169        int flags = mPrivateFlags;
17170        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17171
17172        // Fast path for layouts with no backgrounds
17173        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17174            dispatchDraw(canvas);
17175            if (mOverlay != null && !mOverlay.isEmpty()) {
17176                mOverlay.getOverlayView().draw(canvas);
17177            }
17178        } else {
17179            draw(canvas);
17180        }
17181
17182        mPrivateFlags = flags;
17183
17184        canvas.restoreToCount(restoreCount);
17185        canvas.setBitmap(null);
17186
17187        if (attachInfo != null) {
17188            // Restore the cached Canvas for our siblings
17189            attachInfo.mCanvas = canvas;
17190        }
17191
17192        return bitmap;
17193    }
17194
17195    /**
17196     * Indicates whether this View is currently in edit mode. A View is usually
17197     * in edit mode when displayed within a developer tool. For instance, if
17198     * this View is being drawn by a visual user interface builder, this method
17199     * should return true.
17200     *
17201     * Subclasses should check the return value of this method to provide
17202     * different behaviors if their normal behavior might interfere with the
17203     * host environment. For instance: the class spawns a thread in its
17204     * constructor, the drawing code relies on device-specific features, etc.
17205     *
17206     * This method is usually checked in the drawing code of custom widgets.
17207     *
17208     * @return True if this View is in edit mode, false otherwise.
17209     */
17210    public boolean isInEditMode() {
17211        return false;
17212    }
17213
17214    /**
17215     * If the View draws content inside its padding and enables fading edges,
17216     * it needs to support padding offsets. Padding offsets are added to the
17217     * fading edges to extend the length of the fade so that it covers pixels
17218     * drawn inside the padding.
17219     *
17220     * Subclasses of this class should override this method if they need
17221     * to draw content inside the padding.
17222     *
17223     * @return True if padding offset must be applied, false otherwise.
17224     *
17225     * @see #getLeftPaddingOffset()
17226     * @see #getRightPaddingOffset()
17227     * @see #getTopPaddingOffset()
17228     * @see #getBottomPaddingOffset()
17229     *
17230     * @since CURRENT
17231     */
17232    protected boolean isPaddingOffsetRequired() {
17233        return false;
17234    }
17235
17236    /**
17237     * Amount by which to extend the left fading region. Called only when
17238     * {@link #isPaddingOffsetRequired()} returns true.
17239     *
17240     * @return The left padding offset in pixels.
17241     *
17242     * @see #isPaddingOffsetRequired()
17243     *
17244     * @since CURRENT
17245     */
17246    protected int getLeftPaddingOffset() {
17247        return 0;
17248    }
17249
17250    /**
17251     * Amount by which to extend the right fading region. Called only when
17252     * {@link #isPaddingOffsetRequired()} returns true.
17253     *
17254     * @return The right padding offset in pixels.
17255     *
17256     * @see #isPaddingOffsetRequired()
17257     *
17258     * @since CURRENT
17259     */
17260    protected int getRightPaddingOffset() {
17261        return 0;
17262    }
17263
17264    /**
17265     * Amount by which to extend the top fading region. Called only when
17266     * {@link #isPaddingOffsetRequired()} returns true.
17267     *
17268     * @return The top padding offset in pixels.
17269     *
17270     * @see #isPaddingOffsetRequired()
17271     *
17272     * @since CURRENT
17273     */
17274    protected int getTopPaddingOffset() {
17275        return 0;
17276    }
17277
17278    /**
17279     * Amount by which to extend the bottom fading region. Called only when
17280     * {@link #isPaddingOffsetRequired()} returns true.
17281     *
17282     * @return The bottom padding offset in pixels.
17283     *
17284     * @see #isPaddingOffsetRequired()
17285     *
17286     * @since CURRENT
17287     */
17288    protected int getBottomPaddingOffset() {
17289        return 0;
17290    }
17291
17292    /**
17293     * @hide
17294     * @param offsetRequired
17295     */
17296    protected int getFadeTop(boolean offsetRequired) {
17297        int top = mPaddingTop;
17298        if (offsetRequired) top += getTopPaddingOffset();
17299        return top;
17300    }
17301
17302    /**
17303     * @hide
17304     * @param offsetRequired
17305     */
17306    protected int getFadeHeight(boolean offsetRequired) {
17307        int padding = mPaddingTop;
17308        if (offsetRequired) padding += getTopPaddingOffset();
17309        return mBottom - mTop - mPaddingBottom - padding;
17310    }
17311
17312    /**
17313     * <p>Indicates whether this view is attached to a hardware accelerated
17314     * window or not.</p>
17315     *
17316     * <p>Even if this method returns true, it does not mean that every call
17317     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
17318     * accelerated {@link android.graphics.Canvas}. For instance, if this view
17319     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
17320     * window is hardware accelerated,
17321     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
17322     * return false, and this method will return true.</p>
17323     *
17324     * @return True if the view is attached to a window and the window is
17325     *         hardware accelerated; false in any other case.
17326     */
17327    @ViewDebug.ExportedProperty(category = "drawing")
17328    public boolean isHardwareAccelerated() {
17329        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
17330    }
17331
17332    /**
17333     * Sets a rectangular area on this view to which the view will be clipped
17334     * when it is drawn. Setting the value to null will remove the clip bounds
17335     * and the view will draw normally, using its full bounds.
17336     *
17337     * @param clipBounds The rectangular area, in the local coordinates of
17338     * this view, to which future drawing operations will be clipped.
17339     */
17340    public void setClipBounds(Rect clipBounds) {
17341        if (clipBounds == mClipBounds
17342                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
17343            return;
17344        }
17345        if (clipBounds != null) {
17346            if (mClipBounds == null) {
17347                mClipBounds = new Rect(clipBounds);
17348            } else {
17349                mClipBounds.set(clipBounds);
17350            }
17351        } else {
17352            mClipBounds = null;
17353        }
17354        mRenderNode.setClipBounds(mClipBounds);
17355        invalidateViewProperty(false, false);
17356    }
17357
17358    /**
17359     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
17360     *
17361     * @return A copy of the current clip bounds if clip bounds are set,
17362     * otherwise null.
17363     */
17364    public Rect getClipBounds() {
17365        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
17366    }
17367
17368
17369    /**
17370     * Populates an output rectangle with the clip bounds of the view,
17371     * returning {@code true} if successful or {@code false} if the view's
17372     * clip bounds are {@code null}.
17373     *
17374     * @param outRect rectangle in which to place the clip bounds of the view
17375     * @return {@code true} if successful or {@code false} if the view's
17376     *         clip bounds are {@code null}
17377     */
17378    public boolean getClipBounds(Rect outRect) {
17379        if (mClipBounds != null) {
17380            outRect.set(mClipBounds);
17381            return true;
17382        }
17383        return false;
17384    }
17385
17386    /**
17387     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
17388     * case of an active Animation being run on the view.
17389     */
17390    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
17391            Animation a, boolean scalingRequired) {
17392        Transformation invalidationTransform;
17393        final int flags = parent.mGroupFlags;
17394        final boolean initialized = a.isInitialized();
17395        if (!initialized) {
17396            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
17397            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
17398            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
17399            onAnimationStart();
17400        }
17401
17402        final Transformation t = parent.getChildTransformation();
17403        boolean more = a.getTransformation(drawingTime, t, 1f);
17404        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
17405            if (parent.mInvalidationTransformation == null) {
17406                parent.mInvalidationTransformation = new Transformation();
17407            }
17408            invalidationTransform = parent.mInvalidationTransformation;
17409            a.getTransformation(drawingTime, invalidationTransform, 1f);
17410        } else {
17411            invalidationTransform = t;
17412        }
17413
17414        if (more) {
17415            if (!a.willChangeBounds()) {
17416                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
17417                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
17418                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
17419                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
17420                    // The child need to draw an animation, potentially offscreen, so
17421                    // make sure we do not cancel invalidate requests
17422                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17423                    parent.invalidate(mLeft, mTop, mRight, mBottom);
17424                }
17425            } else {
17426                if (parent.mInvalidateRegion == null) {
17427                    parent.mInvalidateRegion = new RectF();
17428                }
17429                final RectF region = parent.mInvalidateRegion;
17430                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
17431                        invalidationTransform);
17432
17433                // The child need to draw an animation, potentially offscreen, so
17434                // make sure we do not cancel invalidate requests
17435                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
17436
17437                final int left = mLeft + (int) region.left;
17438                final int top = mTop + (int) region.top;
17439                parent.invalidate(left, top, left + (int) (region.width() + .5f),
17440                        top + (int) (region.height() + .5f));
17441            }
17442        }
17443        return more;
17444    }
17445
17446    /**
17447     * This method is called by getDisplayList() when a display list is recorded for a View.
17448     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
17449     */
17450    void setDisplayListProperties(RenderNode renderNode) {
17451        if (renderNode != null) {
17452            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
17453            renderNode.setClipToBounds(mParent instanceof ViewGroup
17454                    && ((ViewGroup) mParent).getClipChildren());
17455
17456            float alpha = 1;
17457            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
17458                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17459                ViewGroup parentVG = (ViewGroup) mParent;
17460                final Transformation t = parentVG.getChildTransformation();
17461                if (parentVG.getChildStaticTransformation(this, t)) {
17462                    final int transformType = t.getTransformationType();
17463                    if (transformType != Transformation.TYPE_IDENTITY) {
17464                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
17465                            alpha = t.getAlpha();
17466                        }
17467                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
17468                            renderNode.setStaticMatrix(t.getMatrix());
17469                        }
17470                    }
17471                }
17472            }
17473            if (mTransformationInfo != null) {
17474                alpha *= getFinalAlpha();
17475                if (alpha < 1) {
17476                    final int multipliedAlpha = (int) (255 * alpha);
17477                    if (onSetAlpha(multipliedAlpha)) {
17478                        alpha = 1;
17479                    }
17480                }
17481                renderNode.setAlpha(alpha);
17482            } else if (alpha < 1) {
17483                renderNode.setAlpha(alpha);
17484            }
17485        }
17486    }
17487
17488    /**
17489     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
17490     *
17491     * This is where the View specializes rendering behavior based on layer type,
17492     * and hardware acceleration.
17493     */
17494    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
17495        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
17496        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
17497         *
17498         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
17499         * HW accelerated, it can't handle drawing RenderNodes.
17500         */
17501        boolean drawingWithRenderNode = mAttachInfo != null
17502                && mAttachInfo.mHardwareAccelerated
17503                && hardwareAcceleratedCanvas;
17504
17505        boolean more = false;
17506        final boolean childHasIdentityMatrix = hasIdentityMatrix();
17507        final int parentFlags = parent.mGroupFlags;
17508
17509        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
17510            parent.getChildTransformation().clear();
17511            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17512        }
17513
17514        Transformation transformToApply = null;
17515        boolean concatMatrix = false;
17516        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
17517        final Animation a = getAnimation();
17518        if (a != null) {
17519            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
17520            concatMatrix = a.willChangeTransformationMatrix();
17521            if (concatMatrix) {
17522                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17523            }
17524            transformToApply = parent.getChildTransformation();
17525        } else {
17526            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
17527                // No longer animating: clear out old animation matrix
17528                mRenderNode.setAnimationMatrix(null);
17529                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
17530            }
17531            if (!drawingWithRenderNode
17532                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
17533                final Transformation t = parent.getChildTransformation();
17534                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
17535                if (hasTransform) {
17536                    final int transformType = t.getTransformationType();
17537                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
17538                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
17539                }
17540            }
17541        }
17542
17543        concatMatrix |= !childHasIdentityMatrix;
17544
17545        // Sets the flag as early as possible to allow draw() implementations
17546        // to call invalidate() successfully when doing animations
17547        mPrivateFlags |= PFLAG_DRAWN;
17548
17549        if (!concatMatrix &&
17550                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
17551                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
17552                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
17553                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
17554            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
17555            return more;
17556        }
17557        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
17558
17559        if (hardwareAcceleratedCanvas) {
17560            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
17561            // retain the flag's value temporarily in the mRecreateDisplayList flag
17562            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
17563            mPrivateFlags &= ~PFLAG_INVALIDATED;
17564        }
17565
17566        RenderNode renderNode = null;
17567        Bitmap cache = null;
17568        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
17569        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
17570             if (layerType != LAYER_TYPE_NONE) {
17571                 // If not drawing with RenderNode, treat HW layers as SW
17572                 layerType = LAYER_TYPE_SOFTWARE;
17573                 buildDrawingCache(true);
17574            }
17575            cache = getDrawingCache(true);
17576        }
17577
17578        if (drawingWithRenderNode) {
17579            // Delay getting the display list until animation-driven alpha values are
17580            // set up and possibly passed on to the view
17581            renderNode = updateDisplayListIfDirty();
17582            if (!renderNode.isValid()) {
17583                // Uncommon, but possible. If a view is removed from the hierarchy during the call
17584                // to getDisplayList(), the display list will be marked invalid and we should not
17585                // try to use it again.
17586                renderNode = null;
17587                drawingWithRenderNode = false;
17588            }
17589        }
17590
17591        int sx = 0;
17592        int sy = 0;
17593        if (!drawingWithRenderNode) {
17594            computeScroll();
17595            sx = mScrollX;
17596            sy = mScrollY;
17597        }
17598
17599        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
17600        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
17601
17602        int restoreTo = -1;
17603        if (!drawingWithRenderNode || transformToApply != null) {
17604            restoreTo = canvas.save();
17605        }
17606        if (offsetForScroll) {
17607            canvas.translate(mLeft - sx, mTop - sy);
17608        } else {
17609            if (!drawingWithRenderNode) {
17610                canvas.translate(mLeft, mTop);
17611            }
17612            if (scalingRequired) {
17613                if (drawingWithRenderNode) {
17614                    // TODO: Might not need this if we put everything inside the DL
17615                    restoreTo = canvas.save();
17616                }
17617                // mAttachInfo cannot be null, otherwise scalingRequired == false
17618                final float scale = 1.0f / mAttachInfo.mApplicationScale;
17619                canvas.scale(scale, scale);
17620            }
17621        }
17622
17623        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
17624        if (transformToApply != null
17625                || alpha < 1
17626                || !hasIdentityMatrix()
17627                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17628            if (transformToApply != null || !childHasIdentityMatrix) {
17629                int transX = 0;
17630                int transY = 0;
17631
17632                if (offsetForScroll) {
17633                    transX = -sx;
17634                    transY = -sy;
17635                }
17636
17637                if (transformToApply != null) {
17638                    if (concatMatrix) {
17639                        if (drawingWithRenderNode) {
17640                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17641                        } else {
17642                            // Undo the scroll translation, apply the transformation matrix,
17643                            // then redo the scroll translate to get the correct result.
17644                            canvas.translate(-transX, -transY);
17645                            canvas.concat(transformToApply.getMatrix());
17646                            canvas.translate(transX, transY);
17647                        }
17648                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17649                    }
17650
17651                    float transformAlpha = transformToApply.getAlpha();
17652                    if (transformAlpha < 1) {
17653                        alpha *= transformAlpha;
17654                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17655                    }
17656                }
17657
17658                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17659                    canvas.translate(-transX, -transY);
17660                    canvas.concat(getMatrix());
17661                    canvas.translate(transX, transY);
17662                }
17663            }
17664
17665            // Deal with alpha if it is or used to be <1
17666            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17667                if (alpha < 1) {
17668                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17669                } else {
17670                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17671                }
17672                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17673                if (!drawingWithDrawingCache) {
17674                    final int multipliedAlpha = (int) (255 * alpha);
17675                    if (!onSetAlpha(multipliedAlpha)) {
17676                        if (drawingWithRenderNode) {
17677                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17678                        } else if (layerType == LAYER_TYPE_NONE) {
17679                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17680                                    multipliedAlpha);
17681                        }
17682                    } else {
17683                        // Alpha is handled by the child directly, clobber the layer's alpha
17684                        mPrivateFlags |= PFLAG_ALPHA_SET;
17685                    }
17686                }
17687            }
17688        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17689            onSetAlpha(255);
17690            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17691        }
17692
17693        if (!drawingWithRenderNode) {
17694            // apply clips directly, since RenderNode won't do it for this draw
17695            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17696                if (offsetForScroll) {
17697                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17698                } else {
17699                    if (!scalingRequired || cache == null) {
17700                        canvas.clipRect(0, 0, getWidth(), getHeight());
17701                    } else {
17702                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17703                    }
17704                }
17705            }
17706
17707            if (mClipBounds != null) {
17708                // clip bounds ignore scroll
17709                canvas.clipRect(mClipBounds);
17710            }
17711        }
17712
17713        if (!drawingWithDrawingCache) {
17714            if (drawingWithRenderNode) {
17715                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17716                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17717            } else {
17718                // Fast path for layouts with no backgrounds
17719                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17720                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17721                    dispatchDraw(canvas);
17722                } else {
17723                    draw(canvas);
17724                }
17725            }
17726        } else if (cache != null) {
17727            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17728            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17729                // no layer paint, use temporary paint to draw bitmap
17730                Paint cachePaint = parent.mCachePaint;
17731                if (cachePaint == null) {
17732                    cachePaint = new Paint();
17733                    cachePaint.setDither(false);
17734                    parent.mCachePaint = cachePaint;
17735                }
17736                cachePaint.setAlpha((int) (alpha * 255));
17737                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17738            } else {
17739                // use layer paint to draw the bitmap, merging the two alphas, but also restore
17740                int layerPaintAlpha = mLayerPaint.getAlpha();
17741                if (alpha < 1) {
17742                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17743                }
17744                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17745                if (alpha < 1) {
17746                    mLayerPaint.setAlpha(layerPaintAlpha);
17747                }
17748            }
17749        }
17750
17751        if (restoreTo >= 0) {
17752            canvas.restoreToCount(restoreTo);
17753        }
17754
17755        if (a != null && !more) {
17756            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17757                onSetAlpha(255);
17758            }
17759            parent.finishAnimatingView(this, a);
17760        }
17761
17762        if (more && hardwareAcceleratedCanvas) {
17763            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17764                // alpha animations should cause the child to recreate its display list
17765                invalidate(true);
17766            }
17767        }
17768
17769        mRecreateDisplayList = false;
17770
17771        return more;
17772    }
17773
17774    static Paint getDebugPaint() {
17775        if (sDebugPaint == null) {
17776            sDebugPaint = new Paint();
17777            sDebugPaint.setAntiAlias(false);
17778        }
17779        return sDebugPaint;
17780    }
17781
17782    final int dipsToPixels(int dips) {
17783        float scale = getContext().getResources().getDisplayMetrics().density;
17784        return (int) (dips * scale + 0.5f);
17785    }
17786
17787    final private void debugDrawFocus(Canvas canvas) {
17788        if (isFocused()) {
17789            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
17790            final int l = mScrollX;
17791            final int r = l + mRight - mLeft;
17792            final int t = mScrollY;
17793            final int b = t + mBottom - mTop;
17794
17795            final Paint paint = getDebugPaint();
17796            paint.setColor(DEBUG_CORNERS_COLOR);
17797
17798            // Draw squares in corners.
17799            paint.setStyle(Paint.Style.FILL);
17800            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
17801            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
17802            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
17803            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
17804
17805            // Draw big X across the view.
17806            paint.setStyle(Paint.Style.STROKE);
17807            canvas.drawLine(l, t, r, b, paint);
17808            canvas.drawLine(l, b, r, t, paint);
17809        }
17810    }
17811
17812    /**
17813     * Manually render this view (and all of its children) to the given Canvas.
17814     * The view must have already done a full layout before this function is
17815     * called.  When implementing a view, implement
17816     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17817     * If you do need to override this method, call the superclass version.
17818     *
17819     * @param canvas The Canvas to which the View is rendered.
17820     */
17821    @CallSuper
17822    public void draw(Canvas canvas) {
17823        final int privateFlags = mPrivateFlags;
17824        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17825                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17826        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17827
17828        /*
17829         * Draw traversal performs several drawing steps which must be executed
17830         * in the appropriate order:
17831         *
17832         *      1. Draw the background
17833         *      2. If necessary, save the canvas' layers to prepare for fading
17834         *      3. Draw view's content
17835         *      4. Draw children
17836         *      5. If necessary, draw the fading edges and restore layers
17837         *      6. Draw decorations (scrollbars for instance)
17838         */
17839
17840        // Step 1, draw the background, if needed
17841        int saveCount;
17842
17843        if (!dirtyOpaque) {
17844            drawBackground(canvas);
17845        }
17846
17847        // skip step 2 & 5 if possible (common case)
17848        final int viewFlags = mViewFlags;
17849        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17850        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17851        if (!verticalEdges && !horizontalEdges) {
17852            // Step 3, draw the content
17853            if (!dirtyOpaque) onDraw(canvas);
17854
17855            // Step 4, draw the children
17856            dispatchDraw(canvas);
17857
17858            // Overlay is part of the content and draws beneath Foreground
17859            if (mOverlay != null && !mOverlay.isEmpty()) {
17860                mOverlay.getOverlayView().dispatchDraw(canvas);
17861            }
17862
17863            // Step 6, draw decorations (foreground, scrollbars)
17864            onDrawForeground(canvas);
17865
17866            if (debugDraw()) {
17867                debugDrawFocus(canvas);
17868            }
17869
17870            // we're done...
17871            return;
17872        }
17873
17874        /*
17875         * Here we do the full fledged routine...
17876         * (this is an uncommon case where speed matters less,
17877         * this is why we repeat some of the tests that have been
17878         * done above)
17879         */
17880
17881        boolean drawTop = false;
17882        boolean drawBottom = false;
17883        boolean drawLeft = false;
17884        boolean drawRight = false;
17885
17886        float topFadeStrength = 0.0f;
17887        float bottomFadeStrength = 0.0f;
17888        float leftFadeStrength = 0.0f;
17889        float rightFadeStrength = 0.0f;
17890
17891        // Step 2, save the canvas' layers
17892        int paddingLeft = mPaddingLeft;
17893
17894        final boolean offsetRequired = isPaddingOffsetRequired();
17895        if (offsetRequired) {
17896            paddingLeft += getLeftPaddingOffset();
17897        }
17898
17899        int left = mScrollX + paddingLeft;
17900        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17901        int top = mScrollY + getFadeTop(offsetRequired);
17902        int bottom = top + getFadeHeight(offsetRequired);
17903
17904        if (offsetRequired) {
17905            right += getRightPaddingOffset();
17906            bottom += getBottomPaddingOffset();
17907        }
17908
17909        final ScrollabilityCache scrollabilityCache = mScrollCache;
17910        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17911        int length = (int) fadeHeight;
17912
17913        // clip the fade length if top and bottom fades overlap
17914        // overlapping fades produce odd-looking artifacts
17915        if (verticalEdges && (top + length > bottom - length)) {
17916            length = (bottom - top) / 2;
17917        }
17918
17919        // also clip horizontal fades if necessary
17920        if (horizontalEdges && (left + length > right - length)) {
17921            length = (right - left) / 2;
17922        }
17923
17924        if (verticalEdges) {
17925            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17926            drawTop = topFadeStrength * fadeHeight > 1.0f;
17927            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17928            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17929        }
17930
17931        if (horizontalEdges) {
17932            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17933            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17934            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17935            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17936        }
17937
17938        saveCount = canvas.getSaveCount();
17939
17940        int solidColor = getSolidColor();
17941        if (solidColor == 0) {
17942            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17943
17944            if (drawTop) {
17945                canvas.saveLayer(left, top, right, top + length, null, flags);
17946            }
17947
17948            if (drawBottom) {
17949                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17950            }
17951
17952            if (drawLeft) {
17953                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17954            }
17955
17956            if (drawRight) {
17957                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17958            }
17959        } else {
17960            scrollabilityCache.setFadeColor(solidColor);
17961        }
17962
17963        // Step 3, draw the content
17964        if (!dirtyOpaque) onDraw(canvas);
17965
17966        // Step 4, draw the children
17967        dispatchDraw(canvas);
17968
17969        // Step 5, draw the fade effect and restore layers
17970        final Paint p = scrollabilityCache.paint;
17971        final Matrix matrix = scrollabilityCache.matrix;
17972        final Shader fade = scrollabilityCache.shader;
17973
17974        if (drawTop) {
17975            matrix.setScale(1, fadeHeight * topFadeStrength);
17976            matrix.postTranslate(left, top);
17977            fade.setLocalMatrix(matrix);
17978            p.setShader(fade);
17979            canvas.drawRect(left, top, right, top + length, p);
17980        }
17981
17982        if (drawBottom) {
17983            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17984            matrix.postRotate(180);
17985            matrix.postTranslate(left, bottom);
17986            fade.setLocalMatrix(matrix);
17987            p.setShader(fade);
17988            canvas.drawRect(left, bottom - length, right, bottom, p);
17989        }
17990
17991        if (drawLeft) {
17992            matrix.setScale(1, fadeHeight * leftFadeStrength);
17993            matrix.postRotate(-90);
17994            matrix.postTranslate(left, top);
17995            fade.setLocalMatrix(matrix);
17996            p.setShader(fade);
17997            canvas.drawRect(left, top, left + length, bottom, p);
17998        }
17999
18000        if (drawRight) {
18001            matrix.setScale(1, fadeHeight * rightFadeStrength);
18002            matrix.postRotate(90);
18003            matrix.postTranslate(right, top);
18004            fade.setLocalMatrix(matrix);
18005            p.setShader(fade);
18006            canvas.drawRect(right - length, top, right, bottom, p);
18007        }
18008
18009        canvas.restoreToCount(saveCount);
18010
18011        // Overlay is part of the content and draws beneath Foreground
18012        if (mOverlay != null && !mOverlay.isEmpty()) {
18013            mOverlay.getOverlayView().dispatchDraw(canvas);
18014        }
18015
18016        // Step 6, draw decorations (foreground, scrollbars)
18017        onDrawForeground(canvas);
18018
18019        if (debugDraw()) {
18020            debugDrawFocus(canvas);
18021        }
18022    }
18023
18024    /**
18025     * Draws the background onto the specified canvas.
18026     *
18027     * @param canvas Canvas on which to draw the background
18028     */
18029    private void drawBackground(Canvas canvas) {
18030        final Drawable background = mBackground;
18031        if (background == null) {
18032            return;
18033        }
18034
18035        setBackgroundBounds();
18036
18037        // Attempt to use a display list if requested.
18038        if (canvas.isHardwareAccelerated() && mAttachInfo != null
18039                && mAttachInfo.mThreadedRenderer != null) {
18040            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
18041
18042            final RenderNode renderNode = mBackgroundRenderNode;
18043            if (renderNode != null && renderNode.isValid()) {
18044                setBackgroundRenderNodeProperties(renderNode);
18045                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18046                return;
18047            }
18048        }
18049
18050        final int scrollX = mScrollX;
18051        final int scrollY = mScrollY;
18052        if ((scrollX | scrollY) == 0) {
18053            background.draw(canvas);
18054        } else {
18055            canvas.translate(scrollX, scrollY);
18056            background.draw(canvas);
18057            canvas.translate(-scrollX, -scrollY);
18058        }
18059    }
18060
18061    /**
18062     * Sets the correct background bounds and rebuilds the outline, if needed.
18063     * <p/>
18064     * This is called by LayoutLib.
18065     */
18066    void setBackgroundBounds() {
18067        if (mBackgroundSizeChanged && mBackground != null) {
18068            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
18069            mBackgroundSizeChanged = false;
18070            rebuildOutline();
18071        }
18072    }
18073
18074    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
18075        renderNode.setTranslationX(mScrollX);
18076        renderNode.setTranslationY(mScrollY);
18077    }
18078
18079    /**
18080     * Creates a new display list or updates the existing display list for the
18081     * specified Drawable.
18082     *
18083     * @param drawable Drawable for which to create a display list
18084     * @param renderNode Existing RenderNode, or {@code null}
18085     * @return A valid display list for the specified drawable
18086     */
18087    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
18088        if (renderNode == null) {
18089            renderNode = RenderNode.create(drawable.getClass().getName(), this);
18090        }
18091
18092        final Rect bounds = drawable.getBounds();
18093        final int width = bounds.width();
18094        final int height = bounds.height();
18095        final DisplayListCanvas canvas = renderNode.start(width, height);
18096
18097        // Reverse left/top translation done by drawable canvas, which will
18098        // instead be applied by rendernode's LTRB bounds below. This way, the
18099        // drawable's bounds match with its rendernode bounds and its content
18100        // will lie within those bounds in the rendernode tree.
18101        canvas.translate(-bounds.left, -bounds.top);
18102
18103        try {
18104            drawable.draw(canvas);
18105        } finally {
18106            renderNode.end(canvas);
18107        }
18108
18109        // Set up drawable properties that are view-independent.
18110        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
18111        renderNode.setProjectBackwards(drawable.isProjected());
18112        renderNode.setProjectionReceiver(true);
18113        renderNode.setClipToBounds(false);
18114        return renderNode;
18115    }
18116
18117    /**
18118     * Returns the overlay for this view, creating it if it does not yet exist.
18119     * Adding drawables to the overlay will cause them to be displayed whenever
18120     * the view itself is redrawn. Objects in the overlay should be actively
18121     * managed: remove them when they should not be displayed anymore. The
18122     * overlay will always have the same size as its host view.
18123     *
18124     * <p>Note: Overlays do not currently work correctly with {@link
18125     * SurfaceView} or {@link TextureView}; contents in overlays for these
18126     * types of views may not display correctly.</p>
18127     *
18128     * @return The ViewOverlay object for this view.
18129     * @see ViewOverlay
18130     */
18131    public ViewOverlay getOverlay() {
18132        if (mOverlay == null) {
18133            mOverlay = new ViewOverlay(mContext, this);
18134        }
18135        return mOverlay;
18136    }
18137
18138    /**
18139     * Override this if your view is known to always be drawn on top of a solid color background,
18140     * and needs to draw fading edges. Returning a non-zero color enables the view system to
18141     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
18142     * should be set to 0xFF.
18143     *
18144     * @see #setVerticalFadingEdgeEnabled(boolean)
18145     * @see #setHorizontalFadingEdgeEnabled(boolean)
18146     *
18147     * @return The known solid color background for this view, or 0 if the color may vary
18148     */
18149    @ViewDebug.ExportedProperty(category = "drawing")
18150    @ColorInt
18151    public int getSolidColor() {
18152        return 0;
18153    }
18154
18155    /**
18156     * Build a human readable string representation of the specified view flags.
18157     *
18158     * @param flags the view flags to convert to a string
18159     * @return a String representing the supplied flags
18160     */
18161    private static String printFlags(int flags) {
18162        String output = "";
18163        int numFlags = 0;
18164        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
18165            output += "TAKES_FOCUS";
18166            numFlags++;
18167        }
18168
18169        switch (flags & VISIBILITY_MASK) {
18170        case INVISIBLE:
18171            if (numFlags > 0) {
18172                output += " ";
18173            }
18174            output += "INVISIBLE";
18175            // USELESS HERE numFlags++;
18176            break;
18177        case GONE:
18178            if (numFlags > 0) {
18179                output += " ";
18180            }
18181            output += "GONE";
18182            // USELESS HERE numFlags++;
18183            break;
18184        default:
18185            break;
18186        }
18187        return output;
18188    }
18189
18190    /**
18191     * Build a human readable string representation of the specified private
18192     * view flags.
18193     *
18194     * @param privateFlags the private view flags to convert to a string
18195     * @return a String representing the supplied flags
18196     */
18197    private static String printPrivateFlags(int privateFlags) {
18198        String output = "";
18199        int numFlags = 0;
18200
18201        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
18202            output += "WANTS_FOCUS";
18203            numFlags++;
18204        }
18205
18206        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
18207            if (numFlags > 0) {
18208                output += " ";
18209            }
18210            output += "FOCUSED";
18211            numFlags++;
18212        }
18213
18214        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
18215            if (numFlags > 0) {
18216                output += " ";
18217            }
18218            output += "SELECTED";
18219            numFlags++;
18220        }
18221
18222        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
18223            if (numFlags > 0) {
18224                output += " ";
18225            }
18226            output += "IS_ROOT_NAMESPACE";
18227            numFlags++;
18228        }
18229
18230        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
18231            if (numFlags > 0) {
18232                output += " ";
18233            }
18234            output += "HAS_BOUNDS";
18235            numFlags++;
18236        }
18237
18238        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
18239            if (numFlags > 0) {
18240                output += " ";
18241            }
18242            output += "DRAWN";
18243            // USELESS HERE numFlags++;
18244        }
18245        return output;
18246    }
18247
18248    /**
18249     * <p>Indicates whether or not this view's layout will be requested during
18250     * the next hierarchy layout pass.</p>
18251     *
18252     * @return true if the layout will be forced during next layout pass
18253     */
18254    public boolean isLayoutRequested() {
18255        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18256    }
18257
18258    /**
18259     * Return true if o is a ViewGroup that is laying out using optical bounds.
18260     * @hide
18261     */
18262    public static boolean isLayoutModeOptical(Object o) {
18263        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
18264    }
18265
18266    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
18267        Insets parentInsets = mParent instanceof View ?
18268                ((View) mParent).getOpticalInsets() : Insets.NONE;
18269        Insets childInsets = getOpticalInsets();
18270        return setFrame(
18271                left   + parentInsets.left - childInsets.left,
18272                top    + parentInsets.top  - childInsets.top,
18273                right  + parentInsets.left + childInsets.right,
18274                bottom + parentInsets.top  + childInsets.bottom);
18275    }
18276
18277    /**
18278     * Assign a size and position to a view and all of its
18279     * descendants
18280     *
18281     * <p>This is the second phase of the layout mechanism.
18282     * (The first is measuring). In this phase, each parent calls
18283     * layout on all of its children to position them.
18284     * This is typically done using the child measurements
18285     * that were stored in the measure pass().</p>
18286     *
18287     * <p>Derived classes should not override this method.
18288     * Derived classes with children should override
18289     * onLayout. In that method, they should
18290     * call layout on each of their children.</p>
18291     *
18292     * @param l Left position, relative to parent
18293     * @param t Top position, relative to parent
18294     * @param r Right position, relative to parent
18295     * @param b Bottom position, relative to parent
18296     */
18297    @SuppressWarnings({"unchecked"})
18298    public void layout(int l, int t, int r, int b) {
18299        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
18300            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
18301            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18302        }
18303
18304        int oldL = mLeft;
18305        int oldT = mTop;
18306        int oldB = mBottom;
18307        int oldR = mRight;
18308
18309        boolean changed = isLayoutModeOptical(mParent) ?
18310                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
18311
18312        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
18313            onLayout(changed, l, t, r, b);
18314
18315            if (shouldDrawRoundScrollbar()) {
18316                if(mRoundScrollbarRenderer == null) {
18317                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
18318                }
18319            } else {
18320                mRoundScrollbarRenderer = null;
18321            }
18322
18323            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
18324
18325            ListenerInfo li = mListenerInfo;
18326            if (li != null && li.mOnLayoutChangeListeners != null) {
18327                ArrayList<OnLayoutChangeListener> listenersCopy =
18328                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
18329                int numListeners = listenersCopy.size();
18330                for (int i = 0; i < numListeners; ++i) {
18331                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
18332                }
18333            }
18334        }
18335
18336        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
18337        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
18338    }
18339
18340    /**
18341     * Called from layout when this view should
18342     * assign a size and position to each of its children.
18343     *
18344     * Derived classes with children should override
18345     * this method and call layout on each of
18346     * their children.
18347     * @param changed This is a new size or position for this view
18348     * @param left Left position, relative to parent
18349     * @param top Top position, relative to parent
18350     * @param right Right position, relative to parent
18351     * @param bottom Bottom position, relative to parent
18352     */
18353    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
18354    }
18355
18356    /**
18357     * Assign a size and position to this view.
18358     *
18359     * This is called from layout.
18360     *
18361     * @param left Left position, relative to parent
18362     * @param top Top position, relative to parent
18363     * @param right Right position, relative to parent
18364     * @param bottom Bottom position, relative to parent
18365     * @return true if the new size and position are different than the
18366     *         previous ones
18367     * {@hide}
18368     */
18369    protected boolean setFrame(int left, int top, int right, int bottom) {
18370        boolean changed = false;
18371
18372        if (DBG) {
18373            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
18374                    + right + "," + bottom + ")");
18375        }
18376
18377        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
18378            changed = true;
18379
18380            // Remember our drawn bit
18381            int drawn = mPrivateFlags & PFLAG_DRAWN;
18382
18383            int oldWidth = mRight - mLeft;
18384            int oldHeight = mBottom - mTop;
18385            int newWidth = right - left;
18386            int newHeight = bottom - top;
18387            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
18388
18389            // Invalidate our old position
18390            invalidate(sizeChanged);
18391
18392            mLeft = left;
18393            mTop = top;
18394            mRight = right;
18395            mBottom = bottom;
18396            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
18397
18398            mPrivateFlags |= PFLAG_HAS_BOUNDS;
18399
18400
18401            if (sizeChanged) {
18402                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
18403            }
18404
18405            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
18406                // If we are visible, force the DRAWN bit to on so that
18407                // this invalidate will go through (at least to our parent).
18408                // This is because someone may have invalidated this view
18409                // before this call to setFrame came in, thereby clearing
18410                // the DRAWN bit.
18411                mPrivateFlags |= PFLAG_DRAWN;
18412                invalidate(sizeChanged);
18413                // parent display list may need to be recreated based on a change in the bounds
18414                // of any child
18415                invalidateParentCaches();
18416            }
18417
18418            // Reset drawn bit to original value (invalidate turns it off)
18419            mPrivateFlags |= drawn;
18420
18421            mBackgroundSizeChanged = true;
18422            if (mForegroundInfo != null) {
18423                mForegroundInfo.mBoundsChanged = true;
18424            }
18425
18426            notifySubtreeAccessibilityStateChangedIfNeeded();
18427        }
18428        return changed;
18429    }
18430
18431    /**
18432     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
18433     * @hide
18434     */
18435    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
18436        setFrame(left, top, right, bottom);
18437    }
18438
18439    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
18440        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
18441        if (mOverlay != null) {
18442            mOverlay.getOverlayView().setRight(newWidth);
18443            mOverlay.getOverlayView().setBottom(newHeight);
18444        }
18445        rebuildOutline();
18446    }
18447
18448    /**
18449     * Finalize inflating a view from XML.  This is called as the last phase
18450     * of inflation, after all child views have been added.
18451     *
18452     * <p>Even if the subclass overrides onFinishInflate, they should always be
18453     * sure to call the super method, so that we get called.
18454     */
18455    @CallSuper
18456    protected void onFinishInflate() {
18457    }
18458
18459    /**
18460     * Returns the resources associated with this view.
18461     *
18462     * @return Resources object.
18463     */
18464    public Resources getResources() {
18465        return mResources;
18466    }
18467
18468    /**
18469     * Invalidates the specified Drawable.
18470     *
18471     * @param drawable the drawable to invalidate
18472     */
18473    @Override
18474    public void invalidateDrawable(@NonNull Drawable drawable) {
18475        if (verifyDrawable(drawable)) {
18476            final Rect dirty = drawable.getDirtyBounds();
18477            final int scrollX = mScrollX;
18478            final int scrollY = mScrollY;
18479
18480            invalidate(dirty.left + scrollX, dirty.top + scrollY,
18481                    dirty.right + scrollX, dirty.bottom + scrollY);
18482            rebuildOutline();
18483        }
18484    }
18485
18486    /**
18487     * Schedules an action on a drawable to occur at a specified time.
18488     *
18489     * @param who the recipient of the action
18490     * @param what the action to run on the drawable
18491     * @param when the time at which the action must occur. Uses the
18492     *        {@link SystemClock#uptimeMillis} timebase.
18493     */
18494    @Override
18495    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
18496        if (verifyDrawable(who) && what != null) {
18497            final long delay = when - SystemClock.uptimeMillis();
18498            if (mAttachInfo != null) {
18499                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
18500                        Choreographer.CALLBACK_ANIMATION, what, who,
18501                        Choreographer.subtractFrameDelay(delay));
18502            } else {
18503                // Postpone the runnable until we know
18504                // on which thread it needs to run.
18505                getRunQueue().postDelayed(what, delay);
18506            }
18507        }
18508    }
18509
18510    /**
18511     * Cancels a scheduled action on a drawable.
18512     *
18513     * @param who the recipient of the action
18514     * @param what the action to cancel
18515     */
18516    @Override
18517    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
18518        if (verifyDrawable(who) && what != null) {
18519            if (mAttachInfo != null) {
18520                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18521                        Choreographer.CALLBACK_ANIMATION, what, who);
18522            }
18523            getRunQueue().removeCallbacks(what);
18524        }
18525    }
18526
18527    /**
18528     * Unschedule any events associated with the given Drawable.  This can be
18529     * used when selecting a new Drawable into a view, so that the previous
18530     * one is completely unscheduled.
18531     *
18532     * @param who The Drawable to unschedule.
18533     *
18534     * @see #drawableStateChanged
18535     */
18536    public void unscheduleDrawable(Drawable who) {
18537        if (mAttachInfo != null && who != null) {
18538            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
18539                    Choreographer.CALLBACK_ANIMATION, null, who);
18540        }
18541    }
18542
18543    /**
18544     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
18545     * that the View directionality can and will be resolved before its Drawables.
18546     *
18547     * Will call {@link View#onResolveDrawables} when resolution is done.
18548     *
18549     * @hide
18550     */
18551    protected void resolveDrawables() {
18552        // Drawables resolution may need to happen before resolving the layout direction (which is
18553        // done only during the measure() call).
18554        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
18555        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
18556        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
18557        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
18558        // direction to be resolved as its resolved value will be the same as its raw value.
18559        if (!isLayoutDirectionResolved() &&
18560                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
18561            return;
18562        }
18563
18564        final int layoutDirection = isLayoutDirectionResolved() ?
18565                getLayoutDirection() : getRawLayoutDirection();
18566
18567        if (mBackground != null) {
18568            mBackground.setLayoutDirection(layoutDirection);
18569        }
18570        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18571            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
18572        }
18573        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
18574        onResolveDrawables(layoutDirection);
18575    }
18576
18577    boolean areDrawablesResolved() {
18578        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
18579    }
18580
18581    /**
18582     * Called when layout direction has been resolved.
18583     *
18584     * The default implementation does nothing.
18585     *
18586     * @param layoutDirection The resolved layout direction.
18587     *
18588     * @see #LAYOUT_DIRECTION_LTR
18589     * @see #LAYOUT_DIRECTION_RTL
18590     *
18591     * @hide
18592     */
18593    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
18594    }
18595
18596    /**
18597     * @hide
18598     */
18599    protected void resetResolvedDrawables() {
18600        resetResolvedDrawablesInternal();
18601    }
18602
18603    void resetResolvedDrawablesInternal() {
18604        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
18605    }
18606
18607    /**
18608     * If your view subclass is displaying its own Drawable objects, it should
18609     * override this function and return true for any Drawable it is
18610     * displaying.  This allows animations for those drawables to be
18611     * scheduled.
18612     *
18613     * <p>Be sure to call through to the super class when overriding this
18614     * function.
18615     *
18616     * @param who The Drawable to verify.  Return true if it is one you are
18617     *            displaying, else return the result of calling through to the
18618     *            super class.
18619     *
18620     * @return boolean If true than the Drawable is being displayed in the
18621     *         view; else false and it is not allowed to animate.
18622     *
18623     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
18624     * @see #drawableStateChanged()
18625     */
18626    @CallSuper
18627    protected boolean verifyDrawable(@NonNull Drawable who) {
18628        // Avoid verifying the scroll bar drawable so that we don't end up in
18629        // an invalidation loop. This effectively prevents the scroll bar
18630        // drawable from triggering invalidations and scheduling runnables.
18631        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
18632    }
18633
18634    /**
18635     * This function is called whenever the state of the view changes in such
18636     * a way that it impacts the state of drawables being shown.
18637     * <p>
18638     * If the View has a StateListAnimator, it will also be called to run necessary state
18639     * change animations.
18640     * <p>
18641     * Be sure to call through to the superclass when overriding this function.
18642     *
18643     * @see Drawable#setState(int[])
18644     */
18645    @CallSuper
18646    protected void drawableStateChanged() {
18647        final int[] state = getDrawableState();
18648        boolean changed = false;
18649
18650        final Drawable bg = mBackground;
18651        if (bg != null && bg.isStateful()) {
18652            changed |= bg.setState(state);
18653        }
18654
18655        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18656        if (fg != null && fg.isStateful()) {
18657            changed |= fg.setState(state);
18658        }
18659
18660        if (mScrollCache != null) {
18661            final Drawable scrollBar = mScrollCache.scrollBar;
18662            if (scrollBar != null && scrollBar.isStateful()) {
18663                changed |= scrollBar.setState(state)
18664                        && mScrollCache.state != ScrollabilityCache.OFF;
18665            }
18666        }
18667
18668        if (mStateListAnimator != null) {
18669            mStateListAnimator.setState(state);
18670        }
18671
18672        if (changed) {
18673            invalidate();
18674        }
18675    }
18676
18677    /**
18678     * This function is called whenever the view hotspot changes and needs to
18679     * be propagated to drawables or child views managed by the view.
18680     * <p>
18681     * Dispatching to child views is handled by
18682     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18683     * <p>
18684     * Be sure to call through to the superclass when overriding this function.
18685     *
18686     * @param x hotspot x coordinate
18687     * @param y hotspot y coordinate
18688     */
18689    @CallSuper
18690    public void drawableHotspotChanged(float x, float y) {
18691        if (mBackground != null) {
18692            mBackground.setHotspot(x, y);
18693        }
18694        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18695            mForegroundInfo.mDrawable.setHotspot(x, y);
18696        }
18697
18698        dispatchDrawableHotspotChanged(x, y);
18699    }
18700
18701    /**
18702     * Dispatches drawableHotspotChanged to all of this View's children.
18703     *
18704     * @param x hotspot x coordinate
18705     * @param y hotspot y coordinate
18706     * @see #drawableHotspotChanged(float, float)
18707     */
18708    public void dispatchDrawableHotspotChanged(float x, float y) {
18709    }
18710
18711    /**
18712     * Call this to force a view to update its drawable state. This will cause
18713     * drawableStateChanged to be called on this view. Views that are interested
18714     * in the new state should call getDrawableState.
18715     *
18716     * @see #drawableStateChanged
18717     * @see #getDrawableState
18718     */
18719    public void refreshDrawableState() {
18720        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18721        drawableStateChanged();
18722
18723        ViewParent parent = mParent;
18724        if (parent != null) {
18725            parent.childDrawableStateChanged(this);
18726        }
18727    }
18728
18729    /**
18730     * Return an array of resource IDs of the drawable states representing the
18731     * current state of the view.
18732     *
18733     * @return The current drawable state
18734     *
18735     * @see Drawable#setState(int[])
18736     * @see #drawableStateChanged()
18737     * @see #onCreateDrawableState(int)
18738     */
18739    public final int[] getDrawableState() {
18740        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
18741            return mDrawableState;
18742        } else {
18743            mDrawableState = onCreateDrawableState(0);
18744            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
18745            return mDrawableState;
18746        }
18747    }
18748
18749    /**
18750     * Generate the new {@link android.graphics.drawable.Drawable} state for
18751     * this view. This is called by the view
18752     * system when the cached Drawable state is determined to be invalid.  To
18753     * retrieve the current state, you should use {@link #getDrawableState}.
18754     *
18755     * @param extraSpace if non-zero, this is the number of extra entries you
18756     * would like in the returned array in which you can place your own
18757     * states.
18758     *
18759     * @return Returns an array holding the current {@link Drawable} state of
18760     * the view.
18761     *
18762     * @see #mergeDrawableStates(int[], int[])
18763     */
18764    protected int[] onCreateDrawableState(int extraSpace) {
18765        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
18766                mParent instanceof View) {
18767            return ((View) mParent).onCreateDrawableState(extraSpace);
18768        }
18769
18770        int[] drawableState;
18771
18772        int privateFlags = mPrivateFlags;
18773
18774        int viewStateIndex = 0;
18775        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
18776        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
18777        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
18778        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
18779        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
18780        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
18781        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
18782                ThreadedRenderer.isAvailable()) {
18783            // This is set if HW acceleration is requested, even if the current
18784            // process doesn't allow it.  This is just to allow app preview
18785            // windows to better match their app.
18786            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
18787        }
18788        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
18789
18790        final int privateFlags2 = mPrivateFlags2;
18791        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
18792            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
18793        }
18794        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
18795            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
18796        }
18797
18798        drawableState = StateSet.get(viewStateIndex);
18799
18800        //noinspection ConstantIfStatement
18801        if (false) {
18802            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18803            Log.i("View", toString()
18804                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18805                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18806                    + " fo=" + hasFocus()
18807                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18808                    + " wf=" + hasWindowFocus()
18809                    + ": " + Arrays.toString(drawableState));
18810        }
18811
18812        if (extraSpace == 0) {
18813            return drawableState;
18814        }
18815
18816        final int[] fullState;
18817        if (drawableState != null) {
18818            fullState = new int[drawableState.length + extraSpace];
18819            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18820        } else {
18821            fullState = new int[extraSpace];
18822        }
18823
18824        return fullState;
18825    }
18826
18827    /**
18828     * Merge your own state values in <var>additionalState</var> into the base
18829     * state values <var>baseState</var> that were returned by
18830     * {@link #onCreateDrawableState(int)}.
18831     *
18832     * @param baseState The base state values returned by
18833     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18834     * own additional state values.
18835     *
18836     * @param additionalState The additional state values you would like
18837     * added to <var>baseState</var>; this array is not modified.
18838     *
18839     * @return As a convenience, the <var>baseState</var> array you originally
18840     * passed into the function is returned.
18841     *
18842     * @see #onCreateDrawableState(int)
18843     */
18844    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18845        final int N = baseState.length;
18846        int i = N - 1;
18847        while (i >= 0 && baseState[i] == 0) {
18848            i--;
18849        }
18850        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18851        return baseState;
18852    }
18853
18854    /**
18855     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18856     * on all Drawable objects associated with this view.
18857     * <p>
18858     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18859     * attached to this view.
18860     */
18861    @CallSuper
18862    public void jumpDrawablesToCurrentState() {
18863        if (mBackground != null) {
18864            mBackground.jumpToCurrentState();
18865        }
18866        if (mStateListAnimator != null) {
18867            mStateListAnimator.jumpToCurrentState();
18868        }
18869        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18870            mForegroundInfo.mDrawable.jumpToCurrentState();
18871        }
18872    }
18873
18874    /**
18875     * Sets the background color for this view.
18876     * @param color the color of the background
18877     */
18878    @RemotableViewMethod
18879    public void setBackgroundColor(@ColorInt int color) {
18880        if (mBackground instanceof ColorDrawable) {
18881            ((ColorDrawable) mBackground.mutate()).setColor(color);
18882            computeOpaqueFlags();
18883            mBackgroundResource = 0;
18884        } else {
18885            setBackground(new ColorDrawable(color));
18886        }
18887    }
18888
18889    /**
18890     * Set the background to a given resource. The resource should refer to
18891     * a Drawable object or 0 to remove the background.
18892     * @param resid The identifier of the resource.
18893     *
18894     * @attr ref android.R.styleable#View_background
18895     */
18896    @RemotableViewMethod
18897    public void setBackgroundResource(@DrawableRes int resid) {
18898        if (resid != 0 && resid == mBackgroundResource) {
18899            return;
18900        }
18901
18902        Drawable d = null;
18903        if (resid != 0) {
18904            d = mContext.getDrawable(resid);
18905        }
18906        setBackground(d);
18907
18908        mBackgroundResource = resid;
18909    }
18910
18911    /**
18912     * Set the background to a given Drawable, or remove the background. If the
18913     * background has padding, this View's padding is set to the background's
18914     * padding. However, when a background is removed, this View's padding isn't
18915     * touched. If setting the padding is desired, please use
18916     * {@link #setPadding(int, int, int, int)}.
18917     *
18918     * @param background The Drawable to use as the background, or null to remove the
18919     *        background
18920     */
18921    public void setBackground(Drawable background) {
18922        //noinspection deprecation
18923        setBackgroundDrawable(background);
18924    }
18925
18926    /**
18927     * @deprecated use {@link #setBackground(Drawable)} instead
18928     */
18929    @Deprecated
18930    public void setBackgroundDrawable(Drawable background) {
18931        computeOpaqueFlags();
18932
18933        if (background == mBackground) {
18934            return;
18935        }
18936
18937        boolean requestLayout = false;
18938
18939        mBackgroundResource = 0;
18940
18941        /*
18942         * Regardless of whether we're setting a new background or not, we want
18943         * to clear the previous drawable. setVisible first while we still have the callback set.
18944         */
18945        if (mBackground != null) {
18946            if (isAttachedToWindow()) {
18947                mBackground.setVisible(false, false);
18948            }
18949            mBackground.setCallback(null);
18950            unscheduleDrawable(mBackground);
18951        }
18952
18953        if (background != null) {
18954            Rect padding = sThreadLocal.get();
18955            if (padding == null) {
18956                padding = new Rect();
18957                sThreadLocal.set(padding);
18958            }
18959            resetResolvedDrawablesInternal();
18960            background.setLayoutDirection(getLayoutDirection());
18961            if (background.getPadding(padding)) {
18962                resetResolvedPaddingInternal();
18963                switch (background.getLayoutDirection()) {
18964                    case LAYOUT_DIRECTION_RTL:
18965                        mUserPaddingLeftInitial = padding.right;
18966                        mUserPaddingRightInitial = padding.left;
18967                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18968                        break;
18969                    case LAYOUT_DIRECTION_LTR:
18970                    default:
18971                        mUserPaddingLeftInitial = padding.left;
18972                        mUserPaddingRightInitial = padding.right;
18973                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18974                }
18975                mLeftPaddingDefined = false;
18976                mRightPaddingDefined = false;
18977            }
18978
18979            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18980            // if it has a different minimum size, we should layout again
18981            if (mBackground == null
18982                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18983                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18984                requestLayout = true;
18985            }
18986
18987            // Set mBackground before we set this as the callback and start making other
18988            // background drawable state change calls. In particular, the setVisible call below
18989            // can result in drawables attempting to start animations or otherwise invalidate,
18990            // which requires the view set as the callback (us) to recognize the drawable as
18991            // belonging to it as per verifyDrawable.
18992            mBackground = background;
18993            if (background.isStateful()) {
18994                background.setState(getDrawableState());
18995            }
18996            if (isAttachedToWindow()) {
18997                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18998            }
18999
19000            applyBackgroundTint();
19001
19002            // Set callback last, since the view may still be initializing.
19003            background.setCallback(this);
19004
19005            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19006                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19007                requestLayout = true;
19008            }
19009        } else {
19010            /* Remove the background */
19011            mBackground = null;
19012            if ((mViewFlags & WILL_NOT_DRAW) != 0
19013                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
19014                mPrivateFlags |= PFLAG_SKIP_DRAW;
19015            }
19016
19017            /*
19018             * When the background is set, we try to apply its padding to this
19019             * View. When the background is removed, we don't touch this View's
19020             * padding. This is noted in the Javadocs. Hence, we don't need to
19021             * requestLayout(), the invalidate() below is sufficient.
19022             */
19023
19024            // The old background's minimum size could have affected this
19025            // View's layout, so let's requestLayout
19026            requestLayout = true;
19027        }
19028
19029        computeOpaqueFlags();
19030
19031        if (requestLayout) {
19032            requestLayout();
19033        }
19034
19035        mBackgroundSizeChanged = true;
19036        invalidate(true);
19037        invalidateOutline();
19038    }
19039
19040    /**
19041     * Gets the background drawable
19042     *
19043     * @return The drawable used as the background for this view, if any.
19044     *
19045     * @see #setBackground(Drawable)
19046     *
19047     * @attr ref android.R.styleable#View_background
19048     */
19049    public Drawable getBackground() {
19050        return mBackground;
19051    }
19052
19053    /**
19054     * Applies a tint to the background drawable. Does not modify the current tint
19055     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19056     * <p>
19057     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
19058     * mutate the drawable and apply the specified tint and tint mode using
19059     * {@link Drawable#setTintList(ColorStateList)}.
19060     *
19061     * @param tint the tint to apply, may be {@code null} to clear tint
19062     *
19063     * @attr ref android.R.styleable#View_backgroundTint
19064     * @see #getBackgroundTintList()
19065     * @see Drawable#setTintList(ColorStateList)
19066     */
19067    public void setBackgroundTintList(@Nullable ColorStateList tint) {
19068        if (mBackgroundTint == null) {
19069            mBackgroundTint = new TintInfo();
19070        }
19071        mBackgroundTint.mTintList = tint;
19072        mBackgroundTint.mHasTintList = true;
19073
19074        applyBackgroundTint();
19075    }
19076
19077    /**
19078     * Return the tint applied to the background drawable, if specified.
19079     *
19080     * @return the tint applied to the background drawable
19081     * @attr ref android.R.styleable#View_backgroundTint
19082     * @see #setBackgroundTintList(ColorStateList)
19083     */
19084    @Nullable
19085    public ColorStateList getBackgroundTintList() {
19086        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
19087    }
19088
19089    /**
19090     * Specifies the blending mode used to apply the tint specified by
19091     * {@link #setBackgroundTintList(ColorStateList)}} to the background
19092     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19093     *
19094     * @param tintMode the blending mode used to apply the tint, may be
19095     *                 {@code null} to clear tint
19096     * @attr ref android.R.styleable#View_backgroundTintMode
19097     * @see #getBackgroundTintMode()
19098     * @see Drawable#setTintMode(PorterDuff.Mode)
19099     */
19100    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19101        if (mBackgroundTint == null) {
19102            mBackgroundTint = new TintInfo();
19103        }
19104        mBackgroundTint.mTintMode = tintMode;
19105        mBackgroundTint.mHasTintMode = true;
19106
19107        applyBackgroundTint();
19108    }
19109
19110    /**
19111     * Return the blending mode used to apply the tint to the background
19112     * drawable, if specified.
19113     *
19114     * @return the blending mode used to apply the tint to the background
19115     *         drawable
19116     * @attr ref android.R.styleable#View_backgroundTintMode
19117     * @see #setBackgroundTintMode(PorterDuff.Mode)
19118     */
19119    @Nullable
19120    public PorterDuff.Mode getBackgroundTintMode() {
19121        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
19122    }
19123
19124    private void applyBackgroundTint() {
19125        if (mBackground != null && mBackgroundTint != null) {
19126            final TintInfo tintInfo = mBackgroundTint;
19127            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19128                mBackground = mBackground.mutate();
19129
19130                if (tintInfo.mHasTintList) {
19131                    mBackground.setTintList(tintInfo.mTintList);
19132                }
19133
19134                if (tintInfo.mHasTintMode) {
19135                    mBackground.setTintMode(tintInfo.mTintMode);
19136                }
19137
19138                // The drawable (or one of its children) may not have been
19139                // stateful before applying the tint, so let's try again.
19140                if (mBackground.isStateful()) {
19141                    mBackground.setState(getDrawableState());
19142                }
19143            }
19144        }
19145    }
19146
19147    /**
19148     * Returns the drawable used as the foreground of this View. The
19149     * foreground drawable, if non-null, is always drawn on top of the view's content.
19150     *
19151     * @return a Drawable or null if no foreground was set
19152     *
19153     * @see #onDrawForeground(Canvas)
19154     */
19155    public Drawable getForeground() {
19156        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19157    }
19158
19159    /**
19160     * Supply a Drawable that is to be rendered on top of all of the content in the view.
19161     *
19162     * @param foreground the Drawable to be drawn on top of the children
19163     *
19164     * @attr ref android.R.styleable#View_foreground
19165     */
19166    public void setForeground(Drawable foreground) {
19167        if (mForegroundInfo == null) {
19168            if (foreground == null) {
19169                // Nothing to do.
19170                return;
19171            }
19172            mForegroundInfo = new ForegroundInfo();
19173        }
19174
19175        if (foreground == mForegroundInfo.mDrawable) {
19176            // Nothing to do
19177            return;
19178        }
19179
19180        if (mForegroundInfo.mDrawable != null) {
19181            if (isAttachedToWindow()) {
19182                mForegroundInfo.mDrawable.setVisible(false, false);
19183            }
19184            mForegroundInfo.mDrawable.setCallback(null);
19185            unscheduleDrawable(mForegroundInfo.mDrawable);
19186        }
19187
19188        mForegroundInfo.mDrawable = foreground;
19189        mForegroundInfo.mBoundsChanged = true;
19190        if (foreground != null) {
19191            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19192                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19193            }
19194            foreground.setLayoutDirection(getLayoutDirection());
19195            if (foreground.isStateful()) {
19196                foreground.setState(getDrawableState());
19197            }
19198            applyForegroundTint();
19199            if (isAttachedToWindow()) {
19200                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19201            }
19202            // Set callback last, since the view may still be initializing.
19203            foreground.setCallback(this);
19204        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
19205            mPrivateFlags |= PFLAG_SKIP_DRAW;
19206        }
19207        requestLayout();
19208        invalidate();
19209    }
19210
19211    /**
19212     * Magic bit used to support features of framework-internal window decor implementation details.
19213     * This used to live exclusively in FrameLayout.
19214     *
19215     * @return true if the foreground should draw inside the padding region or false
19216     *         if it should draw inset by the view's padding
19217     * @hide internal use only; only used by FrameLayout and internal screen layouts.
19218     */
19219    public boolean isForegroundInsidePadding() {
19220        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
19221    }
19222
19223    /**
19224     * Describes how the foreground is positioned.
19225     *
19226     * @return foreground gravity.
19227     *
19228     * @see #setForegroundGravity(int)
19229     *
19230     * @attr ref android.R.styleable#View_foregroundGravity
19231     */
19232    public int getForegroundGravity() {
19233        return mForegroundInfo != null ? mForegroundInfo.mGravity
19234                : Gravity.START | Gravity.TOP;
19235    }
19236
19237    /**
19238     * Describes how the foreground is positioned. Defaults to START and TOP.
19239     *
19240     * @param gravity see {@link android.view.Gravity}
19241     *
19242     * @see #getForegroundGravity()
19243     *
19244     * @attr ref android.R.styleable#View_foregroundGravity
19245     */
19246    public void setForegroundGravity(int gravity) {
19247        if (mForegroundInfo == null) {
19248            mForegroundInfo = new ForegroundInfo();
19249        }
19250
19251        if (mForegroundInfo.mGravity != gravity) {
19252            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
19253                gravity |= Gravity.START;
19254            }
19255
19256            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
19257                gravity |= Gravity.TOP;
19258            }
19259
19260            mForegroundInfo.mGravity = gravity;
19261            requestLayout();
19262        }
19263    }
19264
19265    /**
19266     * Applies a tint to the foreground drawable. Does not modify the current tint
19267     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19268     * <p>
19269     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
19270     * mutate the drawable and apply the specified tint and tint mode using
19271     * {@link Drawable#setTintList(ColorStateList)}.
19272     *
19273     * @param tint the tint to apply, may be {@code null} to clear tint
19274     *
19275     * @attr ref android.R.styleable#View_foregroundTint
19276     * @see #getForegroundTintList()
19277     * @see Drawable#setTintList(ColorStateList)
19278     */
19279    public void setForegroundTintList(@Nullable ColorStateList tint) {
19280        if (mForegroundInfo == null) {
19281            mForegroundInfo = new ForegroundInfo();
19282        }
19283        if (mForegroundInfo.mTintInfo == null) {
19284            mForegroundInfo.mTintInfo = new TintInfo();
19285        }
19286        mForegroundInfo.mTintInfo.mTintList = tint;
19287        mForegroundInfo.mTintInfo.mHasTintList = true;
19288
19289        applyForegroundTint();
19290    }
19291
19292    /**
19293     * Return the tint applied to the foreground drawable, if specified.
19294     *
19295     * @return the tint applied to the foreground drawable
19296     * @attr ref android.R.styleable#View_foregroundTint
19297     * @see #setForegroundTintList(ColorStateList)
19298     */
19299    @Nullable
19300    public ColorStateList getForegroundTintList() {
19301        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19302                ? mForegroundInfo.mTintInfo.mTintList : null;
19303    }
19304
19305    /**
19306     * Specifies the blending mode used to apply the tint specified by
19307     * {@link #setForegroundTintList(ColorStateList)}} to the background
19308     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19309     *
19310     * @param tintMode the blending mode used to apply the tint, may be
19311     *                 {@code null} to clear tint
19312     * @attr ref android.R.styleable#View_foregroundTintMode
19313     * @see #getForegroundTintMode()
19314     * @see Drawable#setTintMode(PorterDuff.Mode)
19315     */
19316    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19317        if (mForegroundInfo == null) {
19318            mForegroundInfo = new ForegroundInfo();
19319        }
19320        if (mForegroundInfo.mTintInfo == null) {
19321            mForegroundInfo.mTintInfo = new TintInfo();
19322        }
19323        mForegroundInfo.mTintInfo.mTintMode = tintMode;
19324        mForegroundInfo.mTintInfo.mHasTintMode = true;
19325
19326        applyForegroundTint();
19327    }
19328
19329    /**
19330     * Return the blending mode used to apply the tint to the foreground
19331     * drawable, if specified.
19332     *
19333     * @return the blending mode used to apply the tint to the foreground
19334     *         drawable
19335     * @attr ref android.R.styleable#View_foregroundTintMode
19336     * @see #setForegroundTintMode(PorterDuff.Mode)
19337     */
19338    @Nullable
19339    public PorterDuff.Mode getForegroundTintMode() {
19340        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
19341                ? mForegroundInfo.mTintInfo.mTintMode : null;
19342    }
19343
19344    private void applyForegroundTint() {
19345        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19346                && mForegroundInfo.mTintInfo != null) {
19347            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
19348            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19349                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
19350
19351                if (tintInfo.mHasTintList) {
19352                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
19353                }
19354
19355                if (tintInfo.mHasTintMode) {
19356                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
19357                }
19358
19359                // The drawable (or one of its children) may not have been
19360                // stateful before applying the tint, so let's try again.
19361                if (mForegroundInfo.mDrawable.isStateful()) {
19362                    mForegroundInfo.mDrawable.setState(getDrawableState());
19363                }
19364            }
19365        }
19366    }
19367
19368    /**
19369     * Draw any foreground content for this view.
19370     *
19371     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
19372     * drawable or other view-specific decorations. The foreground is drawn on top of the
19373     * primary view content.</p>
19374     *
19375     * @param canvas canvas to draw into
19376     */
19377    public void onDrawForeground(Canvas canvas) {
19378        onDrawScrollIndicators(canvas);
19379        onDrawScrollBars(canvas);
19380
19381        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19382        if (foreground != null) {
19383            if (mForegroundInfo.mBoundsChanged) {
19384                mForegroundInfo.mBoundsChanged = false;
19385                final Rect selfBounds = mForegroundInfo.mSelfBounds;
19386                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
19387
19388                if (mForegroundInfo.mInsidePadding) {
19389                    selfBounds.set(0, 0, getWidth(), getHeight());
19390                } else {
19391                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
19392                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
19393                }
19394
19395                final int ld = getLayoutDirection();
19396                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
19397                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
19398                foreground.setBounds(overlayBounds);
19399            }
19400
19401            foreground.draw(canvas);
19402        }
19403    }
19404
19405    /**
19406     * Sets the padding. The view may add on the space required to display
19407     * the scrollbars, depending on the style and visibility of the scrollbars.
19408     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
19409     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
19410     * from the values set in this call.
19411     *
19412     * @attr ref android.R.styleable#View_padding
19413     * @attr ref android.R.styleable#View_paddingBottom
19414     * @attr ref android.R.styleable#View_paddingLeft
19415     * @attr ref android.R.styleable#View_paddingRight
19416     * @attr ref android.R.styleable#View_paddingTop
19417     * @param left the left padding in pixels
19418     * @param top the top padding in pixels
19419     * @param right the right padding in pixels
19420     * @param bottom the bottom padding in pixels
19421     */
19422    public void setPadding(int left, int top, int right, int bottom) {
19423        resetResolvedPaddingInternal();
19424
19425        mUserPaddingStart = UNDEFINED_PADDING;
19426        mUserPaddingEnd = UNDEFINED_PADDING;
19427
19428        mUserPaddingLeftInitial = left;
19429        mUserPaddingRightInitial = right;
19430
19431        mLeftPaddingDefined = true;
19432        mRightPaddingDefined = true;
19433
19434        internalSetPadding(left, top, right, bottom);
19435    }
19436
19437    /**
19438     * @hide
19439     */
19440    protected void internalSetPadding(int left, int top, int right, int bottom) {
19441        mUserPaddingLeft = left;
19442        mUserPaddingRight = right;
19443        mUserPaddingBottom = bottom;
19444
19445        final int viewFlags = mViewFlags;
19446        boolean changed = false;
19447
19448        // Common case is there are no scroll bars.
19449        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
19450            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
19451                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
19452                        ? 0 : getVerticalScrollbarWidth();
19453                switch (mVerticalScrollbarPosition) {
19454                    case SCROLLBAR_POSITION_DEFAULT:
19455                        if (isLayoutRtl()) {
19456                            left += offset;
19457                        } else {
19458                            right += offset;
19459                        }
19460                        break;
19461                    case SCROLLBAR_POSITION_RIGHT:
19462                        right += offset;
19463                        break;
19464                    case SCROLLBAR_POSITION_LEFT:
19465                        left += offset;
19466                        break;
19467                }
19468            }
19469            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
19470                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
19471                        ? 0 : getHorizontalScrollbarHeight();
19472            }
19473        }
19474
19475        if (mPaddingLeft != left) {
19476            changed = true;
19477            mPaddingLeft = left;
19478        }
19479        if (mPaddingTop != top) {
19480            changed = true;
19481            mPaddingTop = top;
19482        }
19483        if (mPaddingRight != right) {
19484            changed = true;
19485            mPaddingRight = right;
19486        }
19487        if (mPaddingBottom != bottom) {
19488            changed = true;
19489            mPaddingBottom = bottom;
19490        }
19491
19492        if (changed) {
19493            requestLayout();
19494            invalidateOutline();
19495        }
19496    }
19497
19498    /**
19499     * Sets the relative padding. The view may add on the space required to display
19500     * the scrollbars, depending on the style and visibility of the scrollbars.
19501     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
19502     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
19503     * from the values set in this call.
19504     *
19505     * @attr ref android.R.styleable#View_padding
19506     * @attr ref android.R.styleable#View_paddingBottom
19507     * @attr ref android.R.styleable#View_paddingStart
19508     * @attr ref android.R.styleable#View_paddingEnd
19509     * @attr ref android.R.styleable#View_paddingTop
19510     * @param start the start padding in pixels
19511     * @param top the top padding in pixels
19512     * @param end the end padding in pixels
19513     * @param bottom the bottom padding in pixels
19514     */
19515    public void setPaddingRelative(int start, int top, int end, int bottom) {
19516        resetResolvedPaddingInternal();
19517
19518        mUserPaddingStart = start;
19519        mUserPaddingEnd = end;
19520        mLeftPaddingDefined = true;
19521        mRightPaddingDefined = true;
19522
19523        switch(getLayoutDirection()) {
19524            case LAYOUT_DIRECTION_RTL:
19525                mUserPaddingLeftInitial = end;
19526                mUserPaddingRightInitial = start;
19527                internalSetPadding(end, top, start, bottom);
19528                break;
19529            case LAYOUT_DIRECTION_LTR:
19530            default:
19531                mUserPaddingLeftInitial = start;
19532                mUserPaddingRightInitial = end;
19533                internalSetPadding(start, top, end, bottom);
19534        }
19535    }
19536
19537    /**
19538     * Returns the top padding of this view.
19539     *
19540     * @return the top padding in pixels
19541     */
19542    public int getPaddingTop() {
19543        return mPaddingTop;
19544    }
19545
19546    /**
19547     * Returns the bottom padding of this view. If there are inset and enabled
19548     * scrollbars, this value may include the space required to display the
19549     * scrollbars as well.
19550     *
19551     * @return the bottom padding in pixels
19552     */
19553    public int getPaddingBottom() {
19554        return mPaddingBottom;
19555    }
19556
19557    /**
19558     * Returns the left padding of this view. If there are inset and enabled
19559     * scrollbars, this value may include the space required to display the
19560     * scrollbars as well.
19561     *
19562     * @return the left padding in pixels
19563     */
19564    public int getPaddingLeft() {
19565        if (!isPaddingResolved()) {
19566            resolvePadding();
19567        }
19568        return mPaddingLeft;
19569    }
19570
19571    /**
19572     * Returns the start padding of this view depending on its resolved layout direction.
19573     * If there are inset and enabled scrollbars, this value may include the space
19574     * required to display the scrollbars as well.
19575     *
19576     * @return the start padding in pixels
19577     */
19578    public int getPaddingStart() {
19579        if (!isPaddingResolved()) {
19580            resolvePadding();
19581        }
19582        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19583                mPaddingRight : mPaddingLeft;
19584    }
19585
19586    /**
19587     * Returns the right padding of this view. If there are inset and enabled
19588     * scrollbars, this value may include the space required to display the
19589     * scrollbars as well.
19590     *
19591     * @return the right padding in pixels
19592     */
19593    public int getPaddingRight() {
19594        if (!isPaddingResolved()) {
19595            resolvePadding();
19596        }
19597        return mPaddingRight;
19598    }
19599
19600    /**
19601     * Returns the end padding of this view depending on its resolved layout direction.
19602     * If there are inset and enabled scrollbars, this value may include the space
19603     * required to display the scrollbars as well.
19604     *
19605     * @return the end padding in pixels
19606     */
19607    public int getPaddingEnd() {
19608        if (!isPaddingResolved()) {
19609            resolvePadding();
19610        }
19611        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
19612                mPaddingLeft : mPaddingRight;
19613    }
19614
19615    /**
19616     * Return if the padding has been set through relative values
19617     * {@link #setPaddingRelative(int, int, int, int)} or through
19618     * @attr ref android.R.styleable#View_paddingStart or
19619     * @attr ref android.R.styleable#View_paddingEnd
19620     *
19621     * @return true if the padding is relative or false if it is not.
19622     */
19623    public boolean isPaddingRelative() {
19624        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
19625    }
19626
19627    Insets computeOpticalInsets() {
19628        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
19629    }
19630
19631    /**
19632     * @hide
19633     */
19634    public void resetPaddingToInitialValues() {
19635        if (isRtlCompatibilityMode()) {
19636            mPaddingLeft = mUserPaddingLeftInitial;
19637            mPaddingRight = mUserPaddingRightInitial;
19638            return;
19639        }
19640        if (isLayoutRtl()) {
19641            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
19642            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
19643        } else {
19644            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
19645            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
19646        }
19647    }
19648
19649    /**
19650     * @hide
19651     */
19652    public Insets getOpticalInsets() {
19653        if (mLayoutInsets == null) {
19654            mLayoutInsets = computeOpticalInsets();
19655        }
19656        return mLayoutInsets;
19657    }
19658
19659    /**
19660     * Set this view's optical insets.
19661     *
19662     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
19663     * property. Views that compute their own optical insets should call it as part of measurement.
19664     * This method does not request layout. If you are setting optical insets outside of
19665     * measure/layout itself you will want to call requestLayout() yourself.
19666     * </p>
19667     * @hide
19668     */
19669    public void setOpticalInsets(Insets insets) {
19670        mLayoutInsets = insets;
19671    }
19672
19673    /**
19674     * Changes the selection state of this view. A view can be selected or not.
19675     * Note that selection is not the same as focus. Views are typically
19676     * selected in the context of an AdapterView like ListView or GridView;
19677     * the selected view is the view that is highlighted.
19678     *
19679     * @param selected true if the view must be selected, false otherwise
19680     */
19681    public void setSelected(boolean selected) {
19682        //noinspection DoubleNegation
19683        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19684            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19685            if (!selected) resetPressedState();
19686            invalidate(true);
19687            refreshDrawableState();
19688            dispatchSetSelected(selected);
19689            if (selected) {
19690                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19691            } else {
19692                notifyViewAccessibilityStateChangedIfNeeded(
19693                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19694            }
19695        }
19696    }
19697
19698    /**
19699     * Dispatch setSelected to all of this View's children.
19700     *
19701     * @see #setSelected(boolean)
19702     *
19703     * @param selected The new selected state
19704     */
19705    protected void dispatchSetSelected(boolean selected) {
19706    }
19707
19708    /**
19709     * Indicates the selection state of this view.
19710     *
19711     * @return true if the view is selected, false otherwise
19712     */
19713    @ViewDebug.ExportedProperty
19714    public boolean isSelected() {
19715        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19716    }
19717
19718    /**
19719     * Changes the activated state of this view. A view can be activated or not.
19720     * Note that activation is not the same as selection.  Selection is
19721     * a transient property, representing the view (hierarchy) the user is
19722     * currently interacting with.  Activation is a longer-term state that the
19723     * user can move views in and out of.  For example, in a list view with
19724     * single or multiple selection enabled, the views in the current selection
19725     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19726     * here.)  The activated state is propagated down to children of the view it
19727     * is set on.
19728     *
19729     * @param activated true if the view must be activated, false otherwise
19730     */
19731    public void setActivated(boolean activated) {
19732        //noinspection DoubleNegation
19733        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19734            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19735            invalidate(true);
19736            refreshDrawableState();
19737            dispatchSetActivated(activated);
19738        }
19739    }
19740
19741    /**
19742     * Dispatch setActivated to all of this View's children.
19743     *
19744     * @see #setActivated(boolean)
19745     *
19746     * @param activated The new activated state
19747     */
19748    protected void dispatchSetActivated(boolean activated) {
19749    }
19750
19751    /**
19752     * Indicates the activation state of this view.
19753     *
19754     * @return true if the view is activated, false otherwise
19755     */
19756    @ViewDebug.ExportedProperty
19757    public boolean isActivated() {
19758        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
19759    }
19760
19761    /**
19762     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
19763     * observer can be used to get notifications when global events, like
19764     * layout, happen.
19765     *
19766     * The returned ViewTreeObserver observer is not guaranteed to remain
19767     * valid for the lifetime of this View. If the caller of this method keeps
19768     * a long-lived reference to ViewTreeObserver, it should always check for
19769     * the return value of {@link ViewTreeObserver#isAlive()}.
19770     *
19771     * @return The ViewTreeObserver for this view's hierarchy.
19772     */
19773    public ViewTreeObserver getViewTreeObserver() {
19774        if (mAttachInfo != null) {
19775            return mAttachInfo.mTreeObserver;
19776        }
19777        if (mFloatingTreeObserver == null) {
19778            mFloatingTreeObserver = new ViewTreeObserver(mContext);
19779        }
19780        return mFloatingTreeObserver;
19781    }
19782
19783    /**
19784     * <p>Finds the topmost view in the current view hierarchy.</p>
19785     *
19786     * @return the topmost view containing this view
19787     */
19788    public View getRootView() {
19789        if (mAttachInfo != null) {
19790            final View v = mAttachInfo.mRootView;
19791            if (v != null) {
19792                return v;
19793            }
19794        }
19795
19796        View parent = this;
19797
19798        while (parent.mParent != null && parent.mParent instanceof View) {
19799            parent = (View) parent.mParent;
19800        }
19801
19802        return parent;
19803    }
19804
19805    /**
19806     * Transforms a motion event from view-local coordinates to on-screen
19807     * coordinates.
19808     *
19809     * @param ev the view-local motion event
19810     * @return false if the transformation could not be applied
19811     * @hide
19812     */
19813    public boolean toGlobalMotionEvent(MotionEvent ev) {
19814        final AttachInfo info = mAttachInfo;
19815        if (info == null) {
19816            return false;
19817        }
19818
19819        final Matrix m = info.mTmpMatrix;
19820        m.set(Matrix.IDENTITY_MATRIX);
19821        transformMatrixToGlobal(m);
19822        ev.transform(m);
19823        return true;
19824    }
19825
19826    /**
19827     * Transforms a motion event from on-screen coordinates to view-local
19828     * coordinates.
19829     *
19830     * @param ev the on-screen motion event
19831     * @return false if the transformation could not be applied
19832     * @hide
19833     */
19834    public boolean toLocalMotionEvent(MotionEvent ev) {
19835        final AttachInfo info = mAttachInfo;
19836        if (info == null) {
19837            return false;
19838        }
19839
19840        final Matrix m = info.mTmpMatrix;
19841        m.set(Matrix.IDENTITY_MATRIX);
19842        transformMatrixToLocal(m);
19843        ev.transform(m);
19844        return true;
19845    }
19846
19847    /**
19848     * Modifies the input matrix such that it maps view-local coordinates to
19849     * on-screen coordinates.
19850     *
19851     * @param m input matrix to modify
19852     * @hide
19853     */
19854    public void transformMatrixToGlobal(Matrix m) {
19855        final ViewParent parent = mParent;
19856        if (parent instanceof View) {
19857            final View vp = (View) parent;
19858            vp.transformMatrixToGlobal(m);
19859            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19860        } else if (parent instanceof ViewRootImpl) {
19861            final ViewRootImpl vr = (ViewRootImpl) parent;
19862            vr.transformMatrixToGlobal(m);
19863            m.preTranslate(0, -vr.mCurScrollY);
19864        }
19865
19866        m.preTranslate(mLeft, mTop);
19867
19868        if (!hasIdentityMatrix()) {
19869            m.preConcat(getMatrix());
19870        }
19871    }
19872
19873    /**
19874     * Modifies the input matrix such that it maps on-screen coordinates to
19875     * view-local coordinates.
19876     *
19877     * @param m input matrix to modify
19878     * @hide
19879     */
19880    public void transformMatrixToLocal(Matrix m) {
19881        final ViewParent parent = mParent;
19882        if (parent instanceof View) {
19883            final View vp = (View) parent;
19884            vp.transformMatrixToLocal(m);
19885            m.postTranslate(vp.mScrollX, vp.mScrollY);
19886        } else if (parent instanceof ViewRootImpl) {
19887            final ViewRootImpl vr = (ViewRootImpl) parent;
19888            vr.transformMatrixToLocal(m);
19889            m.postTranslate(0, vr.mCurScrollY);
19890        }
19891
19892        m.postTranslate(-mLeft, -mTop);
19893
19894        if (!hasIdentityMatrix()) {
19895            m.postConcat(getInverseMatrix());
19896        }
19897    }
19898
19899    /**
19900     * @hide
19901     */
19902    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19903            @ViewDebug.IntToString(from = 0, to = "x"),
19904            @ViewDebug.IntToString(from = 1, to = "y")
19905    })
19906    public int[] getLocationOnScreen() {
19907        int[] location = new int[2];
19908        getLocationOnScreen(location);
19909        return location;
19910    }
19911
19912    /**
19913     * <p>Computes the coordinates of this view on the screen. The argument
19914     * must be an array of two integers. After the method returns, the array
19915     * contains the x and y location in that order.</p>
19916     *
19917     * @param outLocation an array of two integers in which to hold the coordinates
19918     */
19919    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19920        getLocationInWindow(outLocation);
19921
19922        final AttachInfo info = mAttachInfo;
19923        if (info != null) {
19924            outLocation[0] += info.mWindowLeft;
19925            outLocation[1] += info.mWindowTop;
19926        }
19927    }
19928
19929    /**
19930     * <p>Computes the coordinates of this view in its window. The argument
19931     * must be an array of two integers. After the method returns, the array
19932     * contains the x and y location in that order.</p>
19933     *
19934     * @param outLocation an array of two integers in which to hold the coordinates
19935     */
19936    public void getLocationInWindow(@Size(2) int[] outLocation) {
19937        if (outLocation == null || outLocation.length < 2) {
19938            throw new IllegalArgumentException("outLocation must be an array of two integers");
19939        }
19940
19941        outLocation[0] = 0;
19942        outLocation[1] = 0;
19943
19944        transformFromViewToWindowSpace(outLocation);
19945    }
19946
19947    /** @hide */
19948    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19949        if (inOutLocation == null || inOutLocation.length < 2) {
19950            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19951        }
19952
19953        if (mAttachInfo == null) {
19954            // When the view is not attached to a window, this method does not make sense
19955            inOutLocation[0] = inOutLocation[1] = 0;
19956            return;
19957        }
19958
19959        float position[] = mAttachInfo.mTmpTransformLocation;
19960        position[0] = inOutLocation[0];
19961        position[1] = inOutLocation[1];
19962
19963        if (!hasIdentityMatrix()) {
19964            getMatrix().mapPoints(position);
19965        }
19966
19967        position[0] += mLeft;
19968        position[1] += mTop;
19969
19970        ViewParent viewParent = mParent;
19971        while (viewParent instanceof View) {
19972            final View view = (View) viewParent;
19973
19974            position[0] -= view.mScrollX;
19975            position[1] -= view.mScrollY;
19976
19977            if (!view.hasIdentityMatrix()) {
19978                view.getMatrix().mapPoints(position);
19979            }
19980
19981            position[0] += view.mLeft;
19982            position[1] += view.mTop;
19983
19984            viewParent = view.mParent;
19985         }
19986
19987        if (viewParent instanceof ViewRootImpl) {
19988            // *cough*
19989            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19990            position[1] -= vr.mCurScrollY;
19991        }
19992
19993        inOutLocation[0] = Math.round(position[0]);
19994        inOutLocation[1] = Math.round(position[1]);
19995    }
19996
19997    /**
19998     * {@hide}
19999     * @param id the id of the view to be found
20000     * @return the view of the specified id, null if cannot be found
20001     */
20002    protected View findViewTraversal(@IdRes int id) {
20003        if (id == mID) {
20004            return this;
20005        }
20006        return null;
20007    }
20008
20009    /**
20010     * {@hide}
20011     * @param tag the tag of the view to be found
20012     * @return the view of specified tag, null if cannot be found
20013     */
20014    protected View findViewWithTagTraversal(Object tag) {
20015        if (tag != null && tag.equals(mTag)) {
20016            return this;
20017        }
20018        return null;
20019    }
20020
20021    /**
20022     * {@hide}
20023     * @param predicate The predicate to evaluate.
20024     * @param childToSkip If not null, ignores this child during the recursive traversal.
20025     * @return The first view that matches the predicate or null.
20026     */
20027    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
20028        if (predicate.apply(this)) {
20029            return this;
20030        }
20031        return null;
20032    }
20033
20034    /**
20035     * Look for a child view with the given id.  If this view has the given
20036     * id, return this view.
20037     *
20038     * @param id The id to search for.
20039     * @return The view that has the given id in the hierarchy or null
20040     */
20041    @Nullable
20042    public final View findViewById(@IdRes int id) {
20043        if (id < 0) {
20044            return null;
20045        }
20046        return findViewTraversal(id);
20047    }
20048
20049    /**
20050     * Finds a view by its unuque and stable accessibility id.
20051     *
20052     * @param accessibilityId The searched accessibility id.
20053     * @return The found view.
20054     */
20055    final View findViewByAccessibilityId(int accessibilityId) {
20056        if (accessibilityId < 0) {
20057            return null;
20058        }
20059        View view = findViewByAccessibilityIdTraversal(accessibilityId);
20060        if (view != null) {
20061            return view.includeForAccessibility() ? view : null;
20062        }
20063        return null;
20064    }
20065
20066    /**
20067     * Performs the traversal to find a view by its unuque and stable accessibility id.
20068     *
20069     * <strong>Note:</strong>This method does not stop at the root namespace
20070     * boundary since the user can touch the screen at an arbitrary location
20071     * potentially crossing the root namespace bounday which will send an
20072     * accessibility event to accessibility services and they should be able
20073     * to obtain the event source. Also accessibility ids are guaranteed to be
20074     * unique in the window.
20075     *
20076     * @param accessibilityId The accessibility id.
20077     * @return The found view.
20078     *
20079     * @hide
20080     */
20081    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
20082        if (getAccessibilityViewId() == accessibilityId) {
20083            return this;
20084        }
20085        return null;
20086    }
20087
20088    /**
20089     * Look for a child view with the given tag.  If this view has the given
20090     * tag, return this view.
20091     *
20092     * @param tag The tag to search for, using "tag.equals(getTag())".
20093     * @return The View that has the given tag in the hierarchy or null
20094     */
20095    public final View findViewWithTag(Object tag) {
20096        if (tag == null) {
20097            return null;
20098        }
20099        return findViewWithTagTraversal(tag);
20100    }
20101
20102    /**
20103     * {@hide}
20104     * Look for a child view that matches the specified predicate.
20105     * If this view matches the predicate, return this view.
20106     *
20107     * @param predicate The predicate to evaluate.
20108     * @return The first view that matches the predicate or null.
20109     */
20110    public final View findViewByPredicate(Predicate<View> predicate) {
20111        return findViewByPredicateTraversal(predicate, null);
20112    }
20113
20114    /**
20115     * {@hide}
20116     * Look for a child view that matches the specified predicate,
20117     * starting with the specified view and its descendents and then
20118     * recusively searching the ancestors and siblings of that view
20119     * until this view is reached.
20120     *
20121     * This method is useful in cases where the predicate does not match
20122     * a single unique view (perhaps multiple views use the same id)
20123     * and we are trying to find the view that is "closest" in scope to the
20124     * starting view.
20125     *
20126     * @param start The view to start from.
20127     * @param predicate The predicate to evaluate.
20128     * @return The first view that matches the predicate or null.
20129     */
20130    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
20131        View childToSkip = null;
20132        for (;;) {
20133            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
20134            if (view != null || start == this) {
20135                return view;
20136            }
20137
20138            ViewParent parent = start.getParent();
20139            if (parent == null || !(parent instanceof View)) {
20140                return null;
20141            }
20142
20143            childToSkip = start;
20144            start = (View) parent;
20145        }
20146    }
20147
20148    /**
20149     * Sets the identifier for this view. The identifier does not have to be
20150     * unique in this view's hierarchy. The identifier should be a positive
20151     * number.
20152     *
20153     * @see #NO_ID
20154     * @see #getId()
20155     * @see #findViewById(int)
20156     *
20157     * @param id a number used to identify the view
20158     *
20159     * @attr ref android.R.styleable#View_id
20160     */
20161    public void setId(@IdRes int id) {
20162        mID = id;
20163        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
20164            mID = generateViewId();
20165        }
20166    }
20167
20168    /**
20169     * {@hide}
20170     *
20171     * @param isRoot true if the view belongs to the root namespace, false
20172     *        otherwise
20173     */
20174    public void setIsRootNamespace(boolean isRoot) {
20175        if (isRoot) {
20176            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
20177        } else {
20178            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
20179        }
20180    }
20181
20182    /**
20183     * {@hide}
20184     *
20185     * @return true if the view belongs to the root namespace, false otherwise
20186     */
20187    public boolean isRootNamespace() {
20188        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
20189    }
20190
20191    /**
20192     * Returns this view's identifier.
20193     *
20194     * @return a positive integer used to identify the view or {@link #NO_ID}
20195     *         if the view has no ID
20196     *
20197     * @see #setId(int)
20198     * @see #findViewById(int)
20199     * @attr ref android.R.styleable#View_id
20200     */
20201    @IdRes
20202    @ViewDebug.CapturedViewProperty
20203    public int getId() {
20204        return mID;
20205    }
20206
20207    /**
20208     * Returns this view's tag.
20209     *
20210     * @return the Object stored in this view as a tag, or {@code null} if not
20211     *         set
20212     *
20213     * @see #setTag(Object)
20214     * @see #getTag(int)
20215     */
20216    @ViewDebug.ExportedProperty
20217    public Object getTag() {
20218        return mTag;
20219    }
20220
20221    /**
20222     * Sets the tag associated with this view. A tag can be used to mark
20223     * a view in its hierarchy and does not have to be unique within the
20224     * hierarchy. Tags can also be used to store data within a view without
20225     * resorting to another data structure.
20226     *
20227     * @param tag an Object to tag the view with
20228     *
20229     * @see #getTag()
20230     * @see #setTag(int, Object)
20231     */
20232    public void setTag(final Object tag) {
20233        mTag = tag;
20234    }
20235
20236    /**
20237     * Returns the tag associated with this view and the specified key.
20238     *
20239     * @param key The key identifying the tag
20240     *
20241     * @return the Object stored in this view as a tag, or {@code null} if not
20242     *         set
20243     *
20244     * @see #setTag(int, Object)
20245     * @see #getTag()
20246     */
20247    public Object getTag(int key) {
20248        if (mKeyedTags != null) return mKeyedTags.get(key);
20249        return null;
20250    }
20251
20252    /**
20253     * Sets a tag associated with this view and a key. A tag can be used
20254     * to mark a view in its hierarchy and does not have to be unique within
20255     * the hierarchy. Tags can also be used to store data within a view
20256     * without resorting to another data structure.
20257     *
20258     * The specified key should be an id declared in the resources of the
20259     * application to ensure it is unique (see the <a
20260     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
20261     * Keys identified as belonging to
20262     * the Android framework or not associated with any package will cause
20263     * an {@link IllegalArgumentException} to be thrown.
20264     *
20265     * @param key The key identifying the tag
20266     * @param tag An Object to tag the view with
20267     *
20268     * @throws IllegalArgumentException If they specified key is not valid
20269     *
20270     * @see #setTag(Object)
20271     * @see #getTag(int)
20272     */
20273    public void setTag(int key, final Object tag) {
20274        // If the package id is 0x00 or 0x01, it's either an undefined package
20275        // or a framework id
20276        if ((key >>> 24) < 2) {
20277            throw new IllegalArgumentException("The key must be an application-specific "
20278                    + "resource id.");
20279        }
20280
20281        setKeyedTag(key, tag);
20282    }
20283
20284    /**
20285     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
20286     * framework id.
20287     *
20288     * @hide
20289     */
20290    public void setTagInternal(int key, Object tag) {
20291        if ((key >>> 24) != 0x1) {
20292            throw new IllegalArgumentException("The key must be a framework-specific "
20293                    + "resource id.");
20294        }
20295
20296        setKeyedTag(key, tag);
20297    }
20298
20299    private void setKeyedTag(int key, Object tag) {
20300        if (mKeyedTags == null) {
20301            mKeyedTags = new SparseArray<Object>(2);
20302        }
20303
20304        mKeyedTags.put(key, tag);
20305    }
20306
20307    /**
20308     * Prints information about this view in the log output, with the tag
20309     * {@link #VIEW_LOG_TAG}.
20310     *
20311     * @hide
20312     */
20313    public void debug() {
20314        debug(0);
20315    }
20316
20317    /**
20318     * Prints information about this view in the log output, with the tag
20319     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
20320     * indentation defined by the <code>depth</code>.
20321     *
20322     * @param depth the indentation level
20323     *
20324     * @hide
20325     */
20326    protected void debug(int depth) {
20327        String output = debugIndent(depth - 1);
20328
20329        output += "+ " + this;
20330        int id = getId();
20331        if (id != -1) {
20332            output += " (id=" + id + ")";
20333        }
20334        Object tag = getTag();
20335        if (tag != null) {
20336            output += " (tag=" + tag + ")";
20337        }
20338        Log.d(VIEW_LOG_TAG, output);
20339
20340        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
20341            output = debugIndent(depth) + " FOCUSED";
20342            Log.d(VIEW_LOG_TAG, output);
20343        }
20344
20345        output = debugIndent(depth);
20346        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
20347                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
20348                + "} ";
20349        Log.d(VIEW_LOG_TAG, output);
20350
20351        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
20352                || mPaddingBottom != 0) {
20353            output = debugIndent(depth);
20354            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
20355                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
20356            Log.d(VIEW_LOG_TAG, output);
20357        }
20358
20359        output = debugIndent(depth);
20360        output += "mMeasureWidth=" + mMeasuredWidth +
20361                " mMeasureHeight=" + mMeasuredHeight;
20362        Log.d(VIEW_LOG_TAG, output);
20363
20364        output = debugIndent(depth);
20365        if (mLayoutParams == null) {
20366            output += "BAD! no layout params";
20367        } else {
20368            output = mLayoutParams.debug(output);
20369        }
20370        Log.d(VIEW_LOG_TAG, output);
20371
20372        output = debugIndent(depth);
20373        output += "flags={";
20374        output += View.printFlags(mViewFlags);
20375        output += "}";
20376        Log.d(VIEW_LOG_TAG, output);
20377
20378        output = debugIndent(depth);
20379        output += "privateFlags={";
20380        output += View.printPrivateFlags(mPrivateFlags);
20381        output += "}";
20382        Log.d(VIEW_LOG_TAG, output);
20383    }
20384
20385    /**
20386     * Creates a string of whitespaces used for indentation.
20387     *
20388     * @param depth the indentation level
20389     * @return a String containing (depth * 2 + 3) * 2 white spaces
20390     *
20391     * @hide
20392     */
20393    protected static String debugIndent(int depth) {
20394        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
20395        for (int i = 0; i < (depth * 2) + 3; i++) {
20396            spaces.append(' ').append(' ');
20397        }
20398        return spaces.toString();
20399    }
20400
20401    /**
20402     * <p>Return the offset of the widget's text baseline from the widget's top
20403     * boundary. If this widget does not support baseline alignment, this
20404     * method returns -1. </p>
20405     *
20406     * @return the offset of the baseline within the widget's bounds or -1
20407     *         if baseline alignment is not supported
20408     */
20409    @ViewDebug.ExportedProperty(category = "layout")
20410    public int getBaseline() {
20411        return -1;
20412    }
20413
20414    /**
20415     * Returns whether the view hierarchy is currently undergoing a layout pass. This
20416     * information is useful to avoid situations such as calling {@link #requestLayout()} during
20417     * a layout pass.
20418     *
20419     * @return whether the view hierarchy is currently undergoing a layout pass
20420     */
20421    public boolean isInLayout() {
20422        ViewRootImpl viewRoot = getViewRootImpl();
20423        return (viewRoot != null && viewRoot.isInLayout());
20424    }
20425
20426    /**
20427     * Call this when something has changed which has invalidated the
20428     * layout of this view. This will schedule a layout pass of the view
20429     * tree. This should not be called while the view hierarchy is currently in a layout
20430     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
20431     * end of the current layout pass (and then layout will run again) or after the current
20432     * frame is drawn and the next layout occurs.
20433     *
20434     * <p>Subclasses which override this method should call the superclass method to
20435     * handle possible request-during-layout errors correctly.</p>
20436     */
20437    @CallSuper
20438    public void requestLayout() {
20439        if (mMeasureCache != null) mMeasureCache.clear();
20440
20441        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
20442            // Only trigger request-during-layout logic if this is the view requesting it,
20443            // not the views in its parent hierarchy
20444            ViewRootImpl viewRoot = getViewRootImpl();
20445            if (viewRoot != null && viewRoot.isInLayout()) {
20446                if (!viewRoot.requestLayoutDuringLayout(this)) {
20447                    return;
20448                }
20449            }
20450            mAttachInfo.mViewRequestingLayout = this;
20451        }
20452
20453        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20454        mPrivateFlags |= PFLAG_INVALIDATED;
20455
20456        if (mParent != null && !mParent.isLayoutRequested()) {
20457            mParent.requestLayout();
20458        }
20459        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
20460            mAttachInfo.mViewRequestingLayout = null;
20461        }
20462    }
20463
20464    /**
20465     * Forces this view to be laid out during the next layout pass.
20466     * This method does not call requestLayout() or forceLayout()
20467     * on the parent.
20468     */
20469    public void forceLayout() {
20470        if (mMeasureCache != null) mMeasureCache.clear();
20471
20472        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
20473        mPrivateFlags |= PFLAG_INVALIDATED;
20474    }
20475
20476    /**
20477     * <p>
20478     * This is called to find out how big a view should be. The parent
20479     * supplies constraint information in the width and height parameters.
20480     * </p>
20481     *
20482     * <p>
20483     * The actual measurement work of a view is performed in
20484     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
20485     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
20486     * </p>
20487     *
20488     *
20489     * @param widthMeasureSpec Horizontal space requirements as imposed by the
20490     *        parent
20491     * @param heightMeasureSpec Vertical space requirements as imposed by the
20492     *        parent
20493     *
20494     * @see #onMeasure(int, int)
20495     */
20496    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
20497        boolean optical = isLayoutModeOptical(this);
20498        if (optical != isLayoutModeOptical(mParent)) {
20499            Insets insets = getOpticalInsets();
20500            int oWidth  = insets.left + insets.right;
20501            int oHeight = insets.top  + insets.bottom;
20502            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
20503            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
20504        }
20505
20506        // Suppress sign extension for the low bytes
20507        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
20508        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
20509
20510        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20511
20512        // Optimize layout by avoiding an extra EXACTLY pass when the view is
20513        // already measured as the correct size. In API 23 and below, this
20514        // extra pass is required to make LinearLayout re-distribute weight.
20515        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
20516                || heightMeasureSpec != mOldHeightMeasureSpec;
20517        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
20518                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
20519        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
20520                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
20521        final boolean needsLayout = specChanged
20522                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
20523
20524        if (forceLayout || needsLayout) {
20525            // first clears the measured dimension flag
20526            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
20527
20528            resolveRtlPropertiesIfNeeded();
20529
20530            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
20531            if (cacheIndex < 0 || sIgnoreMeasureCache) {
20532                // measure ourselves, this should set the measured dimension flag back
20533                onMeasure(widthMeasureSpec, heightMeasureSpec);
20534                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20535            } else {
20536                long value = mMeasureCache.valueAt(cacheIndex);
20537                // Casting a long to int drops the high 32 bits, no mask needed
20538                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
20539                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20540            }
20541
20542            // flag not set, setMeasuredDimension() was not invoked, we raise
20543            // an exception to warn the developer
20544            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
20545                throw new IllegalStateException("View with id " + getId() + ": "
20546                        + getClass().getName() + "#onMeasure() did not set the"
20547                        + " measured dimension by calling"
20548                        + " setMeasuredDimension()");
20549            }
20550
20551            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
20552        }
20553
20554        mOldWidthMeasureSpec = widthMeasureSpec;
20555        mOldHeightMeasureSpec = heightMeasureSpec;
20556
20557        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
20558                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
20559    }
20560
20561    /**
20562     * <p>
20563     * Measure the view and its content to determine the measured width and the
20564     * measured height. This method is invoked by {@link #measure(int, int)} and
20565     * should be overridden by subclasses to provide accurate and efficient
20566     * measurement of their contents.
20567     * </p>
20568     *
20569     * <p>
20570     * <strong>CONTRACT:</strong> When overriding this method, you
20571     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
20572     * measured width and height of this view. Failure to do so will trigger an
20573     * <code>IllegalStateException</code>, thrown by
20574     * {@link #measure(int, int)}. Calling the superclass'
20575     * {@link #onMeasure(int, int)} is a valid use.
20576     * </p>
20577     *
20578     * <p>
20579     * The base class implementation of measure defaults to the background size,
20580     * unless a larger size is allowed by the MeasureSpec. Subclasses should
20581     * override {@link #onMeasure(int, int)} to provide better measurements of
20582     * their content.
20583     * </p>
20584     *
20585     * <p>
20586     * If this method is overridden, it is the subclass's responsibility to make
20587     * sure the measured height and width are at least the view's minimum height
20588     * and width ({@link #getSuggestedMinimumHeight()} and
20589     * {@link #getSuggestedMinimumWidth()}).
20590     * </p>
20591     *
20592     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
20593     *                         The requirements are encoded with
20594     *                         {@link android.view.View.MeasureSpec}.
20595     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
20596     *                         The requirements are encoded with
20597     *                         {@link android.view.View.MeasureSpec}.
20598     *
20599     * @see #getMeasuredWidth()
20600     * @see #getMeasuredHeight()
20601     * @see #setMeasuredDimension(int, int)
20602     * @see #getSuggestedMinimumHeight()
20603     * @see #getSuggestedMinimumWidth()
20604     * @see android.view.View.MeasureSpec#getMode(int)
20605     * @see android.view.View.MeasureSpec#getSize(int)
20606     */
20607    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
20608        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
20609                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
20610    }
20611
20612    /**
20613     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
20614     * measured width and measured height. Failing to do so will trigger an
20615     * exception at measurement time.</p>
20616     *
20617     * @param measuredWidth The measured width of this view.  May be a complex
20618     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20619     * {@link #MEASURED_STATE_TOO_SMALL}.
20620     * @param measuredHeight The measured height of this view.  May be a complex
20621     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20622     * {@link #MEASURED_STATE_TOO_SMALL}.
20623     */
20624    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
20625        boolean optical = isLayoutModeOptical(this);
20626        if (optical != isLayoutModeOptical(mParent)) {
20627            Insets insets = getOpticalInsets();
20628            int opticalWidth  = insets.left + insets.right;
20629            int opticalHeight = insets.top  + insets.bottom;
20630
20631            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
20632            measuredHeight += optical ? opticalHeight : -opticalHeight;
20633        }
20634        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
20635    }
20636
20637    /**
20638     * Sets the measured dimension without extra processing for things like optical bounds.
20639     * Useful for reapplying consistent values that have already been cooked with adjustments
20640     * for optical bounds, etc. such as those from the measurement cache.
20641     *
20642     * @param measuredWidth The measured width of this view.  May be a complex
20643     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20644     * {@link #MEASURED_STATE_TOO_SMALL}.
20645     * @param measuredHeight The measured height of this view.  May be a complex
20646     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
20647     * {@link #MEASURED_STATE_TOO_SMALL}.
20648     */
20649    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
20650        mMeasuredWidth = measuredWidth;
20651        mMeasuredHeight = measuredHeight;
20652
20653        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
20654    }
20655
20656    /**
20657     * Merge two states as returned by {@link #getMeasuredState()}.
20658     * @param curState The current state as returned from a view or the result
20659     * of combining multiple views.
20660     * @param newState The new view state to combine.
20661     * @return Returns a new integer reflecting the combination of the two
20662     * states.
20663     */
20664    public static int combineMeasuredStates(int curState, int newState) {
20665        return curState | newState;
20666    }
20667
20668    /**
20669     * Version of {@link #resolveSizeAndState(int, int, int)}
20670     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
20671     */
20672    public static int resolveSize(int size, int measureSpec) {
20673        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
20674    }
20675
20676    /**
20677     * Utility to reconcile a desired size and state, with constraints imposed
20678     * by a MeasureSpec. Will take the desired size, unless a different size
20679     * is imposed by the constraints. The returned value is a compound integer,
20680     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20681     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20682     * resulting size is smaller than the size the view wants to be.
20683     *
20684     * @param size How big the view wants to be.
20685     * @param measureSpec Constraints imposed by the parent.
20686     * @param childMeasuredState Size information bit mask for the view's
20687     *                           children.
20688     * @return Size information bit mask as defined by
20689     *         {@link #MEASURED_SIZE_MASK} and
20690     *         {@link #MEASURED_STATE_TOO_SMALL}.
20691     */
20692    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20693        final int specMode = MeasureSpec.getMode(measureSpec);
20694        final int specSize = MeasureSpec.getSize(measureSpec);
20695        final int result;
20696        switch (specMode) {
20697            case MeasureSpec.AT_MOST:
20698                if (specSize < size) {
20699                    result = specSize | MEASURED_STATE_TOO_SMALL;
20700                } else {
20701                    result = size;
20702                }
20703                break;
20704            case MeasureSpec.EXACTLY:
20705                result = specSize;
20706                break;
20707            case MeasureSpec.UNSPECIFIED:
20708            default:
20709                result = size;
20710        }
20711        return result | (childMeasuredState & MEASURED_STATE_MASK);
20712    }
20713
20714    /**
20715     * Utility to return a default size. Uses the supplied size if the
20716     * MeasureSpec imposed no constraints. Will get larger if allowed
20717     * by the MeasureSpec.
20718     *
20719     * @param size Default size for this view
20720     * @param measureSpec Constraints imposed by the parent
20721     * @return The size this view should be.
20722     */
20723    public static int getDefaultSize(int size, int measureSpec) {
20724        int result = size;
20725        int specMode = MeasureSpec.getMode(measureSpec);
20726        int specSize = MeasureSpec.getSize(measureSpec);
20727
20728        switch (specMode) {
20729        case MeasureSpec.UNSPECIFIED:
20730            result = size;
20731            break;
20732        case MeasureSpec.AT_MOST:
20733        case MeasureSpec.EXACTLY:
20734            result = specSize;
20735            break;
20736        }
20737        return result;
20738    }
20739
20740    /**
20741     * Returns the suggested minimum height that the view should use. This
20742     * returns the maximum of the view's minimum height
20743     * and the background's minimum height
20744     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
20745     * <p>
20746     * When being used in {@link #onMeasure(int, int)}, the caller should still
20747     * ensure the returned height is within the requirements of the parent.
20748     *
20749     * @return The suggested minimum height of the view.
20750     */
20751    protected int getSuggestedMinimumHeight() {
20752        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
20753
20754    }
20755
20756    /**
20757     * Returns the suggested minimum width that the view should use. This
20758     * returns the maximum of the view's minimum width
20759     * and the background's minimum width
20760     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
20761     * <p>
20762     * When being used in {@link #onMeasure(int, int)}, the caller should still
20763     * ensure the returned width is within the requirements of the parent.
20764     *
20765     * @return The suggested minimum width of the view.
20766     */
20767    protected int getSuggestedMinimumWidth() {
20768        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
20769    }
20770
20771    /**
20772     * Returns the minimum height of the view.
20773     *
20774     * @return the minimum height the view will try to be, in pixels
20775     *
20776     * @see #setMinimumHeight(int)
20777     *
20778     * @attr ref android.R.styleable#View_minHeight
20779     */
20780    public int getMinimumHeight() {
20781        return mMinHeight;
20782    }
20783
20784    /**
20785     * Sets the minimum height of the view. It is not guaranteed the view will
20786     * be able to achieve this minimum height (for example, if its parent layout
20787     * constrains it with less available height).
20788     *
20789     * @param minHeight The minimum height the view will try to be, in pixels
20790     *
20791     * @see #getMinimumHeight()
20792     *
20793     * @attr ref android.R.styleable#View_minHeight
20794     */
20795    @RemotableViewMethod
20796    public void setMinimumHeight(int minHeight) {
20797        mMinHeight = minHeight;
20798        requestLayout();
20799    }
20800
20801    /**
20802     * Returns the minimum width of the view.
20803     *
20804     * @return the minimum width the view will try to be, in pixels
20805     *
20806     * @see #setMinimumWidth(int)
20807     *
20808     * @attr ref android.R.styleable#View_minWidth
20809     */
20810    public int getMinimumWidth() {
20811        return mMinWidth;
20812    }
20813
20814    /**
20815     * Sets the minimum width of the view. It is not guaranteed the view will
20816     * be able to achieve this minimum width (for example, if its parent layout
20817     * constrains it with less available width).
20818     *
20819     * @param minWidth The minimum width the view will try to be, in pixels
20820     *
20821     * @see #getMinimumWidth()
20822     *
20823     * @attr ref android.R.styleable#View_minWidth
20824     */
20825    public void setMinimumWidth(int minWidth) {
20826        mMinWidth = minWidth;
20827        requestLayout();
20828
20829    }
20830
20831    /**
20832     * Get the animation currently associated with this view.
20833     *
20834     * @return The animation that is currently playing or
20835     *         scheduled to play for this view.
20836     */
20837    public Animation getAnimation() {
20838        return mCurrentAnimation;
20839    }
20840
20841    /**
20842     * Start the specified animation now.
20843     *
20844     * @param animation the animation to start now
20845     */
20846    public void startAnimation(Animation animation) {
20847        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20848        setAnimation(animation);
20849        invalidateParentCaches();
20850        invalidate(true);
20851    }
20852
20853    /**
20854     * Cancels any animations for this view.
20855     */
20856    public void clearAnimation() {
20857        if (mCurrentAnimation != null) {
20858            mCurrentAnimation.detach();
20859        }
20860        mCurrentAnimation = null;
20861        invalidateParentIfNeeded();
20862    }
20863
20864    /**
20865     * Sets the next animation to play for this view.
20866     * If you want the animation to play immediately, use
20867     * {@link #startAnimation(android.view.animation.Animation)} instead.
20868     * This method provides allows fine-grained
20869     * control over the start time and invalidation, but you
20870     * must make sure that 1) the animation has a start time set, and
20871     * 2) the view's parent (which controls animations on its children)
20872     * will be invalidated when the animation is supposed to
20873     * start.
20874     *
20875     * @param animation The next animation, or null.
20876     */
20877    public void setAnimation(Animation animation) {
20878        mCurrentAnimation = animation;
20879
20880        if (animation != null) {
20881            // If the screen is off assume the animation start time is now instead of
20882            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20883            // would cause the animation to start when the screen turns back on
20884            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20885                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20886                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20887            }
20888            animation.reset();
20889        }
20890    }
20891
20892    /**
20893     * Invoked by a parent ViewGroup to notify the start of the animation
20894     * currently associated with this view. If you override this method,
20895     * always call super.onAnimationStart();
20896     *
20897     * @see #setAnimation(android.view.animation.Animation)
20898     * @see #getAnimation()
20899     */
20900    @CallSuper
20901    protected void onAnimationStart() {
20902        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20903    }
20904
20905    /**
20906     * Invoked by a parent ViewGroup to notify the end of the animation
20907     * currently associated with this view. If you override this method,
20908     * always call super.onAnimationEnd();
20909     *
20910     * @see #setAnimation(android.view.animation.Animation)
20911     * @see #getAnimation()
20912     */
20913    @CallSuper
20914    protected void onAnimationEnd() {
20915        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20916    }
20917
20918    /**
20919     * Invoked if there is a Transform that involves alpha. Subclass that can
20920     * draw themselves with the specified alpha should return true, and then
20921     * respect that alpha when their onDraw() is called. If this returns false
20922     * then the view may be redirected to draw into an offscreen buffer to
20923     * fulfill the request, which will look fine, but may be slower than if the
20924     * subclass handles it internally. The default implementation returns false.
20925     *
20926     * @param alpha The alpha (0..255) to apply to the view's drawing
20927     * @return true if the view can draw with the specified alpha.
20928     */
20929    protected boolean onSetAlpha(int alpha) {
20930        return false;
20931    }
20932
20933    /**
20934     * This is used by the RootView to perform an optimization when
20935     * the view hierarchy contains one or several SurfaceView.
20936     * SurfaceView is always considered transparent, but its children are not,
20937     * therefore all View objects remove themselves from the global transparent
20938     * region (passed as a parameter to this function).
20939     *
20940     * @param region The transparent region for this ViewAncestor (window).
20941     *
20942     * @return Returns true if the effective visibility of the view at this
20943     * point is opaque, regardless of the transparent region; returns false
20944     * if it is possible for underlying windows to be seen behind the view.
20945     *
20946     * {@hide}
20947     */
20948    public boolean gatherTransparentRegion(Region region) {
20949        final AttachInfo attachInfo = mAttachInfo;
20950        if (region != null && attachInfo != null) {
20951            final int pflags = mPrivateFlags;
20952            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20953                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20954                // remove it from the transparent region.
20955                final int[] location = attachInfo.mTransparentLocation;
20956                getLocationInWindow(location);
20957                // When a view has Z value, then it will be better to leave some area below the view
20958                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
20959                // the bottom part needs more offset than the left, top and right parts due to the
20960                // spot light effects.
20961                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
20962                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
20963                        location[0] + mRight - mLeft + shadowOffset,
20964                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
20965            } else {
20966                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20967                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20968                    // the background drawable's non-transparent parts from this transparent region.
20969                    applyDrawableToTransparentRegion(mBackground, region);
20970                }
20971                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20972                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20973                    // Similarly, we remove the foreground drawable's non-transparent parts.
20974                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20975                }
20976            }
20977        }
20978        return true;
20979    }
20980
20981    /**
20982     * Play a sound effect for this view.
20983     *
20984     * <p>The framework will play sound effects for some built in actions, such as
20985     * clicking, but you may wish to play these effects in your widget,
20986     * for instance, for internal navigation.
20987     *
20988     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20989     * {@link #isSoundEffectsEnabled()} is true.
20990     *
20991     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20992     */
20993    public void playSoundEffect(int soundConstant) {
20994        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20995            return;
20996        }
20997        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20998    }
20999
21000    /**
21001     * BZZZTT!!1!
21002     *
21003     * <p>Provide haptic feedback to the user for this view.
21004     *
21005     * <p>The framework will provide haptic feedback for some built in actions,
21006     * such as long presses, but you may wish to provide feedback for your
21007     * own widget.
21008     *
21009     * <p>The feedback will only be performed if
21010     * {@link #isHapticFeedbackEnabled()} is true.
21011     *
21012     * @param feedbackConstant One of the constants defined in
21013     * {@link HapticFeedbackConstants}
21014     */
21015    public boolean performHapticFeedback(int feedbackConstant) {
21016        return performHapticFeedback(feedbackConstant, 0);
21017    }
21018
21019    /**
21020     * BZZZTT!!1!
21021     *
21022     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
21023     *
21024     * @param feedbackConstant One of the constants defined in
21025     * {@link HapticFeedbackConstants}
21026     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
21027     */
21028    public boolean performHapticFeedback(int feedbackConstant, int flags) {
21029        if (mAttachInfo == null) {
21030            return false;
21031        }
21032        //noinspection SimplifiableIfStatement
21033        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
21034                && !isHapticFeedbackEnabled()) {
21035            return false;
21036        }
21037        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
21038                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
21039    }
21040
21041    /**
21042     * Request that the visibility of the status bar or other screen/window
21043     * decorations be changed.
21044     *
21045     * <p>This method is used to put the over device UI into temporary modes
21046     * where the user's attention is focused more on the application content,
21047     * by dimming or hiding surrounding system affordances.  This is typically
21048     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
21049     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
21050     * to be placed behind the action bar (and with these flags other system
21051     * affordances) so that smooth transitions between hiding and showing them
21052     * can be done.
21053     *
21054     * <p>Two representative examples of the use of system UI visibility is
21055     * implementing a content browsing application (like a magazine reader)
21056     * and a video playing application.
21057     *
21058     * <p>The first code shows a typical implementation of a View in a content
21059     * browsing application.  In this implementation, the application goes
21060     * into a content-oriented mode by hiding the status bar and action bar,
21061     * and putting the navigation elements into lights out mode.  The user can
21062     * then interact with content while in this mode.  Such an application should
21063     * provide an easy way for the user to toggle out of the mode (such as to
21064     * check information in the status bar or access notifications).  In the
21065     * implementation here, this is done simply by tapping on the content.
21066     *
21067     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
21068     *      content}
21069     *
21070     * <p>This second code sample shows a typical implementation of a View
21071     * in a video playing application.  In this situation, while the video is
21072     * playing the application would like to go into a complete full-screen mode,
21073     * to use as much of the display as possible for the video.  When in this state
21074     * the user can not interact with the application; the system intercepts
21075     * touching on the screen to pop the UI out of full screen mode.  See
21076     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
21077     *
21078     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
21079     *      content}
21080     *
21081     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21082     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21083     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21084     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21085     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21086     */
21087    public void setSystemUiVisibility(int visibility) {
21088        if (visibility != mSystemUiVisibility) {
21089            mSystemUiVisibility = visibility;
21090            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21091                mParent.recomputeViewAttributes(this);
21092            }
21093        }
21094    }
21095
21096    /**
21097     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
21098     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21099     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21100     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21101     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21102     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21103     */
21104    public int getSystemUiVisibility() {
21105        return mSystemUiVisibility;
21106    }
21107
21108    /**
21109     * Returns the current system UI visibility that is currently set for
21110     * the entire window.  This is the combination of the
21111     * {@link #setSystemUiVisibility(int)} values supplied by all of the
21112     * views in the window.
21113     */
21114    public int getWindowSystemUiVisibility() {
21115        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
21116    }
21117
21118    /**
21119     * Override to find out when the window's requested system UI visibility
21120     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
21121     * This is different from the callbacks received through
21122     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
21123     * in that this is only telling you about the local request of the window,
21124     * not the actual values applied by the system.
21125     */
21126    public void onWindowSystemUiVisibilityChanged(int visible) {
21127    }
21128
21129    /**
21130     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
21131     * the view hierarchy.
21132     */
21133    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
21134        onWindowSystemUiVisibilityChanged(visible);
21135    }
21136
21137    /**
21138     * Set a listener to receive callbacks when the visibility of the system bar changes.
21139     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
21140     */
21141    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
21142        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
21143        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21144            mParent.recomputeViewAttributes(this);
21145        }
21146    }
21147
21148    /**
21149     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
21150     * the view hierarchy.
21151     */
21152    public void dispatchSystemUiVisibilityChanged(int visibility) {
21153        ListenerInfo li = mListenerInfo;
21154        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
21155            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
21156                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
21157        }
21158    }
21159
21160    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
21161        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
21162        if (val != mSystemUiVisibility) {
21163            setSystemUiVisibility(val);
21164            return true;
21165        }
21166        return false;
21167    }
21168
21169    /** @hide */
21170    public void setDisabledSystemUiVisibility(int flags) {
21171        if (mAttachInfo != null) {
21172            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
21173                mAttachInfo.mDisabledSystemUiVisibility = flags;
21174                if (mParent != null) {
21175                    mParent.recomputeViewAttributes(this);
21176                }
21177            }
21178        }
21179    }
21180
21181    /**
21182     * Creates an image that the system displays during the drag and drop
21183     * operation. This is called a &quot;drag shadow&quot;. The default implementation
21184     * for a DragShadowBuilder based on a View returns an image that has exactly the same
21185     * appearance as the given View. The default also positions the center of the drag shadow
21186     * directly under the touch point. If no View is provided (the constructor with no parameters
21187     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
21188     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
21189     * default is an invisible drag shadow.
21190     * <p>
21191     * You are not required to use the View you provide to the constructor as the basis of the
21192     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
21193     * anything you want as the drag shadow.
21194     * </p>
21195     * <p>
21196     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
21197     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
21198     *  size and position of the drag shadow. It uses this data to construct a
21199     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
21200     *  so that your application can draw the shadow image in the Canvas.
21201     * </p>
21202     *
21203     * <div class="special reference">
21204     * <h3>Developer Guides</h3>
21205     * <p>For a guide to implementing drag and drop features, read the
21206     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
21207     * </div>
21208     */
21209    public static class DragShadowBuilder {
21210        private final WeakReference<View> mView;
21211
21212        /**
21213         * Constructs a shadow image builder based on a View. By default, the resulting drag
21214         * shadow will have the same appearance and dimensions as the View, with the touch point
21215         * over the center of the View.
21216         * @param view A View. Any View in scope can be used.
21217         */
21218        public DragShadowBuilder(View view) {
21219            mView = new WeakReference<View>(view);
21220        }
21221
21222        /**
21223         * Construct a shadow builder object with no associated View.  This
21224         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
21225         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
21226         * to supply the drag shadow's dimensions and appearance without
21227         * reference to any View object. If they are not overridden, then the result is an
21228         * invisible drag shadow.
21229         */
21230        public DragShadowBuilder() {
21231            mView = new WeakReference<View>(null);
21232        }
21233
21234        /**
21235         * Returns the View object that had been passed to the
21236         * {@link #View.DragShadowBuilder(View)}
21237         * constructor.  If that View parameter was {@code null} or if the
21238         * {@link #View.DragShadowBuilder()}
21239         * constructor was used to instantiate the builder object, this method will return
21240         * null.
21241         *
21242         * @return The View object associate with this builder object.
21243         */
21244        @SuppressWarnings({"JavadocReference"})
21245        final public View getView() {
21246            return mView.get();
21247        }
21248
21249        /**
21250         * Provides the metrics for the shadow image. These include the dimensions of
21251         * the shadow image, and the point within that shadow that should
21252         * be centered under the touch location while dragging.
21253         * <p>
21254         * The default implementation sets the dimensions of the shadow to be the
21255         * same as the dimensions of the View itself and centers the shadow under
21256         * the touch point.
21257         * </p>
21258         *
21259         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
21260         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
21261         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
21262         * image.
21263         *
21264         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
21265         * shadow image that should be underneath the touch point during the drag and drop
21266         * operation. Your application must set {@link android.graphics.Point#x} to the
21267         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
21268         */
21269        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
21270            final View view = mView.get();
21271            if (view != null) {
21272                outShadowSize.set(view.getWidth(), view.getHeight());
21273                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
21274            } else {
21275                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
21276            }
21277        }
21278
21279        /**
21280         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
21281         * based on the dimensions it received from the
21282         * {@link #onProvideShadowMetrics(Point, Point)} callback.
21283         *
21284         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
21285         */
21286        public void onDrawShadow(Canvas canvas) {
21287            final View view = mView.get();
21288            if (view != null) {
21289                view.draw(canvas);
21290            } else {
21291                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
21292            }
21293        }
21294    }
21295
21296    /**
21297     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
21298     * startDragAndDrop()} for newer platform versions.
21299     */
21300    @Deprecated
21301    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
21302                                   Object myLocalState, int flags) {
21303        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
21304    }
21305
21306    /**
21307     * Starts a drag and drop operation. When your application calls this method, it passes a
21308     * {@link android.view.View.DragShadowBuilder} object to the system. The
21309     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
21310     * to get metrics for the drag shadow, and then calls the object's
21311     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
21312     * <p>
21313     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
21314     *  drag events to all the View objects in your application that are currently visible. It does
21315     *  this either by calling the View object's drag listener (an implementation of
21316     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
21317     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
21318     *  Both are passed a {@link android.view.DragEvent} object that has a
21319     *  {@link android.view.DragEvent#getAction()} value of
21320     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
21321     * </p>
21322     * <p>
21323     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
21324     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
21325     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
21326     * to the View the user selected for dragging.
21327     * </p>
21328     * @param data A {@link android.content.ClipData} object pointing to the data to be
21329     * transferred by the drag and drop operation.
21330     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21331     * drag shadow.
21332     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
21333     * drop operation. When dispatching drag events to views in the same activity this object
21334     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
21335     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
21336     * will return null).
21337     * <p>
21338     * myLocalState is a lightweight mechanism for the sending information from the dragged View
21339     * to the target Views. For example, it can contain flags that differentiate between a
21340     * a copy operation and a move operation.
21341     * </p>
21342     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
21343     * flags, or any combination of the following:
21344     *     <ul>
21345     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
21346     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
21347     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
21348     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
21349     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
21350     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
21351     *     </ul>
21352     * @return {@code true} if the method completes successfully, or
21353     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
21354     * do a drag, and so no drag operation is in progress.
21355     */
21356    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
21357            Object myLocalState, int flags) {
21358        if (ViewDebug.DEBUG_DRAG) {
21359            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
21360        }
21361        if (mAttachInfo == null) {
21362            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
21363            return false;
21364        }
21365
21366        if (data != null) {
21367            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
21368        }
21369
21370        boolean okay = false;
21371
21372        Point shadowSize = new Point();
21373        Point shadowTouchPoint = new Point();
21374        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
21375
21376        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
21377                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
21378            throw new IllegalStateException("Drag shadow dimensions must not be negative");
21379        }
21380
21381        if (ViewDebug.DEBUG_DRAG) {
21382            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
21383                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
21384        }
21385        if (mAttachInfo.mDragSurface != null) {
21386            mAttachInfo.mDragSurface.release();
21387        }
21388        mAttachInfo.mDragSurface = new Surface();
21389        try {
21390            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
21391                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
21392            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
21393                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
21394            if (mAttachInfo.mDragToken != null) {
21395                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21396                try {
21397                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21398                    shadowBuilder.onDrawShadow(canvas);
21399                } finally {
21400                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21401                }
21402
21403                final ViewRootImpl root = getViewRootImpl();
21404
21405                // Cache the local state object for delivery with DragEvents
21406                root.setLocalDragState(myLocalState);
21407
21408                // repurpose 'shadowSize' for the last touch point
21409                root.getLastTouchPoint(shadowSize);
21410
21411                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
21412                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
21413                        shadowTouchPoint.x, shadowTouchPoint.y, data);
21414                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
21415            }
21416        } catch (Exception e) {
21417            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
21418            mAttachInfo.mDragSurface.destroy();
21419            mAttachInfo.mDragSurface = null;
21420        }
21421
21422        return okay;
21423    }
21424
21425    /**
21426     * Cancels an ongoing drag and drop operation.
21427     * <p>
21428     * A {@link android.view.DragEvent} object with
21429     * {@link android.view.DragEvent#getAction()} value of
21430     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
21431     * {@link android.view.DragEvent#getResult()} value of {@code false}
21432     * will be sent to every
21433     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
21434     * even if they are not currently visible.
21435     * </p>
21436     * <p>
21437     * This method can be called on any View in the same window as the View on which
21438     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
21439     * was called.
21440     * </p>
21441     */
21442    public final void cancelDragAndDrop() {
21443        if (ViewDebug.DEBUG_DRAG) {
21444            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
21445        }
21446        if (mAttachInfo == null) {
21447            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
21448            return;
21449        }
21450        if (mAttachInfo.mDragToken != null) {
21451            try {
21452                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
21453            } catch (Exception e) {
21454                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
21455            }
21456            mAttachInfo.mDragToken = null;
21457        } else {
21458            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
21459        }
21460    }
21461
21462    /**
21463     * Updates the drag shadow for the ongoing drag and drop operation.
21464     *
21465     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
21466     * new drag shadow.
21467     */
21468    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
21469        if (ViewDebug.DEBUG_DRAG) {
21470            Log.d(VIEW_LOG_TAG, "updateDragShadow");
21471        }
21472        if (mAttachInfo == null) {
21473            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
21474            return;
21475        }
21476        if (mAttachInfo.mDragToken != null) {
21477            try {
21478                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
21479                try {
21480                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
21481                    shadowBuilder.onDrawShadow(canvas);
21482                } finally {
21483                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
21484                }
21485            } catch (Exception e) {
21486                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
21487            }
21488        } else {
21489            Log.e(VIEW_LOG_TAG, "No active drag");
21490        }
21491    }
21492
21493    /**
21494     * Starts a move from {startX, startY}, the amount of the movement will be the offset
21495     * between {startX, startY} and the new cursor positon.
21496     * @param startX horizontal coordinate where the move started.
21497     * @param startY vertical coordinate where the move started.
21498     * @return whether moving was started successfully.
21499     * @hide
21500     */
21501    public final boolean startMovingTask(float startX, float startY) {
21502        if (ViewDebug.DEBUG_POSITIONING) {
21503            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
21504        }
21505        try {
21506            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
21507        } catch (RemoteException e) {
21508            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
21509        }
21510        return false;
21511    }
21512
21513    /**
21514     * Handles drag events sent by the system following a call to
21515     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
21516     * startDragAndDrop()}.
21517     *<p>
21518     * When the system calls this method, it passes a
21519     * {@link android.view.DragEvent} object. A call to
21520     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
21521     * in DragEvent. The method uses these to determine what is happening in the drag and drop
21522     * operation.
21523     * @param event The {@link android.view.DragEvent} sent by the system.
21524     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
21525     * in DragEvent, indicating the type of drag event represented by this object.
21526     * @return {@code true} if the method was successful, otherwise {@code false}.
21527     * <p>
21528     *  The method should return {@code true} in response to an action type of
21529     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
21530     *  operation.
21531     * </p>
21532     * <p>
21533     *  The method should also return {@code true} in response to an action type of
21534     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
21535     *  {@code false} if it didn't.
21536     * </p>
21537     * <p>
21538     *  For all other events, the return value is ignored.
21539     * </p>
21540     */
21541    public boolean onDragEvent(DragEvent event) {
21542        return false;
21543    }
21544
21545    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
21546    boolean dispatchDragEnterExitInPreN(DragEvent event) {
21547        return callDragEventHandler(event);
21548    }
21549
21550    /**
21551     * Detects if this View is enabled and has a drag event listener.
21552     * If both are true, then it calls the drag event listener with the
21553     * {@link android.view.DragEvent} it received. If the drag event listener returns
21554     * {@code true}, then dispatchDragEvent() returns {@code true}.
21555     * <p>
21556     * For all other cases, the method calls the
21557     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
21558     * method and returns its result.
21559     * </p>
21560     * <p>
21561     * This ensures that a drag event is always consumed, even if the View does not have a drag
21562     * event listener. However, if the View has a listener and the listener returns true, then
21563     * onDragEvent() is not called.
21564     * </p>
21565     */
21566    public boolean dispatchDragEvent(DragEvent event) {
21567        event.mEventHandlerWasCalled = true;
21568        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
21569            event.mAction == DragEvent.ACTION_DROP) {
21570            // About to deliver an event with coordinates to this view. Notify that now this view
21571            // has drag focus. This will send exit/enter events as needed.
21572            getViewRootImpl().setDragFocus(this, event);
21573        }
21574        return callDragEventHandler(event);
21575    }
21576
21577    final boolean callDragEventHandler(DragEvent event) {
21578        final boolean result;
21579
21580        ListenerInfo li = mListenerInfo;
21581        //noinspection SimplifiableIfStatement
21582        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
21583                && li.mOnDragListener.onDrag(this, event)) {
21584            result = true;
21585        } else {
21586            result = onDragEvent(event);
21587        }
21588
21589        switch (event.mAction) {
21590            case DragEvent.ACTION_DRAG_ENTERED: {
21591                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
21592                refreshDrawableState();
21593            } break;
21594            case DragEvent.ACTION_DRAG_EXITED: {
21595                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
21596                refreshDrawableState();
21597            } break;
21598            case DragEvent.ACTION_DRAG_ENDED: {
21599                mPrivateFlags2 &= ~View.DRAG_MASK;
21600                refreshDrawableState();
21601            } break;
21602        }
21603
21604        return result;
21605    }
21606
21607    boolean canAcceptDrag() {
21608        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
21609    }
21610
21611    /**
21612     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
21613     * it is ever exposed at all.
21614     * @hide
21615     */
21616    public void onCloseSystemDialogs(String reason) {
21617    }
21618
21619    /**
21620     * Given a Drawable whose bounds have been set to draw into this view,
21621     * update a Region being computed for
21622     * {@link #gatherTransparentRegion(android.graphics.Region)} so
21623     * that any non-transparent parts of the Drawable are removed from the
21624     * given transparent region.
21625     *
21626     * @param dr The Drawable whose transparency is to be applied to the region.
21627     * @param region A Region holding the current transparency information,
21628     * where any parts of the region that are set are considered to be
21629     * transparent.  On return, this region will be modified to have the
21630     * transparency information reduced by the corresponding parts of the
21631     * Drawable that are not transparent.
21632     * {@hide}
21633     */
21634    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
21635        if (DBG) {
21636            Log.i("View", "Getting transparent region for: " + this);
21637        }
21638        final Region r = dr.getTransparentRegion();
21639        final Rect db = dr.getBounds();
21640        final AttachInfo attachInfo = mAttachInfo;
21641        if (r != null && attachInfo != null) {
21642            final int w = getRight()-getLeft();
21643            final int h = getBottom()-getTop();
21644            if (db.left > 0) {
21645                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
21646                r.op(0, 0, db.left, h, Region.Op.UNION);
21647            }
21648            if (db.right < w) {
21649                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
21650                r.op(db.right, 0, w, h, Region.Op.UNION);
21651            }
21652            if (db.top > 0) {
21653                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
21654                r.op(0, 0, w, db.top, Region.Op.UNION);
21655            }
21656            if (db.bottom < h) {
21657                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
21658                r.op(0, db.bottom, w, h, Region.Op.UNION);
21659            }
21660            final int[] location = attachInfo.mTransparentLocation;
21661            getLocationInWindow(location);
21662            r.translate(location[0], location[1]);
21663            region.op(r, Region.Op.INTERSECT);
21664        } else {
21665            region.op(db, Region.Op.DIFFERENCE);
21666        }
21667    }
21668
21669    private void checkForLongClick(int delayOffset, float x, float y) {
21670        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
21671            mHasPerformedLongPress = false;
21672
21673            if (mPendingCheckForLongPress == null) {
21674                mPendingCheckForLongPress = new CheckForLongPress();
21675            }
21676            mPendingCheckForLongPress.setAnchor(x, y);
21677            mPendingCheckForLongPress.rememberWindowAttachCount();
21678            mPendingCheckForLongPress.rememberPressedState();
21679            postDelayed(mPendingCheckForLongPress,
21680                    ViewConfiguration.getLongPressTimeout() - delayOffset);
21681        }
21682    }
21683
21684    /**
21685     * Inflate a view from an XML resource.  This convenience method wraps the {@link
21686     * LayoutInflater} class, which provides a full range of options for view inflation.
21687     *
21688     * @param context The Context object for your activity or application.
21689     * @param resource The resource ID to inflate
21690     * @param root A view group that will be the parent.  Used to properly inflate the
21691     * layout_* parameters.
21692     * @see LayoutInflater
21693     */
21694    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
21695        LayoutInflater factory = LayoutInflater.from(context);
21696        return factory.inflate(resource, root);
21697    }
21698
21699    /**
21700     * Scroll the view with standard behavior for scrolling beyond the normal
21701     * content boundaries. Views that call this method should override
21702     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
21703     * results of an over-scroll operation.
21704     *
21705     * Views can use this method to handle any touch or fling-based scrolling.
21706     *
21707     * @param deltaX Change in X in pixels
21708     * @param deltaY Change in Y in pixels
21709     * @param scrollX Current X scroll value in pixels before applying deltaX
21710     * @param scrollY Current Y scroll value in pixels before applying deltaY
21711     * @param scrollRangeX Maximum content scroll range along the X axis
21712     * @param scrollRangeY Maximum content scroll range along the Y axis
21713     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21714     *          along the X axis.
21715     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21716     *          along the Y axis.
21717     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21718     * @return true if scrolling was clamped to an over-scroll boundary along either
21719     *          axis, false otherwise.
21720     */
21721    @SuppressWarnings({"UnusedParameters"})
21722    protected boolean overScrollBy(int deltaX, int deltaY,
21723            int scrollX, int scrollY,
21724            int scrollRangeX, int scrollRangeY,
21725            int maxOverScrollX, int maxOverScrollY,
21726            boolean isTouchEvent) {
21727        final int overScrollMode = mOverScrollMode;
21728        final boolean canScrollHorizontal =
21729                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21730        final boolean canScrollVertical =
21731                computeVerticalScrollRange() > computeVerticalScrollExtent();
21732        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21733                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21734        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21735                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21736
21737        int newScrollX = scrollX + deltaX;
21738        if (!overScrollHorizontal) {
21739            maxOverScrollX = 0;
21740        }
21741
21742        int newScrollY = scrollY + deltaY;
21743        if (!overScrollVertical) {
21744            maxOverScrollY = 0;
21745        }
21746
21747        // Clamp values if at the limits and record
21748        final int left = -maxOverScrollX;
21749        final int right = maxOverScrollX + scrollRangeX;
21750        final int top = -maxOverScrollY;
21751        final int bottom = maxOverScrollY + scrollRangeY;
21752
21753        boolean clampedX = false;
21754        if (newScrollX > right) {
21755            newScrollX = right;
21756            clampedX = true;
21757        } else if (newScrollX < left) {
21758            newScrollX = left;
21759            clampedX = true;
21760        }
21761
21762        boolean clampedY = false;
21763        if (newScrollY > bottom) {
21764            newScrollY = bottom;
21765            clampedY = true;
21766        } else if (newScrollY < top) {
21767            newScrollY = top;
21768            clampedY = true;
21769        }
21770
21771        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
21772
21773        return clampedX || clampedY;
21774    }
21775
21776    /**
21777     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
21778     * respond to the results of an over-scroll operation.
21779     *
21780     * @param scrollX New X scroll value in pixels
21781     * @param scrollY New Y scroll value in pixels
21782     * @param clampedX True if scrollX was clamped to an over-scroll boundary
21783     * @param clampedY True if scrollY was clamped to an over-scroll boundary
21784     */
21785    protected void onOverScrolled(int scrollX, int scrollY,
21786            boolean clampedX, boolean clampedY) {
21787        // Intentionally empty.
21788    }
21789
21790    /**
21791     * Returns the over-scroll mode for this view. The result will be
21792     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21793     * (allow over-scrolling only if the view content is larger than the container),
21794     * or {@link #OVER_SCROLL_NEVER}.
21795     *
21796     * @return This view's over-scroll mode.
21797     */
21798    public int getOverScrollMode() {
21799        return mOverScrollMode;
21800    }
21801
21802    /**
21803     * Set the over-scroll mode for this view. Valid over-scroll modes are
21804     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21805     * (allow over-scrolling only if the view content is larger than the container),
21806     * or {@link #OVER_SCROLL_NEVER}.
21807     *
21808     * Setting the over-scroll mode of a view will have an effect only if the
21809     * view is capable of scrolling.
21810     *
21811     * @param overScrollMode The new over-scroll mode for this view.
21812     */
21813    public void setOverScrollMode(int overScrollMode) {
21814        if (overScrollMode != OVER_SCROLL_ALWAYS &&
21815                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
21816                overScrollMode != OVER_SCROLL_NEVER) {
21817            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
21818        }
21819        mOverScrollMode = overScrollMode;
21820    }
21821
21822    /**
21823     * Enable or disable nested scrolling for this view.
21824     *
21825     * <p>If this property is set to true the view will be permitted to initiate nested
21826     * scrolling operations with a compatible parent view in the current hierarchy. If this
21827     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
21828     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
21829     * the nested scroll.</p>
21830     *
21831     * @param enabled true to enable nested scrolling, false to disable
21832     *
21833     * @see #isNestedScrollingEnabled()
21834     */
21835    public void setNestedScrollingEnabled(boolean enabled) {
21836        if (enabled) {
21837            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
21838        } else {
21839            stopNestedScroll();
21840            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
21841        }
21842    }
21843
21844    /**
21845     * Returns true if nested scrolling is enabled for this view.
21846     *
21847     * <p>If nested scrolling is enabled and this View class implementation supports it,
21848     * this view will act as a nested scrolling child view when applicable, forwarding data
21849     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21850     * parent.</p>
21851     *
21852     * @return true if nested scrolling is enabled
21853     *
21854     * @see #setNestedScrollingEnabled(boolean)
21855     */
21856    public boolean isNestedScrollingEnabled() {
21857        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21858                PFLAG3_NESTED_SCROLLING_ENABLED;
21859    }
21860
21861    /**
21862     * Begin a nestable scroll operation along the given axes.
21863     *
21864     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21865     *
21866     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21867     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21868     * In the case of touch scrolling the nested scroll will be terminated automatically in
21869     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21870     * In the event of programmatic scrolling the caller must explicitly call
21871     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21872     *
21873     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21874     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21875     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21876     *
21877     * <p>At each incremental step of the scroll the caller should invoke
21878     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21879     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21880     * parent at least partially consumed the scroll and the caller should adjust the amount it
21881     * scrolls by.</p>
21882     *
21883     * <p>After applying the remainder of the scroll delta the caller should invoke
21884     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21885     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21886     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21887     * </p>
21888     *
21889     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21890     *             {@link #SCROLL_AXIS_VERTICAL}.
21891     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21892     *         the current gesture.
21893     *
21894     * @see #stopNestedScroll()
21895     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21896     * @see #dispatchNestedScroll(int, int, int, int, int[])
21897     */
21898    public boolean startNestedScroll(int axes) {
21899        if (hasNestedScrollingParent()) {
21900            // Already in progress
21901            return true;
21902        }
21903        if (isNestedScrollingEnabled()) {
21904            ViewParent p = getParent();
21905            View child = this;
21906            while (p != null) {
21907                try {
21908                    if (p.onStartNestedScroll(child, this, axes)) {
21909                        mNestedScrollingParent = p;
21910                        p.onNestedScrollAccepted(child, this, axes);
21911                        return true;
21912                    }
21913                } catch (AbstractMethodError e) {
21914                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21915                            "method onStartNestedScroll", e);
21916                    // Allow the search upward to continue
21917                }
21918                if (p instanceof View) {
21919                    child = (View) p;
21920                }
21921                p = p.getParent();
21922            }
21923        }
21924        return false;
21925    }
21926
21927    /**
21928     * Stop a nested scroll in progress.
21929     *
21930     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21931     *
21932     * @see #startNestedScroll(int)
21933     */
21934    public void stopNestedScroll() {
21935        if (mNestedScrollingParent != null) {
21936            mNestedScrollingParent.onStopNestedScroll(this);
21937            mNestedScrollingParent = null;
21938        }
21939    }
21940
21941    /**
21942     * Returns true if this view has a nested scrolling parent.
21943     *
21944     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21945     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21946     *
21947     * @return whether this view has a nested scrolling parent
21948     */
21949    public boolean hasNestedScrollingParent() {
21950        return mNestedScrollingParent != null;
21951    }
21952
21953    /**
21954     * Dispatch one step of a nested scroll in progress.
21955     *
21956     * <p>Implementations of views that support nested scrolling should call this to report
21957     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21958     * is not currently in progress or nested scrolling is not
21959     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21960     *
21961     * <p>Compatible View implementations should also call
21962     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21963     * consuming a component of the scroll event themselves.</p>
21964     *
21965     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21966     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21967     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21968     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21969     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21970     *                       in local view coordinates of this view from before this operation
21971     *                       to after it completes. View implementations may use this to adjust
21972     *                       expected input coordinate tracking.
21973     * @return true if the event was dispatched, false if it could not be dispatched.
21974     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21975     */
21976    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21977            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21978        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21979            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21980                int startX = 0;
21981                int startY = 0;
21982                if (offsetInWindow != null) {
21983                    getLocationInWindow(offsetInWindow);
21984                    startX = offsetInWindow[0];
21985                    startY = offsetInWindow[1];
21986                }
21987
21988                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21989                        dxUnconsumed, dyUnconsumed);
21990
21991                if (offsetInWindow != null) {
21992                    getLocationInWindow(offsetInWindow);
21993                    offsetInWindow[0] -= startX;
21994                    offsetInWindow[1] -= startY;
21995                }
21996                return true;
21997            } else if (offsetInWindow != null) {
21998                // No motion, no dispatch. Keep offsetInWindow up to date.
21999                offsetInWindow[0] = 0;
22000                offsetInWindow[1] = 0;
22001            }
22002        }
22003        return false;
22004    }
22005
22006    /**
22007     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
22008     *
22009     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
22010     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
22011     * scrolling operation to consume some or all of the scroll operation before the child view
22012     * consumes it.</p>
22013     *
22014     * @param dx Horizontal scroll distance in pixels
22015     * @param dy Vertical scroll distance in pixels
22016     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
22017     *                 and consumed[1] the consumed dy.
22018     * @param offsetInWindow Optional. If not null, on return this will contain the offset
22019     *                       in local view coordinates of this view from before this operation
22020     *                       to after it completes. View implementations may use this to adjust
22021     *                       expected input coordinate tracking.
22022     * @return true if the parent consumed some or all of the scroll delta
22023     * @see #dispatchNestedScroll(int, int, int, int, int[])
22024     */
22025    public boolean dispatchNestedPreScroll(int dx, int dy,
22026            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
22027        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22028            if (dx != 0 || dy != 0) {
22029                int startX = 0;
22030                int startY = 0;
22031                if (offsetInWindow != null) {
22032                    getLocationInWindow(offsetInWindow);
22033                    startX = offsetInWindow[0];
22034                    startY = offsetInWindow[1];
22035                }
22036
22037                if (consumed == null) {
22038                    if (mTempNestedScrollConsumed == null) {
22039                        mTempNestedScrollConsumed = new int[2];
22040                    }
22041                    consumed = mTempNestedScrollConsumed;
22042                }
22043                consumed[0] = 0;
22044                consumed[1] = 0;
22045                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
22046
22047                if (offsetInWindow != null) {
22048                    getLocationInWindow(offsetInWindow);
22049                    offsetInWindow[0] -= startX;
22050                    offsetInWindow[1] -= startY;
22051                }
22052                return consumed[0] != 0 || consumed[1] != 0;
22053            } else if (offsetInWindow != null) {
22054                offsetInWindow[0] = 0;
22055                offsetInWindow[1] = 0;
22056            }
22057        }
22058        return false;
22059    }
22060
22061    /**
22062     * Dispatch a fling to a nested scrolling parent.
22063     *
22064     * <p>This method should be used to indicate that a nested scrolling child has detected
22065     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
22066     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
22067     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
22068     * along a scrollable axis.</p>
22069     *
22070     * <p>If a nested scrolling child view would normally fling but it is at the edge of
22071     * its own content, it can use this method to delegate the fling to its nested scrolling
22072     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
22073     *
22074     * @param velocityX Horizontal fling velocity in pixels per second
22075     * @param velocityY Vertical fling velocity in pixels per second
22076     * @param consumed true if the child consumed the fling, false otherwise
22077     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
22078     */
22079    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
22080        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22081            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
22082        }
22083        return false;
22084    }
22085
22086    /**
22087     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
22088     *
22089     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
22090     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
22091     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
22092     * before the child view consumes it. If this method returns <code>true</code>, a nested
22093     * parent view consumed the fling and this view should not scroll as a result.</p>
22094     *
22095     * <p>For a better user experience, only one view in a nested scrolling chain should consume
22096     * the fling at a time. If a parent view consumed the fling this method will return false.
22097     * Custom view implementations should account for this in two ways:</p>
22098     *
22099     * <ul>
22100     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
22101     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
22102     *     position regardless.</li>
22103     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
22104     *     even to settle back to a valid idle position.</li>
22105     * </ul>
22106     *
22107     * <p>Views should also not offer fling velocities to nested parent views along an axis
22108     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
22109     * should not offer a horizontal fling velocity to its parents since scrolling along that
22110     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
22111     *
22112     * @param velocityX Horizontal fling velocity in pixels per second
22113     * @param velocityY Vertical fling velocity in pixels per second
22114     * @return true if a nested scrolling parent consumed the fling
22115     */
22116    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
22117        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22118            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
22119        }
22120        return false;
22121    }
22122
22123    /**
22124     * Gets a scale factor that determines the distance the view should scroll
22125     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
22126     * @return The vertical scroll scale factor.
22127     * @hide
22128     */
22129    protected float getVerticalScrollFactor() {
22130        if (mVerticalScrollFactor == 0) {
22131            TypedValue outValue = new TypedValue();
22132            if (!mContext.getTheme().resolveAttribute(
22133                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
22134                throw new IllegalStateException(
22135                        "Expected theme to define listPreferredItemHeight.");
22136            }
22137            mVerticalScrollFactor = outValue.getDimension(
22138                    mContext.getResources().getDisplayMetrics());
22139        }
22140        return mVerticalScrollFactor;
22141    }
22142
22143    /**
22144     * Gets a scale factor that determines the distance the view should scroll
22145     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
22146     * @return The horizontal scroll scale factor.
22147     * @hide
22148     */
22149    protected float getHorizontalScrollFactor() {
22150        // TODO: Should use something else.
22151        return getVerticalScrollFactor();
22152    }
22153
22154    /**
22155     * Return the value specifying the text direction or policy that was set with
22156     * {@link #setTextDirection(int)}.
22157     *
22158     * @return the defined text direction. It can be one of:
22159     *
22160     * {@link #TEXT_DIRECTION_INHERIT},
22161     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22162     * {@link #TEXT_DIRECTION_ANY_RTL},
22163     * {@link #TEXT_DIRECTION_LTR},
22164     * {@link #TEXT_DIRECTION_RTL},
22165     * {@link #TEXT_DIRECTION_LOCALE},
22166     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22167     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22168     *
22169     * @attr ref android.R.styleable#View_textDirection
22170     *
22171     * @hide
22172     */
22173    @ViewDebug.ExportedProperty(category = "text", mapping = {
22174            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22175            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22176            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22177            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22178            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22179            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22180            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22181            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22182    })
22183    public int getRawTextDirection() {
22184        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
22185    }
22186
22187    /**
22188     * Set the text direction.
22189     *
22190     * @param textDirection the direction to set. Should be one of:
22191     *
22192     * {@link #TEXT_DIRECTION_INHERIT},
22193     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22194     * {@link #TEXT_DIRECTION_ANY_RTL},
22195     * {@link #TEXT_DIRECTION_LTR},
22196     * {@link #TEXT_DIRECTION_RTL},
22197     * {@link #TEXT_DIRECTION_LOCALE}
22198     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22199     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
22200     *
22201     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
22202     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
22203     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
22204     *
22205     * @attr ref android.R.styleable#View_textDirection
22206     */
22207    public void setTextDirection(int textDirection) {
22208        if (getRawTextDirection() != textDirection) {
22209            // Reset the current text direction and the resolved one
22210            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
22211            resetResolvedTextDirection();
22212            // Set the new text direction
22213            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
22214            // Do resolution
22215            resolveTextDirection();
22216            // Notify change
22217            onRtlPropertiesChanged(getLayoutDirection());
22218            // Refresh
22219            requestLayout();
22220            invalidate(true);
22221        }
22222    }
22223
22224    /**
22225     * Return the resolved text direction.
22226     *
22227     * @return the resolved text direction. Returns one of:
22228     *
22229     * {@link #TEXT_DIRECTION_FIRST_STRONG},
22230     * {@link #TEXT_DIRECTION_ANY_RTL},
22231     * {@link #TEXT_DIRECTION_LTR},
22232     * {@link #TEXT_DIRECTION_RTL},
22233     * {@link #TEXT_DIRECTION_LOCALE},
22234     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
22235     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
22236     *
22237     * @attr ref android.R.styleable#View_textDirection
22238     */
22239    @ViewDebug.ExportedProperty(category = "text", mapping = {
22240            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
22241            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
22242            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
22243            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
22244            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
22245            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
22246            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
22247            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
22248    })
22249    public int getTextDirection() {
22250        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
22251    }
22252
22253    /**
22254     * Resolve the text direction.
22255     *
22256     * @return true if resolution has been done, false otherwise.
22257     *
22258     * @hide
22259     */
22260    public boolean resolveTextDirection() {
22261        // Reset any previous text direction resolution
22262        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22263
22264        if (hasRtlSupport()) {
22265            // Set resolved text direction flag depending on text direction flag
22266            final int textDirection = getRawTextDirection();
22267            switch(textDirection) {
22268                case TEXT_DIRECTION_INHERIT:
22269                    if (!canResolveTextDirection()) {
22270                        // We cannot do the resolution if there is no parent, so use the default one
22271                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22272                        // Resolution will need to happen again later
22273                        return false;
22274                    }
22275
22276                    // Parent has not yet resolved, so we still return the default
22277                    try {
22278                        if (!mParent.isTextDirectionResolved()) {
22279                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22280                            // Resolution will need to happen again later
22281                            return false;
22282                        }
22283                    } catch (AbstractMethodError e) {
22284                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22285                                " does not fully implement ViewParent", e);
22286                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
22287                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22288                        return true;
22289                    }
22290
22291                    // Set current resolved direction to the same value as the parent's one
22292                    int parentResolvedDirection;
22293                    try {
22294                        parentResolvedDirection = mParent.getTextDirection();
22295                    } catch (AbstractMethodError e) {
22296                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22297                                " does not fully implement ViewParent", e);
22298                        parentResolvedDirection = TEXT_DIRECTION_LTR;
22299                    }
22300                    switch (parentResolvedDirection) {
22301                        case TEXT_DIRECTION_FIRST_STRONG:
22302                        case TEXT_DIRECTION_ANY_RTL:
22303                        case TEXT_DIRECTION_LTR:
22304                        case TEXT_DIRECTION_RTL:
22305                        case TEXT_DIRECTION_LOCALE:
22306                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
22307                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
22308                            mPrivateFlags2 |=
22309                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22310                            break;
22311                        default:
22312                            // Default resolved direction is "first strong" heuristic
22313                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22314                    }
22315                    break;
22316                case TEXT_DIRECTION_FIRST_STRONG:
22317                case TEXT_DIRECTION_ANY_RTL:
22318                case TEXT_DIRECTION_LTR:
22319                case TEXT_DIRECTION_RTL:
22320                case TEXT_DIRECTION_LOCALE:
22321                case TEXT_DIRECTION_FIRST_STRONG_LTR:
22322                case TEXT_DIRECTION_FIRST_STRONG_RTL:
22323                    // Resolved direction is the same as text direction
22324                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
22325                    break;
22326                default:
22327                    // Default resolved direction is "first strong" heuristic
22328                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22329            }
22330        } else {
22331            // Default resolved direction is "first strong" heuristic
22332            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22333        }
22334
22335        // Set to resolved
22336        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
22337        return true;
22338    }
22339
22340    /**
22341     * Check if text direction resolution can be done.
22342     *
22343     * @return true if text direction resolution can be done otherwise return false.
22344     */
22345    public boolean canResolveTextDirection() {
22346        switch (getRawTextDirection()) {
22347            case TEXT_DIRECTION_INHERIT:
22348                if (mParent != null) {
22349                    try {
22350                        return mParent.canResolveTextDirection();
22351                    } catch (AbstractMethodError e) {
22352                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22353                                " does not fully implement ViewParent", e);
22354                    }
22355                }
22356                return false;
22357
22358            default:
22359                return true;
22360        }
22361    }
22362
22363    /**
22364     * Reset resolved text direction. Text direction will be resolved during a call to
22365     * {@link #onMeasure(int, int)}.
22366     *
22367     * @hide
22368     */
22369    public void resetResolvedTextDirection() {
22370        // Reset any previous text direction resolution
22371        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
22372        // Set to default value
22373        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
22374    }
22375
22376    /**
22377     * @return true if text direction is inherited.
22378     *
22379     * @hide
22380     */
22381    public boolean isTextDirectionInherited() {
22382        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
22383    }
22384
22385    /**
22386     * @return true if text direction is resolved.
22387     */
22388    public boolean isTextDirectionResolved() {
22389        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
22390    }
22391
22392    /**
22393     * Return the value specifying the text alignment or policy that was set with
22394     * {@link #setTextAlignment(int)}.
22395     *
22396     * @return the defined text alignment. It can be one of:
22397     *
22398     * {@link #TEXT_ALIGNMENT_INHERIT},
22399     * {@link #TEXT_ALIGNMENT_GRAVITY},
22400     * {@link #TEXT_ALIGNMENT_CENTER},
22401     * {@link #TEXT_ALIGNMENT_TEXT_START},
22402     * {@link #TEXT_ALIGNMENT_TEXT_END},
22403     * {@link #TEXT_ALIGNMENT_VIEW_START},
22404     * {@link #TEXT_ALIGNMENT_VIEW_END}
22405     *
22406     * @attr ref android.R.styleable#View_textAlignment
22407     *
22408     * @hide
22409     */
22410    @ViewDebug.ExportedProperty(category = "text", mapping = {
22411            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22412            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22413            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22414            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22415            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22416            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22417            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22418    })
22419    @TextAlignment
22420    public int getRawTextAlignment() {
22421        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
22422    }
22423
22424    /**
22425     * Set the text alignment.
22426     *
22427     * @param textAlignment The text alignment to set. Should be one of
22428     *
22429     * {@link #TEXT_ALIGNMENT_INHERIT},
22430     * {@link #TEXT_ALIGNMENT_GRAVITY},
22431     * {@link #TEXT_ALIGNMENT_CENTER},
22432     * {@link #TEXT_ALIGNMENT_TEXT_START},
22433     * {@link #TEXT_ALIGNMENT_TEXT_END},
22434     * {@link #TEXT_ALIGNMENT_VIEW_START},
22435     * {@link #TEXT_ALIGNMENT_VIEW_END}
22436     *
22437     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
22438     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
22439     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
22440     *
22441     * @attr ref android.R.styleable#View_textAlignment
22442     */
22443    public void setTextAlignment(@TextAlignment int textAlignment) {
22444        if (textAlignment != getRawTextAlignment()) {
22445            // Reset the current and resolved text alignment
22446            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
22447            resetResolvedTextAlignment();
22448            // Set the new text alignment
22449            mPrivateFlags2 |=
22450                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
22451            // Do resolution
22452            resolveTextAlignment();
22453            // Notify change
22454            onRtlPropertiesChanged(getLayoutDirection());
22455            // Refresh
22456            requestLayout();
22457            invalidate(true);
22458        }
22459    }
22460
22461    /**
22462     * Return the resolved text alignment.
22463     *
22464     * @return the resolved text alignment. Returns one of:
22465     *
22466     * {@link #TEXT_ALIGNMENT_GRAVITY},
22467     * {@link #TEXT_ALIGNMENT_CENTER},
22468     * {@link #TEXT_ALIGNMENT_TEXT_START},
22469     * {@link #TEXT_ALIGNMENT_TEXT_END},
22470     * {@link #TEXT_ALIGNMENT_VIEW_START},
22471     * {@link #TEXT_ALIGNMENT_VIEW_END}
22472     *
22473     * @attr ref android.R.styleable#View_textAlignment
22474     */
22475    @ViewDebug.ExportedProperty(category = "text", mapping = {
22476            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
22477            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
22478            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
22479            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
22480            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
22481            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
22482            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
22483    })
22484    @TextAlignment
22485    public int getTextAlignment() {
22486        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
22487                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
22488    }
22489
22490    /**
22491     * Resolve the text alignment.
22492     *
22493     * @return true if resolution has been done, false otherwise.
22494     *
22495     * @hide
22496     */
22497    public boolean resolveTextAlignment() {
22498        // Reset any previous text alignment resolution
22499        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22500
22501        if (hasRtlSupport()) {
22502            // Set resolved text alignment flag depending on text alignment flag
22503            final int textAlignment = getRawTextAlignment();
22504            switch (textAlignment) {
22505                case TEXT_ALIGNMENT_INHERIT:
22506                    // Check if we can resolve the text alignment
22507                    if (!canResolveTextAlignment()) {
22508                        // We cannot do the resolution if there is no parent so use the default
22509                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22510                        // Resolution will need to happen again later
22511                        return false;
22512                    }
22513
22514                    // Parent has not yet resolved, so we still return the default
22515                    try {
22516                        if (!mParent.isTextAlignmentResolved()) {
22517                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22518                            // Resolution will need to happen again later
22519                            return false;
22520                        }
22521                    } catch (AbstractMethodError e) {
22522                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22523                                " does not fully implement ViewParent", e);
22524                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
22525                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22526                        return true;
22527                    }
22528
22529                    int parentResolvedTextAlignment;
22530                    try {
22531                        parentResolvedTextAlignment = mParent.getTextAlignment();
22532                    } catch (AbstractMethodError e) {
22533                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22534                                " does not fully implement ViewParent", e);
22535                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
22536                    }
22537                    switch (parentResolvedTextAlignment) {
22538                        case TEXT_ALIGNMENT_GRAVITY:
22539                        case TEXT_ALIGNMENT_TEXT_START:
22540                        case TEXT_ALIGNMENT_TEXT_END:
22541                        case TEXT_ALIGNMENT_CENTER:
22542                        case TEXT_ALIGNMENT_VIEW_START:
22543                        case TEXT_ALIGNMENT_VIEW_END:
22544                            // Resolved text alignment is the same as the parent resolved
22545                            // text alignment
22546                            mPrivateFlags2 |=
22547                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22548                            break;
22549                        default:
22550                            // Use default resolved text alignment
22551                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22552                    }
22553                    break;
22554                case TEXT_ALIGNMENT_GRAVITY:
22555                case TEXT_ALIGNMENT_TEXT_START:
22556                case TEXT_ALIGNMENT_TEXT_END:
22557                case TEXT_ALIGNMENT_CENTER:
22558                case TEXT_ALIGNMENT_VIEW_START:
22559                case TEXT_ALIGNMENT_VIEW_END:
22560                    // Resolved text alignment is the same as text alignment
22561                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
22562                    break;
22563                default:
22564                    // Use default resolved text alignment
22565                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22566            }
22567        } else {
22568            // Use default resolved text alignment
22569            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22570        }
22571
22572        // Set the resolved
22573        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22574        return true;
22575    }
22576
22577    /**
22578     * Check if text alignment resolution can be done.
22579     *
22580     * @return true if text alignment resolution can be done otherwise return false.
22581     */
22582    public boolean canResolveTextAlignment() {
22583        switch (getRawTextAlignment()) {
22584            case TEXT_DIRECTION_INHERIT:
22585                if (mParent != null) {
22586                    try {
22587                        return mParent.canResolveTextAlignment();
22588                    } catch (AbstractMethodError e) {
22589                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
22590                                " does not fully implement ViewParent", e);
22591                    }
22592                }
22593                return false;
22594
22595            default:
22596                return true;
22597        }
22598    }
22599
22600    /**
22601     * Reset resolved text alignment. Text alignment will be resolved during a call to
22602     * {@link #onMeasure(int, int)}.
22603     *
22604     * @hide
22605     */
22606    public void resetResolvedTextAlignment() {
22607        // Reset any previous text alignment resolution
22608        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
22609        // Set to default
22610        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
22611    }
22612
22613    /**
22614     * @return true if text alignment is inherited.
22615     *
22616     * @hide
22617     */
22618    public boolean isTextAlignmentInherited() {
22619        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
22620    }
22621
22622    /**
22623     * @return true if text alignment is resolved.
22624     */
22625    public boolean isTextAlignmentResolved() {
22626        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
22627    }
22628
22629    /**
22630     * Generate a value suitable for use in {@link #setId(int)}.
22631     * This value will not collide with ID values generated at build time by aapt for R.id.
22632     *
22633     * @return a generated ID value
22634     */
22635    public static int generateViewId() {
22636        for (;;) {
22637            final int result = sNextGeneratedId.get();
22638            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
22639            int newValue = result + 1;
22640            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
22641            if (sNextGeneratedId.compareAndSet(result, newValue)) {
22642                return result;
22643            }
22644        }
22645    }
22646
22647    /**
22648     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
22649     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
22650     *                           a normal View or a ViewGroup with
22651     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
22652     * @hide
22653     */
22654    public void captureTransitioningViews(List<View> transitioningViews) {
22655        if (getVisibility() == View.VISIBLE) {
22656            transitioningViews.add(this);
22657        }
22658    }
22659
22660    /**
22661     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
22662     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
22663     * @hide
22664     */
22665    public void findNamedViews(Map<String, View> namedElements) {
22666        if (getVisibility() == VISIBLE || mGhostView != null) {
22667            String transitionName = getTransitionName();
22668            if (transitionName != null) {
22669                namedElements.put(transitionName, this);
22670            }
22671        }
22672    }
22673
22674    /**
22675     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
22676     * The default implementation does not care the location or event types, but some subclasses
22677     * may use it (such as WebViews).
22678     * @param event The MotionEvent from a mouse
22679     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
22680     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
22681     * @see PointerIcon
22682     */
22683    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
22684        final float x = event.getX(pointerIndex);
22685        final float y = event.getY(pointerIndex);
22686        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
22687            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
22688        }
22689        return mPointerIcon;
22690    }
22691
22692    /**
22693     * Set the pointer icon for the current view.
22694     * Passing {@code null} will restore the pointer icon to its default value.
22695     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
22696     */
22697    public void setPointerIcon(PointerIcon pointerIcon) {
22698        mPointerIcon = pointerIcon;
22699        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
22700            return;
22701        }
22702        try {
22703            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
22704        } catch (RemoteException e) {
22705        }
22706    }
22707
22708    /**
22709     * Gets the pointer icon for the current view.
22710     */
22711    public PointerIcon getPointerIcon() {
22712        return mPointerIcon;
22713    }
22714
22715    //
22716    // Properties
22717    //
22718    /**
22719     * A Property wrapper around the <code>alpha</code> functionality handled by the
22720     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
22721     */
22722    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
22723        @Override
22724        public void setValue(View object, float value) {
22725            object.setAlpha(value);
22726        }
22727
22728        @Override
22729        public Float get(View object) {
22730            return object.getAlpha();
22731        }
22732    };
22733
22734    /**
22735     * A Property wrapper around the <code>translationX</code> functionality handled by the
22736     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
22737     */
22738    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
22739        @Override
22740        public void setValue(View object, float value) {
22741            object.setTranslationX(value);
22742        }
22743
22744                @Override
22745        public Float get(View object) {
22746            return object.getTranslationX();
22747        }
22748    };
22749
22750    /**
22751     * A Property wrapper around the <code>translationY</code> functionality handled by the
22752     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
22753     */
22754    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
22755        @Override
22756        public void setValue(View object, float value) {
22757            object.setTranslationY(value);
22758        }
22759
22760        @Override
22761        public Float get(View object) {
22762            return object.getTranslationY();
22763        }
22764    };
22765
22766    /**
22767     * A Property wrapper around the <code>translationZ</code> functionality handled by the
22768     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
22769     */
22770    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
22771        @Override
22772        public void setValue(View object, float value) {
22773            object.setTranslationZ(value);
22774        }
22775
22776        @Override
22777        public Float get(View object) {
22778            return object.getTranslationZ();
22779        }
22780    };
22781
22782    /**
22783     * A Property wrapper around the <code>x</code> functionality handled by the
22784     * {@link View#setX(float)} and {@link View#getX()} methods.
22785     */
22786    public static final Property<View, Float> X = new FloatProperty<View>("x") {
22787        @Override
22788        public void setValue(View object, float value) {
22789            object.setX(value);
22790        }
22791
22792        @Override
22793        public Float get(View object) {
22794            return object.getX();
22795        }
22796    };
22797
22798    /**
22799     * A Property wrapper around the <code>y</code> functionality handled by the
22800     * {@link View#setY(float)} and {@link View#getY()} methods.
22801     */
22802    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
22803        @Override
22804        public void setValue(View object, float value) {
22805            object.setY(value);
22806        }
22807
22808        @Override
22809        public Float get(View object) {
22810            return object.getY();
22811        }
22812    };
22813
22814    /**
22815     * A Property wrapper around the <code>z</code> functionality handled by the
22816     * {@link View#setZ(float)} and {@link View#getZ()} methods.
22817     */
22818    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
22819        @Override
22820        public void setValue(View object, float value) {
22821            object.setZ(value);
22822        }
22823
22824        @Override
22825        public Float get(View object) {
22826            return object.getZ();
22827        }
22828    };
22829
22830    /**
22831     * A Property wrapper around the <code>rotation</code> functionality handled by the
22832     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
22833     */
22834    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
22835        @Override
22836        public void setValue(View object, float value) {
22837            object.setRotation(value);
22838        }
22839
22840        @Override
22841        public Float get(View object) {
22842            return object.getRotation();
22843        }
22844    };
22845
22846    /**
22847     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22848     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22849     */
22850    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22851        @Override
22852        public void setValue(View object, float value) {
22853            object.setRotationX(value);
22854        }
22855
22856        @Override
22857        public Float get(View object) {
22858            return object.getRotationX();
22859        }
22860    };
22861
22862    /**
22863     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22864     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22865     */
22866    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22867        @Override
22868        public void setValue(View object, float value) {
22869            object.setRotationY(value);
22870        }
22871
22872        @Override
22873        public Float get(View object) {
22874            return object.getRotationY();
22875        }
22876    };
22877
22878    /**
22879     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22880     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22881     */
22882    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22883        @Override
22884        public void setValue(View object, float value) {
22885            object.setScaleX(value);
22886        }
22887
22888        @Override
22889        public Float get(View object) {
22890            return object.getScaleX();
22891        }
22892    };
22893
22894    /**
22895     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22896     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22897     */
22898    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22899        @Override
22900        public void setValue(View object, float value) {
22901            object.setScaleY(value);
22902        }
22903
22904        @Override
22905        public Float get(View object) {
22906            return object.getScaleY();
22907        }
22908    };
22909
22910    /**
22911     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22912     * Each MeasureSpec represents a requirement for either the width or the height.
22913     * A MeasureSpec is comprised of a size and a mode. There are three possible
22914     * modes:
22915     * <dl>
22916     * <dt>UNSPECIFIED</dt>
22917     * <dd>
22918     * The parent has not imposed any constraint on the child. It can be whatever size
22919     * it wants.
22920     * </dd>
22921     *
22922     * <dt>EXACTLY</dt>
22923     * <dd>
22924     * The parent has determined an exact size for the child. The child is going to be
22925     * given those bounds regardless of how big it wants to be.
22926     * </dd>
22927     *
22928     * <dt>AT_MOST</dt>
22929     * <dd>
22930     * The child can be as large as it wants up to the specified size.
22931     * </dd>
22932     * </dl>
22933     *
22934     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22935     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22936     */
22937    public static class MeasureSpec {
22938        private static final int MODE_SHIFT = 30;
22939        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22940
22941        /** @hide */
22942        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22943        @Retention(RetentionPolicy.SOURCE)
22944        public @interface MeasureSpecMode {}
22945
22946        /**
22947         * Measure specification mode: The parent has not imposed any constraint
22948         * on the child. It can be whatever size it wants.
22949         */
22950        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22951
22952        /**
22953         * Measure specification mode: The parent has determined an exact size
22954         * for the child. The child is going to be given those bounds regardless
22955         * of how big it wants to be.
22956         */
22957        public static final int EXACTLY     = 1 << MODE_SHIFT;
22958
22959        /**
22960         * Measure specification mode: The child can be as large as it wants up
22961         * to the specified size.
22962         */
22963        public static final int AT_MOST     = 2 << MODE_SHIFT;
22964
22965        /**
22966         * Creates a measure specification based on the supplied size and mode.
22967         *
22968         * The mode must always be one of the following:
22969         * <ul>
22970         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22971         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22972         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22973         * </ul>
22974         *
22975         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22976         * implementation was such that the order of arguments did not matter
22977         * and overflow in either value could impact the resulting MeasureSpec.
22978         * {@link android.widget.RelativeLayout} was affected by this bug.
22979         * Apps targeting API levels greater than 17 will get the fixed, more strict
22980         * behavior.</p>
22981         *
22982         * @param size the size of the measure specification
22983         * @param mode the mode of the measure specification
22984         * @return the measure specification based on size and mode
22985         */
22986        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22987                                          @MeasureSpecMode int mode) {
22988            if (sUseBrokenMakeMeasureSpec) {
22989                return size + mode;
22990            } else {
22991                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22992            }
22993        }
22994
22995        /**
22996         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22997         * will automatically get a size of 0. Older apps expect this.
22998         *
22999         * @hide internal use only for compatibility with system widgets and older apps
23000         */
23001        public static int makeSafeMeasureSpec(int size, int mode) {
23002            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
23003                return 0;
23004            }
23005            return makeMeasureSpec(size, mode);
23006        }
23007
23008        /**
23009         * Extracts the mode from the supplied measure specification.
23010         *
23011         * @param measureSpec the measure specification to extract the mode from
23012         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
23013         *         {@link android.view.View.MeasureSpec#AT_MOST} or
23014         *         {@link android.view.View.MeasureSpec#EXACTLY}
23015         */
23016        @MeasureSpecMode
23017        public static int getMode(int measureSpec) {
23018            //noinspection ResourceType
23019            return (measureSpec & MODE_MASK);
23020        }
23021
23022        /**
23023         * Extracts the size from the supplied measure specification.
23024         *
23025         * @param measureSpec the measure specification to extract the size from
23026         * @return the size in pixels defined in the supplied measure specification
23027         */
23028        public static int getSize(int measureSpec) {
23029            return (measureSpec & ~MODE_MASK);
23030        }
23031
23032        static int adjust(int measureSpec, int delta) {
23033            final int mode = getMode(measureSpec);
23034            int size = getSize(measureSpec);
23035            if (mode == UNSPECIFIED) {
23036                // No need to adjust size for UNSPECIFIED mode.
23037                return makeMeasureSpec(size, UNSPECIFIED);
23038            }
23039            size += delta;
23040            if (size < 0) {
23041                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
23042                        ") spec: " + toString(measureSpec) + " delta: " + delta);
23043                size = 0;
23044            }
23045            return makeMeasureSpec(size, mode);
23046        }
23047
23048        /**
23049         * Returns a String representation of the specified measure
23050         * specification.
23051         *
23052         * @param measureSpec the measure specification to convert to a String
23053         * @return a String with the following format: "MeasureSpec: MODE SIZE"
23054         */
23055        public static String toString(int measureSpec) {
23056            int mode = getMode(measureSpec);
23057            int size = getSize(measureSpec);
23058
23059            StringBuilder sb = new StringBuilder("MeasureSpec: ");
23060
23061            if (mode == UNSPECIFIED)
23062                sb.append("UNSPECIFIED ");
23063            else if (mode == EXACTLY)
23064                sb.append("EXACTLY ");
23065            else if (mode == AT_MOST)
23066                sb.append("AT_MOST ");
23067            else
23068                sb.append(mode).append(" ");
23069
23070            sb.append(size);
23071            return sb.toString();
23072        }
23073    }
23074
23075    private final class CheckForLongPress implements Runnable {
23076        private int mOriginalWindowAttachCount;
23077        private float mX;
23078        private float mY;
23079        private boolean mOriginalPressedState;
23080
23081        @Override
23082        public void run() {
23083            if ((mOriginalPressedState == isPressed()) && (mParent != null)
23084                    && mOriginalWindowAttachCount == mWindowAttachCount) {
23085                if (performLongClick(mX, mY)) {
23086                    mHasPerformedLongPress = true;
23087                }
23088            }
23089        }
23090
23091        public void setAnchor(float x, float y) {
23092            mX = x;
23093            mY = y;
23094        }
23095
23096        public void rememberWindowAttachCount() {
23097            mOriginalWindowAttachCount = mWindowAttachCount;
23098        }
23099
23100        public void rememberPressedState() {
23101            mOriginalPressedState = isPressed();
23102        }
23103    }
23104
23105    private final class CheckForTap implements Runnable {
23106        public float x;
23107        public float y;
23108
23109        @Override
23110        public void run() {
23111            mPrivateFlags &= ~PFLAG_PREPRESSED;
23112            setPressed(true, x, y);
23113            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
23114        }
23115    }
23116
23117    private final class PerformClick implements Runnable {
23118        @Override
23119        public void run() {
23120            performClick();
23121        }
23122    }
23123
23124    /**
23125     * This method returns a ViewPropertyAnimator object, which can be used to animate
23126     * specific properties on this View.
23127     *
23128     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
23129     */
23130    public ViewPropertyAnimator animate() {
23131        if (mAnimator == null) {
23132            mAnimator = new ViewPropertyAnimator(this);
23133        }
23134        return mAnimator;
23135    }
23136
23137    /**
23138     * Sets the name of the View to be used to identify Views in Transitions.
23139     * Names should be unique in the View hierarchy.
23140     *
23141     * @param transitionName The name of the View to uniquely identify it for Transitions.
23142     */
23143    public final void setTransitionName(String transitionName) {
23144        mTransitionName = transitionName;
23145    }
23146
23147    /**
23148     * Returns the name of the View to be used to identify Views in Transitions.
23149     * Names should be unique in the View hierarchy.
23150     *
23151     * <p>This returns null if the View has not been given a name.</p>
23152     *
23153     * @return The name used of the View to be used to identify Views in Transitions or null
23154     * if no name has been given.
23155     */
23156    @ViewDebug.ExportedProperty
23157    public String getTransitionName() {
23158        return mTransitionName;
23159    }
23160
23161    /**
23162     * @hide
23163     */
23164    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
23165        // Do nothing.
23166    }
23167
23168    /**
23169     * Interface definition for a callback to be invoked when a hardware key event is
23170     * dispatched to this view. The callback will be invoked before the key event is
23171     * given to the view. This is only useful for hardware keyboards; a software input
23172     * method has no obligation to trigger this listener.
23173     */
23174    public interface OnKeyListener {
23175        /**
23176         * Called when a hardware key is dispatched to a view. This allows listeners to
23177         * get a chance to respond before the target view.
23178         * <p>Key presses in software keyboards will generally NOT trigger this method,
23179         * although some may elect to do so in some situations. Do not assume a
23180         * software input method has to be key-based; even if it is, it may use key presses
23181         * in a different way than you expect, so there is no way to reliably catch soft
23182         * input key presses.
23183         *
23184         * @param v The view the key has been dispatched to.
23185         * @param keyCode The code for the physical key that was pressed
23186         * @param event The KeyEvent object containing full information about
23187         *        the event.
23188         * @return True if the listener has consumed the event, false otherwise.
23189         */
23190        boolean onKey(View v, int keyCode, KeyEvent event);
23191    }
23192
23193    /**
23194     * Interface definition for a callback to be invoked when a touch event is
23195     * dispatched to this view. The callback will be invoked before the touch
23196     * event is given to the view.
23197     */
23198    public interface OnTouchListener {
23199        /**
23200         * Called when a touch event is dispatched to a view. This allows listeners to
23201         * get a chance to respond before the target view.
23202         *
23203         * @param v The view the touch event has been dispatched to.
23204         * @param event The MotionEvent object containing full information about
23205         *        the event.
23206         * @return True if the listener has consumed the event, false otherwise.
23207         */
23208        boolean onTouch(View v, MotionEvent event);
23209    }
23210
23211    /**
23212     * Interface definition for a callback to be invoked when a hover event is
23213     * dispatched to this view. The callback will be invoked before the hover
23214     * event is given to the view.
23215     */
23216    public interface OnHoverListener {
23217        /**
23218         * Called when a hover event is dispatched to a view. This allows listeners to
23219         * get a chance to respond before the target view.
23220         *
23221         * @param v The view the hover event has been dispatched to.
23222         * @param event The MotionEvent object containing full information about
23223         *        the event.
23224         * @return True if the listener has consumed the event, false otherwise.
23225         */
23226        boolean onHover(View v, MotionEvent event);
23227    }
23228
23229    /**
23230     * Interface definition for a callback to be invoked when a generic motion event is
23231     * dispatched to this view. The callback will be invoked before the generic motion
23232     * event is given to the view.
23233     */
23234    public interface OnGenericMotionListener {
23235        /**
23236         * Called when a generic motion event is dispatched to a view. This allows listeners to
23237         * get a chance to respond before the target view.
23238         *
23239         * @param v The view the generic motion event has been dispatched to.
23240         * @param event The MotionEvent object containing full information about
23241         *        the event.
23242         * @return True if the listener has consumed the event, false otherwise.
23243         */
23244        boolean onGenericMotion(View v, MotionEvent event);
23245    }
23246
23247    /**
23248     * Interface definition for a callback to be invoked when a view has been clicked and held.
23249     */
23250    public interface OnLongClickListener {
23251        /**
23252         * Called when a view has been clicked and held.
23253         *
23254         * @param v The view that was clicked and held.
23255         *
23256         * @return true if the callback consumed the long click, false otherwise.
23257         */
23258        boolean onLongClick(View v);
23259    }
23260
23261    /**
23262     * Interface definition for a callback to be invoked when a drag is being dispatched
23263     * to this view.  The callback will be invoked before the hosting view's own
23264     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
23265     * onDrag(event) behavior, it should return 'false' from this callback.
23266     *
23267     * <div class="special reference">
23268     * <h3>Developer Guides</h3>
23269     * <p>For a guide to implementing drag and drop features, read the
23270     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23271     * </div>
23272     */
23273    public interface OnDragListener {
23274        /**
23275         * Called when a drag event is dispatched to a view. This allows listeners
23276         * to get a chance to override base View behavior.
23277         *
23278         * @param v The View that received the drag event.
23279         * @param event The {@link android.view.DragEvent} object for the drag event.
23280         * @return {@code true} if the drag event was handled successfully, or {@code false}
23281         * if the drag event was not handled. Note that {@code false} will trigger the View
23282         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
23283         */
23284        boolean onDrag(View v, DragEvent event);
23285    }
23286
23287    /**
23288     * Interface definition for a callback to be invoked when the focus state of
23289     * a view changed.
23290     */
23291    public interface OnFocusChangeListener {
23292        /**
23293         * Called when the focus state of a view has changed.
23294         *
23295         * @param v The view whose state has changed.
23296         * @param hasFocus The new focus state of v.
23297         */
23298        void onFocusChange(View v, boolean hasFocus);
23299    }
23300
23301    /**
23302     * Interface definition for a callback to be invoked when a view is clicked.
23303     */
23304    public interface OnClickListener {
23305        /**
23306         * Called when a view has been clicked.
23307         *
23308         * @param v The view that was clicked.
23309         */
23310        void onClick(View v);
23311    }
23312
23313    /**
23314     * Interface definition for a callback to be invoked when a view is context clicked.
23315     */
23316    public interface OnContextClickListener {
23317        /**
23318         * Called when a view is context clicked.
23319         *
23320         * @param v The view that has been context clicked.
23321         * @return true if the callback consumed the context click, false otherwise.
23322         */
23323        boolean onContextClick(View v);
23324    }
23325
23326    /**
23327     * Interface definition for a callback to be invoked when the context menu
23328     * for this view is being built.
23329     */
23330    public interface OnCreateContextMenuListener {
23331        /**
23332         * Called when the context menu for this view is being built. It is not
23333         * safe to hold onto the menu after this method returns.
23334         *
23335         * @param menu The context menu that is being built
23336         * @param v The view for which the context menu is being built
23337         * @param menuInfo Extra information about the item for which the
23338         *            context menu should be shown. This information will vary
23339         *            depending on the class of v.
23340         */
23341        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
23342    }
23343
23344    /**
23345     * Interface definition for a callback to be invoked when the status bar changes
23346     * visibility.  This reports <strong>global</strong> changes to the system UI
23347     * state, not what the application is requesting.
23348     *
23349     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
23350     */
23351    public interface OnSystemUiVisibilityChangeListener {
23352        /**
23353         * Called when the status bar changes visibility because of a call to
23354         * {@link View#setSystemUiVisibility(int)}.
23355         *
23356         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23357         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
23358         * This tells you the <strong>global</strong> state of these UI visibility
23359         * flags, not what your app is currently applying.
23360         */
23361        public void onSystemUiVisibilityChange(int visibility);
23362    }
23363
23364    /**
23365     * Interface definition for a callback to be invoked when this view is attached
23366     * or detached from its window.
23367     */
23368    public interface OnAttachStateChangeListener {
23369        /**
23370         * Called when the view is attached to a window.
23371         * @param v The view that was attached
23372         */
23373        public void onViewAttachedToWindow(View v);
23374        /**
23375         * Called when the view is detached from a window.
23376         * @param v The view that was detached
23377         */
23378        public void onViewDetachedFromWindow(View v);
23379    }
23380
23381    /**
23382     * Listener for applying window insets on a view in a custom way.
23383     *
23384     * <p>Apps may choose to implement this interface if they want to apply custom policy
23385     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
23386     * is set, its
23387     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
23388     * method will be called instead of the View's own
23389     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
23390     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
23391     * the View's normal behavior as part of its own.</p>
23392     */
23393    public interface OnApplyWindowInsetsListener {
23394        /**
23395         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
23396         * on a View, this listener method will be called instead of the view's own
23397         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
23398         *
23399         * @param v The view applying window insets
23400         * @param insets The insets to apply
23401         * @return The insets supplied, minus any insets that were consumed
23402         */
23403        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
23404    }
23405
23406    private final class UnsetPressedState implements Runnable {
23407        @Override
23408        public void run() {
23409            setPressed(false);
23410        }
23411    }
23412
23413    /**
23414     * Base class for derived classes that want to save and restore their own
23415     * state in {@link android.view.View#onSaveInstanceState()}.
23416     */
23417    public static class BaseSavedState extends AbsSavedState {
23418        String mStartActivityRequestWhoSaved;
23419
23420        /**
23421         * Constructor used when reading from a parcel. Reads the state of the superclass.
23422         *
23423         * @param source parcel to read from
23424         */
23425        public BaseSavedState(Parcel source) {
23426            this(source, null);
23427        }
23428
23429        /**
23430         * Constructor used when reading from a parcel using a given class loader.
23431         * Reads the state of the superclass.
23432         *
23433         * @param source parcel to read from
23434         * @param loader ClassLoader to use for reading
23435         */
23436        public BaseSavedState(Parcel source, ClassLoader loader) {
23437            super(source, loader);
23438            mStartActivityRequestWhoSaved = source.readString();
23439        }
23440
23441        /**
23442         * Constructor called by derived classes when creating their SavedState objects
23443         *
23444         * @param superState The state of the superclass of this view
23445         */
23446        public BaseSavedState(Parcelable superState) {
23447            super(superState);
23448        }
23449
23450        @Override
23451        public void writeToParcel(Parcel out, int flags) {
23452            super.writeToParcel(out, flags);
23453            out.writeString(mStartActivityRequestWhoSaved);
23454        }
23455
23456        public static final Parcelable.Creator<BaseSavedState> CREATOR
23457                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
23458            @Override
23459            public BaseSavedState createFromParcel(Parcel in) {
23460                return new BaseSavedState(in);
23461            }
23462
23463            @Override
23464            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
23465                return new BaseSavedState(in, loader);
23466            }
23467
23468            @Override
23469            public BaseSavedState[] newArray(int size) {
23470                return new BaseSavedState[size];
23471            }
23472        };
23473    }
23474
23475    /**
23476     * A set of information given to a view when it is attached to its parent
23477     * window.
23478     */
23479    final static class AttachInfo {
23480        interface Callbacks {
23481            void playSoundEffect(int effectId);
23482            boolean performHapticFeedback(int effectId, boolean always);
23483        }
23484
23485        /**
23486         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
23487         * to a Handler. This class contains the target (View) to invalidate and
23488         * the coordinates of the dirty rectangle.
23489         *
23490         * For performance purposes, this class also implements a pool of up to
23491         * POOL_LIMIT objects that get reused. This reduces memory allocations
23492         * whenever possible.
23493         */
23494        static class InvalidateInfo {
23495            private static final int POOL_LIMIT = 10;
23496
23497            private static final SynchronizedPool<InvalidateInfo> sPool =
23498                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
23499
23500            View target;
23501
23502            int left;
23503            int top;
23504            int right;
23505            int bottom;
23506
23507            public static InvalidateInfo obtain() {
23508                InvalidateInfo instance = sPool.acquire();
23509                return (instance != null) ? instance : new InvalidateInfo();
23510            }
23511
23512            public void recycle() {
23513                target = null;
23514                sPool.release(this);
23515            }
23516        }
23517
23518        final IWindowSession mSession;
23519
23520        final IWindow mWindow;
23521
23522        final IBinder mWindowToken;
23523
23524        final Display mDisplay;
23525
23526        final Callbacks mRootCallbacks;
23527
23528        IWindowId mIWindowId;
23529        WindowId mWindowId;
23530
23531        /**
23532         * The top view of the hierarchy.
23533         */
23534        View mRootView;
23535
23536        IBinder mPanelParentWindowToken;
23537
23538        boolean mHardwareAccelerated;
23539        boolean mHardwareAccelerationRequested;
23540        ThreadedRenderer mThreadedRenderer;
23541        List<RenderNode> mPendingAnimatingRenderNodes;
23542
23543        /**
23544         * The state of the display to which the window is attached, as reported
23545         * by {@link Display#getState()}.  Note that the display state constants
23546         * declared by {@link Display} do not exactly line up with the screen state
23547         * constants declared by {@link View} (there are more display states than
23548         * screen states).
23549         */
23550        int mDisplayState = Display.STATE_UNKNOWN;
23551
23552        /**
23553         * Scale factor used by the compatibility mode
23554         */
23555        float mApplicationScale;
23556
23557        /**
23558         * Indicates whether the application is in compatibility mode
23559         */
23560        boolean mScalingRequired;
23561
23562        /**
23563         * Left position of this view's window
23564         */
23565        int mWindowLeft;
23566
23567        /**
23568         * Top position of this view's window
23569         */
23570        int mWindowTop;
23571
23572        /**
23573         * Indicates whether views need to use 32-bit drawing caches
23574         */
23575        boolean mUse32BitDrawingCache;
23576
23577        /**
23578         * For windows that are full-screen but using insets to layout inside
23579         * of the screen areas, these are the current insets to appear inside
23580         * the overscan area of the display.
23581         */
23582        final Rect mOverscanInsets = new Rect();
23583
23584        /**
23585         * For windows that are full-screen but using insets to layout inside
23586         * of the screen decorations, these are the current insets for the
23587         * content of the window.
23588         */
23589        final Rect mContentInsets = new Rect();
23590
23591        /**
23592         * For windows that are full-screen but using insets to layout inside
23593         * of the screen decorations, these are the current insets for the
23594         * actual visible parts of the window.
23595         */
23596        final Rect mVisibleInsets = new Rect();
23597
23598        /**
23599         * For windows that are full-screen but using insets to layout inside
23600         * of the screen decorations, these are the current insets for the
23601         * stable system windows.
23602         */
23603        final Rect mStableInsets = new Rect();
23604
23605        /**
23606         * For windows that include areas that are not covered by real surface these are the outsets
23607         * for real surface.
23608         */
23609        final Rect mOutsets = new Rect();
23610
23611        /**
23612         * In multi-window we force show the navigation bar. Because we don't want that the surface
23613         * size changes in this mode, we instead have a flag whether the navigation bar size should
23614         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
23615         */
23616        boolean mAlwaysConsumeNavBar;
23617
23618        /**
23619         * The internal insets given by this window.  This value is
23620         * supplied by the client (through
23621         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
23622         * be given to the window manager when changed to be used in laying
23623         * out windows behind it.
23624         */
23625        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
23626                = new ViewTreeObserver.InternalInsetsInfo();
23627
23628        /**
23629         * Set to true when mGivenInternalInsets is non-empty.
23630         */
23631        boolean mHasNonEmptyGivenInternalInsets;
23632
23633        /**
23634         * All views in the window's hierarchy that serve as scroll containers,
23635         * used to determine if the window can be resized or must be panned
23636         * to adjust for a soft input area.
23637         */
23638        final ArrayList<View> mScrollContainers = new ArrayList<View>();
23639
23640        final KeyEvent.DispatcherState mKeyDispatchState
23641                = new KeyEvent.DispatcherState();
23642
23643        /**
23644         * Indicates whether the view's window currently has the focus.
23645         */
23646        boolean mHasWindowFocus;
23647
23648        /**
23649         * The current visibility of the window.
23650         */
23651        int mWindowVisibility;
23652
23653        /**
23654         * Indicates the time at which drawing started to occur.
23655         */
23656        long mDrawingTime;
23657
23658        /**
23659         * Indicates whether or not ignoring the DIRTY_MASK flags.
23660         */
23661        boolean mIgnoreDirtyState;
23662
23663        /**
23664         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
23665         * to avoid clearing that flag prematurely.
23666         */
23667        boolean mSetIgnoreDirtyState = false;
23668
23669        /**
23670         * Indicates whether the view's window is currently in touch mode.
23671         */
23672        boolean mInTouchMode;
23673
23674        /**
23675         * Indicates whether the view has requested unbuffered input dispatching for the current
23676         * event stream.
23677         */
23678        boolean mUnbufferedDispatchRequested;
23679
23680        /**
23681         * Indicates that ViewAncestor should trigger a global layout change
23682         * the next time it performs a traversal
23683         */
23684        boolean mRecomputeGlobalAttributes;
23685
23686        /**
23687         * Always report new attributes at next traversal.
23688         */
23689        boolean mForceReportNewAttributes;
23690
23691        /**
23692         * Set during a traveral if any views want to keep the screen on.
23693         */
23694        boolean mKeepScreenOn;
23695
23696        /**
23697         * Set during a traveral if the light center needs to be updated.
23698         */
23699        boolean mNeedsUpdateLightCenter;
23700
23701        /**
23702         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
23703         */
23704        int mSystemUiVisibility;
23705
23706        /**
23707         * Hack to force certain system UI visibility flags to be cleared.
23708         */
23709        int mDisabledSystemUiVisibility;
23710
23711        /**
23712         * Last global system UI visibility reported by the window manager.
23713         */
23714        int mGlobalSystemUiVisibility = -1;
23715
23716        /**
23717         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
23718         * attached.
23719         */
23720        boolean mHasSystemUiListeners;
23721
23722        /**
23723         * Set if the window has requested to extend into the overscan region
23724         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
23725         */
23726        boolean mOverscanRequested;
23727
23728        /**
23729         * Set if the visibility of any views has changed.
23730         */
23731        boolean mViewVisibilityChanged;
23732
23733        /**
23734         * Set to true if a view has been scrolled.
23735         */
23736        boolean mViewScrollChanged;
23737
23738        /**
23739         * Set to true if high contrast mode enabled
23740         */
23741        boolean mHighContrastText;
23742
23743        /**
23744         * Set to true if a pointer event is currently being handled.
23745         */
23746        boolean mHandlingPointerEvent;
23747
23748        /**
23749         * Global to the view hierarchy used as a temporary for dealing with
23750         * x/y points in the transparent region computations.
23751         */
23752        final int[] mTransparentLocation = new int[2];
23753
23754        /**
23755         * Global to the view hierarchy used as a temporary for dealing with
23756         * x/y points in the ViewGroup.invalidateChild implementation.
23757         */
23758        final int[] mInvalidateChildLocation = new int[2];
23759
23760        /**
23761         * Global to the view hierarchy used as a temporary for dealing with
23762         * computing absolute on-screen location.
23763         */
23764        final int[] mTmpLocation = new int[2];
23765
23766        /**
23767         * Global to the view hierarchy used as a temporary for dealing with
23768         * x/y location when view is transformed.
23769         */
23770        final float[] mTmpTransformLocation = new float[2];
23771
23772        /**
23773         * The view tree observer used to dispatch global events like
23774         * layout, pre-draw, touch mode change, etc.
23775         */
23776        final ViewTreeObserver mTreeObserver;
23777
23778        /**
23779         * A Canvas used by the view hierarchy to perform bitmap caching.
23780         */
23781        Canvas mCanvas;
23782
23783        /**
23784         * The view root impl.
23785         */
23786        final ViewRootImpl mViewRootImpl;
23787
23788        /**
23789         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
23790         * handler can be used to pump events in the UI events queue.
23791         */
23792        final Handler mHandler;
23793
23794        /**
23795         * Temporary for use in computing invalidate rectangles while
23796         * calling up the hierarchy.
23797         */
23798        final Rect mTmpInvalRect = new Rect();
23799
23800        /**
23801         * Temporary for use in computing hit areas with transformed views
23802         */
23803        final RectF mTmpTransformRect = new RectF();
23804
23805        /**
23806         * Temporary for use in computing hit areas with transformed views
23807         */
23808        final RectF mTmpTransformRect1 = new RectF();
23809
23810        /**
23811         * Temporary list of rectanges.
23812         */
23813        final List<RectF> mTmpRectList = new ArrayList<>();
23814
23815        /**
23816         * Temporary for use in transforming invalidation rect
23817         */
23818        final Matrix mTmpMatrix = new Matrix();
23819
23820        /**
23821         * Temporary for use in transforming invalidation rect
23822         */
23823        final Transformation mTmpTransformation = new Transformation();
23824
23825        /**
23826         * Temporary for use in querying outlines from OutlineProviders
23827         */
23828        final Outline mTmpOutline = new Outline();
23829
23830        /**
23831         * Temporary list for use in collecting focusable descendents of a view.
23832         */
23833        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
23834
23835        /**
23836         * The id of the window for accessibility purposes.
23837         */
23838        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
23839
23840        /**
23841         * Flags related to accessibility processing.
23842         *
23843         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
23844         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
23845         */
23846        int mAccessibilityFetchFlags;
23847
23848        /**
23849         * The drawable for highlighting accessibility focus.
23850         */
23851        Drawable mAccessibilityFocusDrawable;
23852
23853        /**
23854         * Show where the margins, bounds and layout bounds are for each view.
23855         */
23856        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23857
23858        /**
23859         * Point used to compute visible regions.
23860         */
23861        final Point mPoint = new Point();
23862
23863        /**
23864         * Used to track which View originated a requestLayout() call, used when
23865         * requestLayout() is called during layout.
23866         */
23867        View mViewRequestingLayout;
23868
23869        /**
23870         * Used to track views that need (at least) a partial relayout at their current size
23871         * during the next traversal.
23872         */
23873        List<View> mPartialLayoutViews = new ArrayList<>();
23874
23875        /**
23876         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23877         * modification. Lazily assigned during ViewRootImpl layout.
23878         */
23879        List<View> mEmptyPartialLayoutViews;
23880
23881        /**
23882         * Used to track the identity of the current drag operation.
23883         */
23884        IBinder mDragToken;
23885
23886        /**
23887         * The drag shadow surface for the current drag operation.
23888         */
23889        public Surface mDragSurface;
23890
23891
23892        /**
23893         * The view that currently has a tooltip displayed.
23894         */
23895        View mTooltipHost;
23896
23897        /**
23898         * Creates a new set of attachment information with the specified
23899         * events handler and thread.
23900         *
23901         * @param handler the events handler the view must use
23902         */
23903        AttachInfo(IWindowSession session, IWindow window, Display display,
23904                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
23905                Context context) {
23906            mSession = session;
23907            mWindow = window;
23908            mWindowToken = window.asBinder();
23909            mDisplay = display;
23910            mViewRootImpl = viewRootImpl;
23911            mHandler = handler;
23912            mRootCallbacks = effectPlayer;
23913            mTreeObserver = new ViewTreeObserver(context);
23914        }
23915    }
23916
23917    /**
23918     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23919     * is supported. This avoids keeping too many unused fields in most
23920     * instances of View.</p>
23921     */
23922    private static class ScrollabilityCache implements Runnable {
23923
23924        /**
23925         * Scrollbars are not visible
23926         */
23927        public static final int OFF = 0;
23928
23929        /**
23930         * Scrollbars are visible
23931         */
23932        public static final int ON = 1;
23933
23934        /**
23935         * Scrollbars are fading away
23936         */
23937        public static final int FADING = 2;
23938
23939        public boolean fadeScrollBars;
23940
23941        public int fadingEdgeLength;
23942        public int scrollBarDefaultDelayBeforeFade;
23943        public int scrollBarFadeDuration;
23944
23945        public int scrollBarSize;
23946        public ScrollBarDrawable scrollBar;
23947        public float[] interpolatorValues;
23948        public View host;
23949
23950        public final Paint paint;
23951        public final Matrix matrix;
23952        public Shader shader;
23953
23954        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23955
23956        private static final float[] OPAQUE = { 255 };
23957        private static final float[] TRANSPARENT = { 0.0f };
23958
23959        /**
23960         * When fading should start. This time moves into the future every time
23961         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23962         */
23963        public long fadeStartTime;
23964
23965
23966        /**
23967         * The current state of the scrollbars: ON, OFF, or FADING
23968         */
23969        public int state = OFF;
23970
23971        private int mLastColor;
23972
23973        public final Rect mScrollBarBounds = new Rect();
23974
23975        public static final int NOT_DRAGGING = 0;
23976        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23977        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23978        public int mScrollBarDraggingState = NOT_DRAGGING;
23979
23980        public float mScrollBarDraggingPos = 0;
23981
23982        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23983            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23984            scrollBarSize = configuration.getScaledScrollBarSize();
23985            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23986            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23987
23988            paint = new Paint();
23989            matrix = new Matrix();
23990            // use use a height of 1, and then wack the matrix each time we
23991            // actually use it.
23992            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23993            paint.setShader(shader);
23994            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23995
23996            this.host = host;
23997        }
23998
23999        public void setFadeColor(int color) {
24000            if (color != mLastColor) {
24001                mLastColor = color;
24002
24003                if (color != 0) {
24004                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
24005                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
24006                    paint.setShader(shader);
24007                    // Restore the default transfer mode (src_over)
24008                    paint.setXfermode(null);
24009                } else {
24010                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
24011                    paint.setShader(shader);
24012                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
24013                }
24014            }
24015        }
24016
24017        public void run() {
24018            long now = AnimationUtils.currentAnimationTimeMillis();
24019            if (now >= fadeStartTime) {
24020
24021                // the animation fades the scrollbars out by changing
24022                // the opacity (alpha) from fully opaque to fully
24023                // transparent
24024                int nextFrame = (int) now;
24025                int framesCount = 0;
24026
24027                Interpolator interpolator = scrollBarInterpolator;
24028
24029                // Start opaque
24030                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
24031
24032                // End transparent
24033                nextFrame += scrollBarFadeDuration;
24034                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
24035
24036                state = FADING;
24037
24038                // Kick off the fade animation
24039                host.invalidate(true);
24040            }
24041        }
24042    }
24043
24044    /**
24045     * Resuable callback for sending
24046     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
24047     */
24048    private class SendViewScrolledAccessibilityEvent implements Runnable {
24049        public volatile boolean mIsPending;
24050
24051        public void run() {
24052            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
24053            mIsPending = false;
24054        }
24055    }
24056
24057    /**
24058     * <p>
24059     * This class represents a delegate that can be registered in a {@link View}
24060     * to enhance accessibility support via composition rather via inheritance.
24061     * It is specifically targeted to widget developers that extend basic View
24062     * classes i.e. classes in package android.view, that would like their
24063     * applications to be backwards compatible.
24064     * </p>
24065     * <div class="special reference">
24066     * <h3>Developer Guides</h3>
24067     * <p>For more information about making applications accessible, read the
24068     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
24069     * developer guide.</p>
24070     * </div>
24071     * <p>
24072     * A scenario in which a developer would like to use an accessibility delegate
24073     * is overriding a method introduced in a later API version than the minimal API
24074     * version supported by the application. For example, the method
24075     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
24076     * in API version 4 when the accessibility APIs were first introduced. If a
24077     * developer would like his application to run on API version 4 devices (assuming
24078     * all other APIs used by the application are version 4 or lower) and take advantage
24079     * of this method, instead of overriding the method which would break the application's
24080     * backwards compatibility, he can override the corresponding method in this
24081     * delegate and register the delegate in the target View if the API version of
24082     * the system is high enough, i.e. the API version is the same as or higher than the API
24083     * version that introduced
24084     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
24085     * </p>
24086     * <p>
24087     * Here is an example implementation:
24088     * </p>
24089     * <code><pre><p>
24090     * if (Build.VERSION.SDK_INT >= 14) {
24091     *     // If the API version is equal of higher than the version in
24092     *     // which onInitializeAccessibilityNodeInfo was introduced we
24093     *     // register a delegate with a customized implementation.
24094     *     View view = findViewById(R.id.view_id);
24095     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
24096     *         public void onInitializeAccessibilityNodeInfo(View host,
24097     *                 AccessibilityNodeInfo info) {
24098     *             // Let the default implementation populate the info.
24099     *             super.onInitializeAccessibilityNodeInfo(host, info);
24100     *             // Set some other information.
24101     *             info.setEnabled(host.isEnabled());
24102     *         }
24103     *     });
24104     * }
24105     * </code></pre></p>
24106     * <p>
24107     * This delegate contains methods that correspond to the accessibility methods
24108     * in View. If a delegate has been specified the implementation in View hands
24109     * off handling to the corresponding method in this delegate. The default
24110     * implementation the delegate methods behaves exactly as the corresponding
24111     * method in View for the case of no accessibility delegate been set. Hence,
24112     * to customize the behavior of a View method, clients can override only the
24113     * corresponding delegate method without altering the behavior of the rest
24114     * accessibility related methods of the host view.
24115     * </p>
24116     * <p>
24117     * <strong>Note:</strong> On platform versions prior to
24118     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
24119     * views in the {@code android.widget.*} package are called <i>before</i>
24120     * host methods. This prevents certain properties such as class name from
24121     * being modified by overriding
24122     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
24123     * as any changes will be overwritten by the host class.
24124     * <p>
24125     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
24126     * methods are called <i>after</i> host methods, which all properties to be
24127     * modified without being overwritten by the host class.
24128     */
24129    public static class AccessibilityDelegate {
24130
24131        /**
24132         * Sends an accessibility event of the given type. If accessibility is not
24133         * enabled this method has no effect.
24134         * <p>
24135         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
24136         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
24137         * been set.
24138         * </p>
24139         *
24140         * @param host The View hosting the delegate.
24141         * @param eventType The type of the event to send.
24142         *
24143         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
24144         */
24145        public void sendAccessibilityEvent(View host, int eventType) {
24146            host.sendAccessibilityEventInternal(eventType);
24147        }
24148
24149        /**
24150         * Performs the specified accessibility action on the view. For
24151         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
24152         * <p>
24153         * The default implementation behaves as
24154         * {@link View#performAccessibilityAction(int, Bundle)
24155         *  View#performAccessibilityAction(int, Bundle)} for the case of
24156         *  no accessibility delegate been set.
24157         * </p>
24158         *
24159         * @param action The action to perform.
24160         * @return Whether the action was performed.
24161         *
24162         * @see View#performAccessibilityAction(int, Bundle)
24163         *      View#performAccessibilityAction(int, Bundle)
24164         */
24165        public boolean performAccessibilityAction(View host, int action, Bundle args) {
24166            return host.performAccessibilityActionInternal(action, args);
24167        }
24168
24169        /**
24170         * Sends an accessibility event. This method behaves exactly as
24171         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
24172         * empty {@link AccessibilityEvent} and does not perform a check whether
24173         * accessibility is enabled.
24174         * <p>
24175         * The default implementation behaves as
24176         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24177         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
24178         * the case of no accessibility delegate been set.
24179         * </p>
24180         *
24181         * @param host The View hosting the delegate.
24182         * @param event The event to send.
24183         *
24184         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24185         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
24186         */
24187        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
24188            host.sendAccessibilityEventUncheckedInternal(event);
24189        }
24190
24191        /**
24192         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
24193         * to its children for adding their text content to the event.
24194         * <p>
24195         * The default implementation behaves as
24196         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24197         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
24198         * the case of no accessibility delegate been set.
24199         * </p>
24200         *
24201         * @param host The View hosting the delegate.
24202         * @param event The event.
24203         * @return True if the event population was completed.
24204         *
24205         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24206         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
24207         */
24208        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24209            return host.dispatchPopulateAccessibilityEventInternal(event);
24210        }
24211
24212        /**
24213         * Gives a chance to the host View to populate the accessibility event with its
24214         * text content.
24215         * <p>
24216         * The default implementation behaves as
24217         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
24218         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
24219         * the case of no accessibility delegate been set.
24220         * </p>
24221         *
24222         * @param host The View hosting the delegate.
24223         * @param event The accessibility event which to populate.
24224         *
24225         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
24226         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
24227         */
24228        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
24229            host.onPopulateAccessibilityEventInternal(event);
24230        }
24231
24232        /**
24233         * Initializes an {@link AccessibilityEvent} with information about the
24234         * the host View which is the event source.
24235         * <p>
24236         * The default implementation behaves as
24237         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
24238         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
24239         * the case of no accessibility delegate been set.
24240         * </p>
24241         *
24242         * @param host The View hosting the delegate.
24243         * @param event The event to initialize.
24244         *
24245         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
24246         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
24247         */
24248        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
24249            host.onInitializeAccessibilityEventInternal(event);
24250        }
24251
24252        /**
24253         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
24254         * <p>
24255         * The default implementation behaves as
24256         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24257         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
24258         * the case of no accessibility delegate been set.
24259         * </p>
24260         *
24261         * @param host The View hosting the delegate.
24262         * @param info The instance to initialize.
24263         *
24264         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24265         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
24266         */
24267        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
24268            host.onInitializeAccessibilityNodeInfoInternal(info);
24269        }
24270
24271        /**
24272         * Called when a child of the host View has requested sending an
24273         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
24274         * to augment the event.
24275         * <p>
24276         * The default implementation behaves as
24277         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24278         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
24279         * the case of no accessibility delegate been set.
24280         * </p>
24281         *
24282         * @param host The View hosting the delegate.
24283         * @param child The child which requests sending the event.
24284         * @param event The event to be sent.
24285         * @return True if the event should be sent
24286         *
24287         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24288         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
24289         */
24290        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
24291                AccessibilityEvent event) {
24292            return host.onRequestSendAccessibilityEventInternal(child, event);
24293        }
24294
24295        /**
24296         * Gets the provider for managing a virtual view hierarchy rooted at this View
24297         * and reported to {@link android.accessibilityservice.AccessibilityService}s
24298         * that explore the window content.
24299         * <p>
24300         * The default implementation behaves as
24301         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
24302         * the case of no accessibility delegate been set.
24303         * </p>
24304         *
24305         * @return The provider.
24306         *
24307         * @see AccessibilityNodeProvider
24308         */
24309        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
24310            return null;
24311        }
24312
24313        /**
24314         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
24315         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
24316         * This method is responsible for obtaining an accessibility node info from a
24317         * pool of reusable instances and calling
24318         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
24319         * view to initialize the former.
24320         * <p>
24321         * <strong>Note:</strong> The client is responsible for recycling the obtained
24322         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
24323         * creation.
24324         * </p>
24325         * <p>
24326         * The default implementation behaves as
24327         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
24328         * the case of no accessibility delegate been set.
24329         * </p>
24330         * @return A populated {@link AccessibilityNodeInfo}.
24331         *
24332         * @see AccessibilityNodeInfo
24333         *
24334         * @hide
24335         */
24336        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
24337            return host.createAccessibilityNodeInfoInternal();
24338        }
24339    }
24340
24341    private class MatchIdPredicate implements Predicate<View> {
24342        public int mId;
24343
24344        @Override
24345        public boolean apply(View view) {
24346            return (view.mID == mId);
24347        }
24348    }
24349
24350    private class MatchLabelForPredicate implements Predicate<View> {
24351        private int mLabeledId;
24352
24353        @Override
24354        public boolean apply(View view) {
24355            return (view.mLabelForId == mLabeledId);
24356        }
24357    }
24358
24359    private class SendViewStateChangedAccessibilityEvent implements Runnable {
24360        private int mChangeTypes = 0;
24361        private boolean mPosted;
24362        private boolean mPostedWithDelay;
24363        private long mLastEventTimeMillis;
24364
24365        @Override
24366        public void run() {
24367            mPosted = false;
24368            mPostedWithDelay = false;
24369            mLastEventTimeMillis = SystemClock.uptimeMillis();
24370            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
24371                final AccessibilityEvent event = AccessibilityEvent.obtain();
24372                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
24373                event.setContentChangeTypes(mChangeTypes);
24374                sendAccessibilityEventUnchecked(event);
24375            }
24376            mChangeTypes = 0;
24377        }
24378
24379        public void runOrPost(int changeType) {
24380            mChangeTypes |= changeType;
24381
24382            // If this is a live region or the child of a live region, collect
24383            // all events from this frame and send them on the next frame.
24384            if (inLiveRegion()) {
24385                // If we're already posted with a delay, remove that.
24386                if (mPostedWithDelay) {
24387                    removeCallbacks(this);
24388                    mPostedWithDelay = false;
24389                }
24390                // Only post if we're not already posted.
24391                if (!mPosted) {
24392                    post(this);
24393                    mPosted = true;
24394                }
24395                return;
24396            }
24397
24398            if (mPosted) {
24399                return;
24400            }
24401
24402            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
24403            final long minEventIntevalMillis =
24404                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
24405            if (timeSinceLastMillis >= minEventIntevalMillis) {
24406                removeCallbacks(this);
24407                run();
24408            } else {
24409                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
24410                mPostedWithDelay = true;
24411            }
24412        }
24413    }
24414
24415    private boolean inLiveRegion() {
24416        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24417            return true;
24418        }
24419
24420        ViewParent parent = getParent();
24421        while (parent instanceof View) {
24422            if (((View) parent).getAccessibilityLiveRegion()
24423                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
24424                return true;
24425            }
24426            parent = parent.getParent();
24427        }
24428
24429        return false;
24430    }
24431
24432    /**
24433     * Dump all private flags in readable format, useful for documentation and
24434     * sanity checking.
24435     */
24436    private static void dumpFlags() {
24437        final HashMap<String, String> found = Maps.newHashMap();
24438        try {
24439            for (Field field : View.class.getDeclaredFields()) {
24440                final int modifiers = field.getModifiers();
24441                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
24442                    if (field.getType().equals(int.class)) {
24443                        final int value = field.getInt(null);
24444                        dumpFlag(found, field.getName(), value);
24445                    } else if (field.getType().equals(int[].class)) {
24446                        final int[] values = (int[]) field.get(null);
24447                        for (int i = 0; i < values.length; i++) {
24448                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
24449                        }
24450                    }
24451                }
24452            }
24453        } catch (IllegalAccessException e) {
24454            throw new RuntimeException(e);
24455        }
24456
24457        final ArrayList<String> keys = Lists.newArrayList();
24458        keys.addAll(found.keySet());
24459        Collections.sort(keys);
24460        for (String key : keys) {
24461            Log.d(VIEW_LOG_TAG, found.get(key));
24462        }
24463    }
24464
24465    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
24466        // Sort flags by prefix, then by bits, always keeping unique keys
24467        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
24468        final int prefix = name.indexOf('_');
24469        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
24470        final String output = bits + " " + name;
24471        found.put(key, output);
24472    }
24473
24474    /** {@hide} */
24475    public void encode(@NonNull ViewHierarchyEncoder stream) {
24476        stream.beginObject(this);
24477        encodeProperties(stream);
24478        stream.endObject();
24479    }
24480
24481    /** {@hide} */
24482    @CallSuper
24483    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
24484        Object resolveId = ViewDebug.resolveId(getContext(), mID);
24485        if (resolveId instanceof String) {
24486            stream.addProperty("id", (String) resolveId);
24487        } else {
24488            stream.addProperty("id", mID);
24489        }
24490
24491        stream.addProperty("misc:transformation.alpha",
24492                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
24493        stream.addProperty("misc:transitionName", getTransitionName());
24494
24495        // layout
24496        stream.addProperty("layout:left", mLeft);
24497        stream.addProperty("layout:right", mRight);
24498        stream.addProperty("layout:top", mTop);
24499        stream.addProperty("layout:bottom", mBottom);
24500        stream.addProperty("layout:width", getWidth());
24501        stream.addProperty("layout:height", getHeight());
24502        stream.addProperty("layout:layoutDirection", getLayoutDirection());
24503        stream.addProperty("layout:layoutRtl", isLayoutRtl());
24504        stream.addProperty("layout:hasTransientState", hasTransientState());
24505        stream.addProperty("layout:baseline", getBaseline());
24506
24507        // layout params
24508        ViewGroup.LayoutParams layoutParams = getLayoutParams();
24509        if (layoutParams != null) {
24510            stream.addPropertyKey("layoutParams");
24511            layoutParams.encode(stream);
24512        }
24513
24514        // scrolling
24515        stream.addProperty("scrolling:scrollX", mScrollX);
24516        stream.addProperty("scrolling:scrollY", mScrollY);
24517
24518        // padding
24519        stream.addProperty("padding:paddingLeft", mPaddingLeft);
24520        stream.addProperty("padding:paddingRight", mPaddingRight);
24521        stream.addProperty("padding:paddingTop", mPaddingTop);
24522        stream.addProperty("padding:paddingBottom", mPaddingBottom);
24523        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
24524        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
24525        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
24526        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
24527        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
24528
24529        // measurement
24530        stream.addProperty("measurement:minHeight", mMinHeight);
24531        stream.addProperty("measurement:minWidth", mMinWidth);
24532        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
24533        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
24534
24535        // drawing
24536        stream.addProperty("drawing:elevation", getElevation());
24537        stream.addProperty("drawing:translationX", getTranslationX());
24538        stream.addProperty("drawing:translationY", getTranslationY());
24539        stream.addProperty("drawing:translationZ", getTranslationZ());
24540        stream.addProperty("drawing:rotation", getRotation());
24541        stream.addProperty("drawing:rotationX", getRotationX());
24542        stream.addProperty("drawing:rotationY", getRotationY());
24543        stream.addProperty("drawing:scaleX", getScaleX());
24544        stream.addProperty("drawing:scaleY", getScaleY());
24545        stream.addProperty("drawing:pivotX", getPivotX());
24546        stream.addProperty("drawing:pivotY", getPivotY());
24547        stream.addProperty("drawing:opaque", isOpaque());
24548        stream.addProperty("drawing:alpha", getAlpha());
24549        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
24550        stream.addProperty("drawing:shadow", hasShadow());
24551        stream.addProperty("drawing:solidColor", getSolidColor());
24552        stream.addProperty("drawing:layerType", mLayerType);
24553        stream.addProperty("drawing:willNotDraw", willNotDraw());
24554        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
24555        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
24556        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
24557        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
24558
24559        // focus
24560        stream.addProperty("focus:hasFocus", hasFocus());
24561        stream.addProperty("focus:isFocused", isFocused());
24562        stream.addProperty("focus:isFocusable", isFocusable());
24563        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
24564
24565        stream.addProperty("misc:clickable", isClickable());
24566        stream.addProperty("misc:pressed", isPressed());
24567        stream.addProperty("misc:selected", isSelected());
24568        stream.addProperty("misc:touchMode", isInTouchMode());
24569        stream.addProperty("misc:hovered", isHovered());
24570        stream.addProperty("misc:activated", isActivated());
24571
24572        stream.addProperty("misc:visibility", getVisibility());
24573        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
24574        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
24575
24576        stream.addProperty("misc:enabled", isEnabled());
24577        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
24578        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
24579
24580        // theme attributes
24581        Resources.Theme theme = getContext().getTheme();
24582        if (theme != null) {
24583            stream.addPropertyKey("theme");
24584            theme.encode(stream);
24585        }
24586
24587        // view attribute information
24588        int n = mAttributes != null ? mAttributes.length : 0;
24589        stream.addProperty("meta:__attrCount__", n/2);
24590        for (int i = 0; i < n; i += 2) {
24591            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
24592        }
24593
24594        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
24595
24596        // text
24597        stream.addProperty("text:textDirection", getTextDirection());
24598        stream.addProperty("text:textAlignment", getTextAlignment());
24599
24600        // accessibility
24601        CharSequence contentDescription = getContentDescription();
24602        stream.addProperty("accessibility:contentDescription",
24603                contentDescription == null ? "" : contentDescription.toString());
24604        stream.addProperty("accessibility:labelFor", getLabelFor());
24605        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
24606    }
24607
24608    /**
24609     * Determine if this view is rendered on a round wearable device and is the main view
24610     * on the screen.
24611     */
24612    private boolean shouldDrawRoundScrollbar() {
24613        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
24614            return false;
24615        }
24616
24617        final View rootView = getRootView();
24618        final WindowInsets insets = getRootWindowInsets();
24619
24620        int height = getHeight();
24621        int width = getWidth();
24622        int displayHeight = rootView.getHeight();
24623        int displayWidth = rootView.getWidth();
24624
24625        if (height != displayHeight || width != displayWidth) {
24626            return false;
24627        }
24628
24629        getLocationOnScreen(mAttachInfo.mTmpLocation);
24630        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
24631                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
24632    }
24633
24634    /**
24635     * Sets the tooltip text which will be displayed in a small popup next to the view.
24636     * <p>
24637     * The tooltip will be displayed:
24638     * <li>On long click, unless is not handled otherwise (by OnLongClickListener or a context
24639     * menu). </li>
24640     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
24641     *
24642     * @param tooltip the tooltip text, or null if no tooltip is required
24643     */
24644    public final void setTooltip(@Nullable CharSequence tooltip) {
24645        if (TextUtils.isEmpty(tooltip)) {
24646            setFlags(0, TOOLTIP);
24647            hideTooltip();
24648            mTooltipInfo = null;
24649        } else {
24650            setFlags(TOOLTIP, TOOLTIP);
24651            if (mTooltipInfo == null) {
24652                mTooltipInfo = new TooltipInfo();
24653                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
24654                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
24655            }
24656            mTooltipInfo.mTooltip = tooltip;
24657            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
24658                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltip);
24659            }
24660        }
24661    }
24662
24663    /**
24664     * Returns the view's tooltip text.
24665     *
24666     * @return the tooltip text
24667     */
24668    @Nullable
24669    public final CharSequence getTooltip() {
24670        return mTooltipInfo != null ? mTooltipInfo.mTooltip : null;
24671    }
24672
24673    private boolean showTooltip(int x, int y, boolean fromLongClick) {
24674        if (mAttachInfo == null) {
24675            return false;
24676        }
24677        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
24678            return false;
24679        }
24680        final CharSequence tooltipText = getTooltip();
24681        if (TextUtils.isEmpty(tooltipText)) {
24682            return false;
24683        }
24684        hideTooltip();
24685        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
24686        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
24687        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
24688        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, tooltipText);
24689        mAttachInfo.mTooltipHost = this;
24690        return true;
24691    }
24692
24693    void hideTooltip() {
24694        if (mTooltipInfo == null) {
24695            return;
24696        }
24697        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24698        if (mTooltipInfo.mTooltipPopup == null) {
24699            return;
24700        }
24701        mTooltipInfo.mTooltipPopup.hide();
24702        mTooltipInfo.mTooltipPopup = null;
24703        mTooltipInfo.mTooltipFromLongClick = false;
24704        if (mAttachInfo != null) {
24705            mAttachInfo.mTooltipHost = null;
24706        }
24707    }
24708
24709    private boolean showLongClickTooltip(int x, int y) {
24710        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24711        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24712        return showTooltip(x, y, true);
24713    }
24714
24715    private void showHoverTooltip() {
24716        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
24717    }
24718
24719    boolean dispatchTooltipHoverEvent(MotionEvent event) {
24720        if (mTooltipInfo == null) {
24721            return false;
24722        }
24723        switch(event.getAction()) {
24724            case MotionEvent.ACTION_HOVER_MOVE:
24725                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
24726                    break;
24727                }
24728                if (!mTooltipInfo.mTooltipFromLongClick) {
24729                    if (mTooltipInfo.mTooltipPopup == null) {
24730                        // Schedule showing the tooltip after a timeout.
24731                        mTooltipInfo.mAnchorX = (int) event.getX();
24732                        mTooltipInfo.mAnchorY = (int) event.getY();
24733                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
24734                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
24735                                ViewConfiguration.getHoverTooltipShowTimeout());
24736                    }
24737
24738                    // Hide hover-triggered tooltip after a period of inactivity.
24739                    // Match the timeout used by NativeInputManager to hide the mouse pointer
24740                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
24741                    final int timeout;
24742                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
24743                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
24744                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
24745                    } else {
24746                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
24747                    }
24748                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24749                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
24750                }
24751                return true;
24752
24753            case MotionEvent.ACTION_HOVER_EXIT:
24754                if (!mTooltipInfo.mTooltipFromLongClick) {
24755                    hideTooltip();
24756                }
24757                break;
24758        }
24759        return false;
24760    }
24761
24762    void handleTooltipKey(KeyEvent event) {
24763        switch (event.getAction()) {
24764            case KeyEvent.ACTION_DOWN:
24765                if (event.getRepeatCount() == 0) {
24766                    hideTooltip();
24767                }
24768                break;
24769
24770            case KeyEvent.ACTION_UP:
24771                handleTooltipUp();
24772                break;
24773        }
24774    }
24775
24776    private void handleTooltipUp() {
24777        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24778            return;
24779        }
24780        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
24781        postDelayed(mTooltipInfo.mHideTooltipRunnable,
24782                ViewConfiguration.getLongPressTooltipHideTimeout());
24783    }
24784
24785    /**
24786     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
24787     * is not showing.
24788     * @hide
24789     */
24790    @TestApi
24791    public View getTooltipView() {
24792        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
24793            return null;
24794        }
24795        return mTooltipInfo.mTooltipPopup.getContentView();
24796    }
24797}
24798