View.java revision 1edc6daf1d13ec472da2aae2a2a88d130c495cb7
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 android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.CallSuper;
22import android.annotation.ColorInt;
23import android.annotation.DrawableRes;
24import android.annotation.FloatRange;
25import android.annotation.IdRes;
26import android.annotation.IntDef;
27import android.annotation.IntRange;
28import android.annotation.LayoutRes;
29import android.annotation.NonNull;
30import android.annotation.Nullable;
31import android.annotation.Size;
32import android.annotation.UiThread;
33import android.content.ClipData;
34import android.content.Context;
35import android.content.ContextWrapper;
36import android.content.Intent;
37import android.content.res.ColorStateList;
38import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.content.res.TypedArray;
41import android.graphics.Bitmap;
42import android.graphics.Canvas;
43import android.graphics.Insets;
44import android.graphics.Interpolator;
45import android.graphics.LinearGradient;
46import android.graphics.Matrix;
47import android.graphics.Outline;
48import android.graphics.Paint;
49import android.graphics.PixelFormat;
50import android.graphics.Point;
51import android.graphics.PorterDuff;
52import android.graphics.PorterDuffXfermode;
53import android.graphics.Rect;
54import android.graphics.RectF;
55import android.graphics.Region;
56import android.graphics.Shader;
57import android.graphics.drawable.ColorDrawable;
58import android.graphics.drawable.Drawable;
59import android.hardware.display.DisplayManagerGlobal;
60import android.os.Build.VERSION_CODES;
61import android.os.Bundle;
62import android.os.Handler;
63import android.os.IBinder;
64import android.os.Parcel;
65import android.os.Parcelable;
66import android.os.RemoteException;
67import android.os.SystemClock;
68import android.os.SystemProperties;
69import android.os.Trace;
70import android.text.TextUtils;
71import android.util.AttributeSet;
72import android.util.FloatProperty;
73import android.util.LayoutDirection;
74import android.util.Log;
75import android.util.LongSparseLongArray;
76import android.util.Pools.SynchronizedPool;
77import android.util.Property;
78import android.util.SparseArray;
79import android.util.StateSet;
80import android.util.SuperNotCalledException;
81import android.util.TypedValue;
82import android.view.ContextMenu.ContextMenuInfo;
83import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
85import android.view.AccessibilityIterators.TextSegmentIterator;
86import android.view.AccessibilityIterators.WordTextSegmentIterator;
87import android.view.accessibility.AccessibilityEvent;
88import android.view.accessibility.AccessibilityEventSource;
89import android.view.accessibility.AccessibilityManager;
90import android.view.accessibility.AccessibilityNodeInfo;
91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
92import android.view.accessibility.AccessibilityNodeProvider;
93import android.view.animation.Animation;
94import android.view.animation.AnimationUtils;
95import android.view.animation.Transformation;
96import android.view.inputmethod.EditorInfo;
97import android.view.inputmethod.InputConnection;
98import android.view.inputmethod.InputMethodManager;
99import android.widget.Checkable;
100import android.widget.FrameLayout;
101import android.widget.ScrollBarDrawable;
102import static android.os.Build.VERSION_CODES.*;
103import static java.lang.Math.max;
104
105import com.android.internal.R;
106import com.android.internal.util.Predicate;
107import com.android.internal.view.menu.MenuBuilder;
108import com.android.internal.widget.ScrollBarUtils;
109import com.google.android.collect.Lists;
110import com.google.android.collect.Maps;
111
112import java.lang.NullPointerException;
113import java.lang.annotation.Retention;
114import java.lang.annotation.RetentionPolicy;
115import java.lang.ref.WeakReference;
116import java.lang.reflect.Field;
117import java.lang.reflect.InvocationTargetException;
118import java.lang.reflect.Method;
119import java.lang.reflect.Modifier;
120import java.util.ArrayList;
121import java.util.Arrays;
122import java.util.Collections;
123import java.util.HashMap;
124import java.util.List;
125import java.util.Locale;
126import java.util.Map;
127import java.util.concurrent.CopyOnWriteArrayList;
128import java.util.concurrent.atomic.AtomicInteger;
129
130/**
131 * <p>
132 * This class represents the basic building block for user interface components. A View
133 * occupies a rectangular area on the screen and is responsible for drawing and
134 * event handling. View is the base class for <em>widgets</em>, which are
135 * used to create interactive UI components (buttons, text fields, etc.). The
136 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
137 * are invisible containers that hold other Views (or other ViewGroups) and define
138 * their layout properties.
139 * </p>
140 *
141 * <div class="special reference">
142 * <h3>Developer Guides</h3>
143 * <p>For information about using this class to develop your application's user interface,
144 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
145 * </div>
146 *
147 * <a name="Using"></a>
148 * <h3>Using Views</h3>
149 * <p>
150 * All of the views in a window are arranged in a single tree. You can add views
151 * either from code or by specifying a tree of views in one or more XML layout
152 * files. There are many specialized subclasses of views that act as controls or
153 * are capable of displaying text, images, or other content.
154 * </p>
155 * <p>
156 * Once you have created a tree of views, there are typically a few types of
157 * common operations you may wish to perform:
158 * <ul>
159 * <li><strong>Set properties:</strong> for example setting the text of a
160 * {@link android.widget.TextView}. The available properties and the methods
161 * that set them will vary among the different subclasses of views. Note that
162 * properties that are known at build time can be set in the XML layout
163 * files.</li>
164 * <li><strong>Set focus:</strong> The framework will handle moving focus in
165 * response to user input. To force focus to a specific view, call
166 * {@link #requestFocus}.</li>
167 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
168 * that will be notified when something interesting happens to the view. For
169 * example, all views will let you set a listener to be notified when the view
170 * gains or loses focus. You can register such a listener using
171 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
172 * Other view subclasses offer more specialized listeners. For example, a Button
173 * exposes a listener to notify clients when the button is clicked.</li>
174 * <li><strong>Set visibility:</strong> You can hide or show views using
175 * {@link #setVisibility(int)}.</li>
176 * </ul>
177 * </p>
178 * <p><em>
179 * Note: The Android framework is responsible for measuring, laying out and
180 * drawing views. You should not call methods that perform these actions on
181 * views yourself unless you are actually implementing a
182 * {@link android.view.ViewGroup}.
183 * </em></p>
184 *
185 * <a name="Lifecycle"></a>
186 * <h3>Implementing a Custom View</h3>
187 *
188 * <p>
189 * To implement a custom view, you will usually begin by providing overrides for
190 * some of the standard methods that the framework calls on all views. You do
191 * not need to override all of these methods. In fact, you can start by just
192 * overriding {@link #onDraw(android.graphics.Canvas)}.
193 * <table border="2" width="85%" align="center" cellpadding="5">
194 *     <thead>
195 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
196 *     </thead>
197 *
198 *     <tbody>
199 *     <tr>
200 *         <td rowspan="2">Creation</td>
201 *         <td>Constructors</td>
202 *         <td>There is a form of the constructor that are called when the view
203 *         is created from code and a form that is called when the view is
204 *         inflated from a layout file. The second form should parse and apply
205 *         any attributes defined in the layout file.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onFinishInflate()}</code></td>
210 *         <td>Called after a view and all of its children has been inflated
211 *         from XML.</td>
212 *     </tr>
213 *
214 *     <tr>
215 *         <td rowspan="3">Layout</td>
216 *         <td><code>{@link #onMeasure(int, int)}</code></td>
217 *         <td>Called to determine the size requirements for this view and all
218 *         of its children.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
223 *         <td>Called when this view should assign a size and position to all
224 *         of its children.
225 *         </td>
226 *     </tr>
227 *     <tr>
228 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
229 *         <td>Called when the size of this view has changed.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td>Drawing</td>
235 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
236 *         <td>Called when the view should render its content.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td rowspan="4">Event processing</td>
242 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
243 *         <td>Called when a new hardware key event occurs.
244 *         </td>
245 *     </tr>
246 *     <tr>
247 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
248 *         <td>Called when a hardware key up event occurs.
249 *         </td>
250 *     </tr>
251 *     <tr>
252 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
253 *         <td>Called when a trackball motion event occurs.
254 *         </td>
255 *     </tr>
256 *     <tr>
257 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
258 *         <td>Called when a touch screen motion event occurs.
259 *         </td>
260 *     </tr>
261 *
262 *     <tr>
263 *         <td rowspan="2">Focus</td>
264 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
265 *         <td>Called when the view gains or loses focus.
266 *         </td>
267 *     </tr>
268 *
269 *     <tr>
270 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
271 *         <td>Called when the window containing the view gains or loses focus.
272 *         </td>
273 *     </tr>
274 *
275 *     <tr>
276 *         <td rowspan="3">Attaching</td>
277 *         <td><code>{@link #onAttachedToWindow()}</code></td>
278 *         <td>Called when the view is attached to a window.
279 *         </td>
280 *     </tr>
281 *
282 *     <tr>
283 *         <td><code>{@link #onDetachedFromWindow}</code></td>
284 *         <td>Called when the view is detached from its window.
285 *         </td>
286 *     </tr>
287 *
288 *     <tr>
289 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
290 *         <td>Called when the visibility of the window containing the view
291 *         has changed.
292 *         </td>
293 *     </tr>
294 *     </tbody>
295 *
296 * </table>
297 * </p>
298 *
299 * <a name="IDs"></a>
300 * <h3>IDs</h3>
301 * Views may have an integer id associated with them. These ids are typically
302 * assigned in the layout XML files, and are used to find specific views within
303 * the view tree. A common pattern is to:
304 * <ul>
305 * <li>Define a Button in the layout file and assign it a unique ID.
306 * <pre>
307 * &lt;Button
308 *     android:id="@+id/my_button"
309 *     android:layout_width="wrap_content"
310 *     android:layout_height="wrap_content"
311 *     android:text="@string/my_button_text"/&gt;
312 * </pre></li>
313 * <li>From the onCreate method of an Activity, find the Button
314 * <pre class="prettyprint">
315 *      Button myButton = (Button) findViewById(R.id.my_button);
316 * </pre></li>
317 * </ul>
318 * <p>
319 * View IDs need not be unique throughout the tree, but it is good practice to
320 * ensure that they are at least unique within the part of the tree you are
321 * searching.
322 * </p>
323 *
324 * <a name="Position"></a>
325 * <h3>Position</h3>
326 * <p>
327 * The geometry of a view is that of a rectangle. A view has a location,
328 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
329 * two dimensions, expressed as a width and a height. The unit for location
330 * and dimensions is the pixel.
331 * </p>
332 *
333 * <p>
334 * It is possible to retrieve the location of a view by invoking the methods
335 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
336 * coordinate of the rectangle representing the view. The latter returns the
337 * top, or Y, coordinate of the rectangle representing the view. These methods
338 * both return the location of the view relative to its parent. For instance,
339 * when getLeft() returns 20, that means the view is located 20 pixels to the
340 * right of the left edge of its direct parent.
341 * </p>
342 *
343 * <p>
344 * In addition, several convenience methods are offered to avoid unnecessary
345 * computations, namely {@link #getRight()} and {@link #getBottom()}.
346 * These methods return the coordinates of the right and bottom edges of the
347 * rectangle representing the view. For instance, calling {@link #getRight()}
348 * is similar to the following computation: <code>getLeft() + getWidth()</code>
349 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
350 * </p>
351 *
352 * <a name="SizePaddingMargins"></a>
353 * <h3>Size, padding and margins</h3>
354 * <p>
355 * The size of a view is expressed with a width and a height. A view actually
356 * possess two pairs of width and height values.
357 * </p>
358 *
359 * <p>
360 * The first pair is known as <em>measured width</em> and
361 * <em>measured height</em>. These dimensions define how big a view wants to be
362 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
363 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
364 * and {@link #getMeasuredHeight()}.
365 * </p>
366 *
367 * <p>
368 * The second pair is simply known as <em>width</em> and <em>height</em>, or
369 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
370 * dimensions define the actual size of the view on screen, at drawing time and
371 * after layout. These values may, but do not have to, be different from the
372 * measured width and height. The width and height can be obtained by calling
373 * {@link #getWidth()} and {@link #getHeight()}.
374 * </p>
375 *
376 * <p>
377 * To measure its dimensions, a view takes into account its padding. The padding
378 * is expressed in pixels for the left, top, right and bottom parts of the view.
379 * Padding can be used to offset the content of the view by a specific amount of
380 * pixels. For instance, a left padding of 2 will push the view's content by
381 * 2 pixels to the right of the left edge. Padding can be set using the
382 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
383 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
384 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
385 * {@link #getPaddingEnd()}.
386 * </p>
387 *
388 * <p>
389 * Even though a view can define a padding, it does not provide any support for
390 * margins. However, view groups provide such a support. Refer to
391 * {@link android.view.ViewGroup} and
392 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
393 * </p>
394 *
395 * <a name="Layout"></a>
396 * <h3>Layout</h3>
397 * <p>
398 * Layout is a two pass process: a measure pass and a layout pass. The measuring
399 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
400 * of the view tree. Each view pushes dimension specifications down the tree
401 * during the recursion. At the end of the measure pass, every view has stored
402 * its measurements. The second pass happens in
403 * {@link #layout(int,int,int,int)} and is also top-down. During
404 * this pass each parent is responsible for positioning all of its children
405 * using the sizes computed in the measure pass.
406 * </p>
407 *
408 * <p>
409 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
410 * {@link #getMeasuredHeight()} values must be set, along with those for all of
411 * that view's descendants. A view's measured width and measured height values
412 * must respect the constraints imposed by the view's parents. This guarantees
413 * that at the end of the measure pass, all parents accept all of their
414 * children's measurements. A parent view may call measure() more than once on
415 * its children. For example, the parent may measure each child once with
416 * unspecified dimensions to find out how big they want to be, then call
417 * measure() on them again with actual numbers if the sum of all the children's
418 * unconstrained sizes is too big or too small.
419 * </p>
420 *
421 * <p>
422 * The measure pass uses two classes to communicate dimensions. The
423 * {@link MeasureSpec} class is used by views to tell their parents how they
424 * want to be measured and positioned. The base LayoutParams class just
425 * describes how big the view wants to be for both width and height. For each
426 * dimension, it can specify one of:
427 * <ul>
428 * <li> an exact number
429 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
430 * (minus padding)
431 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
432 * enclose its content (plus padding).
433 * </ul>
434 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
435 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
436 * an X and Y value.
437 * </p>
438 *
439 * <p>
440 * MeasureSpecs are used to push requirements down the tree from parent to
441 * child. A MeasureSpec can be in one of three modes:
442 * <ul>
443 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
444 * of a child view. For example, a LinearLayout may call measure() on its child
445 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
446 * tall the child view wants to be given a width of 240 pixels.
447 * <li>EXACTLY: This is used by the parent to impose an exact size on the
448 * child. The child must use this size, and guarantee that all of its
449 * descendants will fit within this size.
450 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
451 * child. The child must guarantee that it and all of its descendants will fit
452 * within this size.
453 * </ul>
454 * </p>
455 *
456 * <p>
457 * To initiate a layout, call {@link #requestLayout}. This method is typically
458 * called by a view on itself when it believes that is can no longer fit within
459 * its current bounds.
460 * </p>
461 *
462 * <a name="Drawing"></a>
463 * <h3>Drawing</h3>
464 * <p>
465 * Drawing is handled by walking the tree and recording the drawing commands of
466 * any View that needs to update. After this, the drawing commands of the
467 * entire tree are issued to screen, clipped to the newly damaged area.
468 * </p>
469 *
470 * <p>
471 * The tree is largely recorded and drawn in order, with parents drawn before
472 * (i.e., behind) their children, with siblings drawn in the order they appear
473 * in the tree. If you set a background drawable for a View, then the View will
474 * draw it before calling back to its <code>onDraw()</code> method. The child
475 * drawing order can be overridden with
476 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
477 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
478 * </p>
479 *
480 * <p>
481 * To force a view to draw, call {@link #invalidate()}.
482 * </p>
483 *
484 * <a name="EventHandlingThreading"></a>
485 * <h3>Event Handling and Threading</h3>
486 * <p>
487 * The basic cycle of a view is as follows:
488 * <ol>
489 * <li>An event comes in and is dispatched to the appropriate view. The view
490 * handles the event and notifies any listeners.</li>
491 * <li>If in the course of processing the event, the view's bounds may need
492 * to be changed, the view will call {@link #requestLayout()}.</li>
493 * <li>Similarly, if in the course of processing the event the view's appearance
494 * may need to be changed, the view will call {@link #invalidate()}.</li>
495 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
496 * the framework will take care of measuring, laying out, and drawing the tree
497 * as appropriate.</li>
498 * </ol>
499 * </p>
500 *
501 * <p><em>Note: The entire view tree is single threaded. You must always be on
502 * the UI thread when calling any method on any view.</em>
503 * If you are doing work on other threads and want to update the state of a view
504 * from that thread, you should use a {@link Handler}.
505 * </p>
506 *
507 * <a name="FocusHandling"></a>
508 * <h3>Focus Handling</h3>
509 * <p>
510 * The framework will handle routine focus movement in response to user input.
511 * This includes changing the focus as views are removed or hidden, or as new
512 * views become available. Views indicate their willingness to take focus
513 * through the {@link #isFocusable} method. To change whether a view can take
514 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
515 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
516 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
517 * </p>
518 * <p>
519 * Focus movement is based on an algorithm which finds the nearest neighbor in a
520 * given direction. In rare cases, the default algorithm may not match the
521 * intended behavior of the developer. In these situations, you can provide
522 * explicit overrides by using these XML attributes in the layout file:
523 * <pre>
524 * nextFocusDown
525 * nextFocusLeft
526 * nextFocusRight
527 * nextFocusUp
528 * </pre>
529 * </p>
530 *
531 *
532 * <p>
533 * To get a particular view to take focus, call {@link #requestFocus()}.
534 * </p>
535 *
536 * <a name="TouchMode"></a>
537 * <h3>Touch Mode</h3>
538 * <p>
539 * When a user is navigating a user interface via directional keys such as a D-pad, it is
540 * necessary to give focus to actionable items such as buttons so the user can see
541 * what will take input.  If the device has touch capabilities, however, and the user
542 * begins interacting with the interface by touching it, it is no longer necessary to
543 * always highlight, or give focus to, a particular view.  This motivates a mode
544 * for interaction named 'touch mode'.
545 * </p>
546 * <p>
547 * For a touch capable device, once the user touches the screen, the device
548 * will enter touch mode.  From this point onward, only views for which
549 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
550 * Other views that are touchable, like buttons, will not take focus when touched; they will
551 * only fire the on click listeners.
552 * </p>
553 * <p>
554 * Any time a user hits a directional key, such as a D-pad direction, the view device will
555 * exit touch mode, and find a view to take focus, so that the user may resume interacting
556 * with the user interface without touching the screen again.
557 * </p>
558 * <p>
559 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
560 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
561 * </p>
562 *
563 * <a name="Scrolling"></a>
564 * <h3>Scrolling</h3>
565 * <p>
566 * The framework provides basic support for views that wish to internally
567 * scroll their content. This includes keeping track of the X and Y scroll
568 * offset as well as mechanisms for drawing scrollbars. See
569 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
570 * {@link #awakenScrollBars()} for more details.
571 * </p>
572 *
573 * <a name="Tags"></a>
574 * <h3>Tags</h3>
575 * <p>
576 * Unlike IDs, tags are not used to identify views. Tags are essentially an
577 * extra piece of information that can be associated with a view. They are most
578 * often used as a convenience to store data related to views in the views
579 * themselves rather than by putting them in a separate structure.
580 * </p>
581 * <p>
582 * Tags may be specified with character sequence values in layout XML as either
583 * a single tag using the {@link android.R.styleable#View_tag android:tag}
584 * attribute or multiple tags using the {@code <tag>} child element:
585 * <pre>
586 *     &ltView ...
587 *           android:tag="@string/mytag_value" /&gt;
588 *     &ltView ...&gt;
589 *         &lttag android:id="@+id/mytag"
590 *              android:value="@string/mytag_value" /&gt;
591 *     &lt/View>
592 * </pre>
593 * </p>
594 * <p>
595 * Tags may also be specified with arbitrary objects from code using
596 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
597 * </p>
598 *
599 * <a name="Themes"></a>
600 * <h3>Themes</h3>
601 * <p>
602 * By default, Views are created using the theme of the Context object supplied
603 * to their constructor; however, a different theme may be specified by using
604 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
605 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
606 * code.
607 * </p>
608 * <p>
609 * When the {@link android.R.styleable#View_theme android:theme} attribute is
610 * used in XML, the specified theme is applied on top of the inflation
611 * context's theme (see {@link LayoutInflater}) and used for the view itself as
612 * well as any child elements.
613 * </p>
614 * <p>
615 * In the following example, both views will be created using the Material dark
616 * color scheme; however, because an overlay theme is used which only defines a
617 * subset of attributes, the value of
618 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
619 * the inflation context's theme (e.g. the Activity theme) will be preserved.
620 * <pre>
621 *     &ltLinearLayout
622 *             ...
623 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
624 *         &ltView ...&gt;
625 *     &lt/LinearLayout&gt;
626 * </pre>
627 * </p>
628 *
629 * <a name="Properties"></a>
630 * <h3>Properties</h3>
631 * <p>
632 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
633 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
634 * available both in the {@link Property} form as well as in similarly-named setter/getter
635 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
636 * be used to set persistent state associated with these rendering-related properties on the view.
637 * The properties and methods can also be used in conjunction with
638 * {@link android.animation.Animator Animator}-based animations, described more in the
639 * <a href="#Animation">Animation</a> section.
640 * </p>
641 *
642 * <a name="Animation"></a>
643 * <h3>Animation</h3>
644 * <p>
645 * Starting with Android 3.0, the preferred way of animating views is to use the
646 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
647 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
648 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
649 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
650 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
651 * makes animating these View properties particularly easy and efficient.
652 * </p>
653 * <p>
654 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
655 * You can attach an {@link Animation} object to a view using
656 * {@link #setAnimation(Animation)} or
657 * {@link #startAnimation(Animation)}. The animation can alter the scale,
658 * rotation, translation and alpha of a view over time. If the animation is
659 * attached to a view that has children, the animation will affect the entire
660 * subtree rooted by that node. When an animation is started, the framework will
661 * take care of redrawing the appropriate views until the animation completes.
662 * </p>
663 *
664 * <a name="Security"></a>
665 * <h3>Security</h3>
666 * <p>
667 * Sometimes it is essential that an application be able to verify that an action
668 * is being performed with the full knowledge and consent of the user, such as
669 * granting a permission request, making a purchase or clicking on an advertisement.
670 * Unfortunately, a malicious application could try to spoof the user into
671 * performing these actions, unaware, by concealing the intended purpose of the view.
672 * As a remedy, the framework offers a touch filtering mechanism that can be used to
673 * improve the security of views that provide access to sensitive functionality.
674 * </p><p>
675 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
676 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
677 * will discard touches that are received whenever the view's window is obscured by
678 * another visible window.  As a result, the view will not receive touches whenever a
679 * toast, dialog or other window appears above the view's window.
680 * </p><p>
681 * For more fine-grained control over security, consider overriding the
682 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
683 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
684 * </p>
685 *
686 * @attr ref android.R.styleable#View_alpha
687 * @attr ref android.R.styleable#View_background
688 * @attr ref android.R.styleable#View_clickable
689 * @attr ref android.R.styleable#View_contentDescription
690 * @attr ref android.R.styleable#View_drawingCacheQuality
691 * @attr ref android.R.styleable#View_duplicateParentState
692 * @attr ref android.R.styleable#View_id
693 * @attr ref android.R.styleable#View_requiresFadingEdge
694 * @attr ref android.R.styleable#View_fadeScrollbars
695 * @attr ref android.R.styleable#View_fadingEdgeLength
696 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
697 * @attr ref android.R.styleable#View_fitsSystemWindows
698 * @attr ref android.R.styleable#View_isScrollContainer
699 * @attr ref android.R.styleable#View_focusable
700 * @attr ref android.R.styleable#View_focusableInTouchMode
701 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
702 * @attr ref android.R.styleable#View_keepScreenOn
703 * @attr ref android.R.styleable#View_layerType
704 * @attr ref android.R.styleable#View_layoutDirection
705 * @attr ref android.R.styleable#View_longClickable
706 * @attr ref android.R.styleable#View_minHeight
707 * @attr ref android.R.styleable#View_minWidth
708 * @attr ref android.R.styleable#View_nextFocusDown
709 * @attr ref android.R.styleable#View_nextFocusLeft
710 * @attr ref android.R.styleable#View_nextFocusRight
711 * @attr ref android.R.styleable#View_nextFocusUp
712 * @attr ref android.R.styleable#View_onClick
713 * @attr ref android.R.styleable#View_padding
714 * @attr ref android.R.styleable#View_paddingBottom
715 * @attr ref android.R.styleable#View_paddingLeft
716 * @attr ref android.R.styleable#View_paddingRight
717 * @attr ref android.R.styleable#View_paddingTop
718 * @attr ref android.R.styleable#View_paddingStart
719 * @attr ref android.R.styleable#View_paddingEnd
720 * @attr ref android.R.styleable#View_saveEnabled
721 * @attr ref android.R.styleable#View_rotation
722 * @attr ref android.R.styleable#View_rotationX
723 * @attr ref android.R.styleable#View_rotationY
724 * @attr ref android.R.styleable#View_scaleX
725 * @attr ref android.R.styleable#View_scaleY
726 * @attr ref android.R.styleable#View_scrollX
727 * @attr ref android.R.styleable#View_scrollY
728 * @attr ref android.R.styleable#View_scrollbarSize
729 * @attr ref android.R.styleable#View_scrollbarStyle
730 * @attr ref android.R.styleable#View_scrollbars
731 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
732 * @attr ref android.R.styleable#View_scrollbarFadeDuration
733 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
734 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
735 * @attr ref android.R.styleable#View_scrollbarThumbVertical
736 * @attr ref android.R.styleable#View_scrollbarTrackVertical
737 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
739 * @attr ref android.R.styleable#View_stateListAnimator
740 * @attr ref android.R.styleable#View_transitionName
741 * @attr ref android.R.styleable#View_soundEffectsEnabled
742 * @attr ref android.R.styleable#View_tag
743 * @attr ref android.R.styleable#View_textAlignment
744 * @attr ref android.R.styleable#View_textDirection
745 * @attr ref android.R.styleable#View_transformPivotX
746 * @attr ref android.R.styleable#View_transformPivotY
747 * @attr ref android.R.styleable#View_translationX
748 * @attr ref android.R.styleable#View_translationY
749 * @attr ref android.R.styleable#View_translationZ
750 * @attr ref android.R.styleable#View_visibility
751 * @attr ref android.R.styleable#View_theme
752 *
753 * @see android.view.ViewGroup
754 */
755@UiThread
756public class View implements Drawable.Callback, KeyEvent.Callback,
757        AccessibilityEventSource {
758    private static final boolean DBG = false;
759
760    /**
761     * The logging tag used by this class with android.util.Log.
762     */
763    protected static final String VIEW_LOG_TAG = "View";
764
765    /**
766     * When set to true, apps will draw debugging information about their layouts.
767     *
768     * @hide
769     */
770    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
771
772    /**
773     * When set to true, this view will save its attribute data.
774     *
775     * @hide
776     */
777    public static boolean mDebugViewAttributes = false;
778
779    /**
780     * Used to mark a View that has no ID.
781     */
782    public static final int NO_ID = -1;
783
784    /**
785     * Signals that compatibility booleans have been initialized according to
786     * target SDK versions.
787     */
788    private static boolean sCompatibilityDone = false;
789
790    /**
791     * Use the old (broken) way of building MeasureSpecs.
792     */
793    private static boolean sUseBrokenMakeMeasureSpec = false;
794
795    /**
796     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
797     */
798    static boolean sUseZeroUnspecifiedMeasureSpec = false;
799
800    /**
801     * Ignore any optimizations using the measure cache.
802     */
803    private static boolean sIgnoreMeasureCache = false;
804
805    /**
806     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
807     */
808    private static boolean sAlwaysRemeasureExactly = false;
809
810    /**
811     * Relax constraints around whether setLayoutParams() must be called after
812     * modifying the layout params.
813     */
814    private static boolean sLayoutParamsAlwaysChanged = false;
815
816    /**
817     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
818     * without throwing
819     */
820    static boolean sTextureViewIgnoresDrawableSetters = false;
821
822    /**
823     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
824     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
825     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
826     * check is implemented for backwards compatibility.
827     *
828     * {@hide}
829     */
830    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
831
832    /**
833     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
834     * calling setFlags.
835     */
836    private static final int NOT_FOCUSABLE = 0x00000000;
837
838    /**
839     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
840     * setFlags.
841     */
842    private static final int FOCUSABLE = 0x00000001;
843
844    /**
845     * Mask for use with setFlags indicating bits used for focus.
846     */
847    private static final int FOCUSABLE_MASK = 0x00000001;
848
849    /**
850     * This view will adjust its padding to fit sytem windows (e.g. status bar)
851     */
852    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
853
854    /** @hide */
855    @IntDef({VISIBLE, INVISIBLE, GONE})
856    @Retention(RetentionPolicy.SOURCE)
857    public @interface Visibility {}
858
859    /**
860     * This view is visible.
861     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
862     * android:visibility}.
863     */
864    public static final int VISIBLE = 0x00000000;
865
866    /**
867     * This view is invisible, but it still takes up space for layout purposes.
868     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
869     * android:visibility}.
870     */
871    public static final int INVISIBLE = 0x00000004;
872
873    /**
874     * This view is invisible, and it doesn't take any space for layout
875     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
876     * android:visibility}.
877     */
878    public static final int GONE = 0x00000008;
879
880    /**
881     * Mask for use with setFlags indicating bits used for visibility.
882     * {@hide}
883     */
884    static final int VISIBILITY_MASK = 0x0000000C;
885
886    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
887
888    /**
889     * This view is enabled. Interpretation varies by subclass.
890     * Use with ENABLED_MASK when calling setFlags.
891     * {@hide}
892     */
893    static final int ENABLED = 0x00000000;
894
895    /**
896     * This view is disabled. Interpretation varies by subclass.
897     * Use with ENABLED_MASK when calling setFlags.
898     * {@hide}
899     */
900    static final int DISABLED = 0x00000020;
901
902   /**
903    * Mask for use with setFlags indicating bits used for indicating whether
904    * this view is enabled
905    * {@hide}
906    */
907    static final int ENABLED_MASK = 0x00000020;
908
909    /**
910     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
911     * called and further optimizations will be performed. It is okay to have
912     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
913     * {@hide}
914     */
915    static final int WILL_NOT_DRAW = 0x00000080;
916
917    /**
918     * Mask for use with setFlags indicating bits used for indicating whether
919     * this view is will draw
920     * {@hide}
921     */
922    static final int DRAW_MASK = 0x00000080;
923
924    /**
925     * <p>This view doesn't show scrollbars.</p>
926     * {@hide}
927     */
928    static final int SCROLLBARS_NONE = 0x00000000;
929
930    /**
931     * <p>This view shows horizontal scrollbars.</p>
932     * {@hide}
933     */
934    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
935
936    /**
937     * <p>This view shows vertical scrollbars.</p>
938     * {@hide}
939     */
940    static final int SCROLLBARS_VERTICAL = 0x00000200;
941
942    /**
943     * <p>Mask for use with setFlags indicating bits used for indicating which
944     * scrollbars are enabled.</p>
945     * {@hide}
946     */
947    static final int SCROLLBARS_MASK = 0x00000300;
948
949    /**
950     * Indicates that the view should filter touches when its window is obscured.
951     * Refer to the class comments for more information about this security feature.
952     * {@hide}
953     */
954    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
955
956    /**
957     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
958     * that they are optional and should be skipped if the window has
959     * requested system UI flags that ignore those insets for layout.
960     */
961    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
962
963    /**
964     * <p>This view doesn't show fading edges.</p>
965     * {@hide}
966     */
967    static final int FADING_EDGE_NONE = 0x00000000;
968
969    /**
970     * <p>This view shows horizontal fading edges.</p>
971     * {@hide}
972     */
973    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
974
975    /**
976     * <p>This view shows vertical fading edges.</p>
977     * {@hide}
978     */
979    static final int FADING_EDGE_VERTICAL = 0x00002000;
980
981    /**
982     * <p>Mask for use with setFlags indicating bits used for indicating which
983     * fading edges are enabled.</p>
984     * {@hide}
985     */
986    static final int FADING_EDGE_MASK = 0x00003000;
987
988    /**
989     * <p>Indicates this view can be clicked. When clickable, a View reacts
990     * to clicks by notifying the OnClickListener.<p>
991     * {@hide}
992     */
993    static final int CLICKABLE = 0x00004000;
994
995    /**
996     * <p>Indicates this view is caching its drawing into a bitmap.</p>
997     * {@hide}
998     */
999    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1000
1001    /**
1002     * <p>Indicates that no icicle should be saved for this view.<p>
1003     * {@hide}
1004     */
1005    static final int SAVE_DISABLED = 0x000010000;
1006
1007    /**
1008     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1009     * property.</p>
1010     * {@hide}
1011     */
1012    static final int SAVE_DISABLED_MASK = 0x000010000;
1013
1014    /**
1015     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1016     * {@hide}
1017     */
1018    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1019
1020    /**
1021     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1022     * {@hide}
1023     */
1024    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1025
1026    /** @hide */
1027    @Retention(RetentionPolicy.SOURCE)
1028    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1029    public @interface DrawingCacheQuality {}
1030
1031    /**
1032     * <p>Enables low quality mode for the drawing cache.</p>
1033     */
1034    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1035
1036    /**
1037     * <p>Enables high quality mode for the drawing cache.</p>
1038     */
1039    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1040
1041    /**
1042     * <p>Enables automatic quality mode for the drawing cache.</p>
1043     */
1044    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1045
1046    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1047            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1048    };
1049
1050    /**
1051     * <p>Mask for use with setFlags indicating bits used for the cache
1052     * quality property.</p>
1053     * {@hide}
1054     */
1055    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1056
1057    /**
1058     * <p>
1059     * Indicates this view can be long clicked. When long clickable, a View
1060     * reacts to long clicks by notifying the OnLongClickListener or showing a
1061     * context menu.
1062     * </p>
1063     * {@hide}
1064     */
1065    static final int LONG_CLICKABLE = 0x00200000;
1066
1067    /**
1068     * <p>Indicates that this view gets its drawable states from its direct parent
1069     * and ignores its original internal states.</p>
1070     *
1071     * @hide
1072     */
1073    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1074
1075    /**
1076     * <p>
1077     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1078     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1079     * OnContextClickListener.
1080     * </p>
1081     * {@hide}
1082     */
1083    static final int CONTEXT_CLICKABLE = 0x00800000;
1084
1085
1086    /** @hide */
1087    @IntDef({
1088        SCROLLBARS_INSIDE_OVERLAY,
1089        SCROLLBARS_INSIDE_INSET,
1090        SCROLLBARS_OUTSIDE_OVERLAY,
1091        SCROLLBARS_OUTSIDE_INSET
1092    })
1093    @Retention(RetentionPolicy.SOURCE)
1094    public @interface ScrollBarStyle {}
1095
1096    /**
1097     * The scrollbar style to display the scrollbars inside the content area,
1098     * without increasing the padding. The scrollbars will be overlaid with
1099     * translucency on the view's content.
1100     */
1101    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1102
1103    /**
1104     * The scrollbar style to display the scrollbars inside the padded area,
1105     * increasing the padding of the view. The scrollbars will not overlap the
1106     * content area of the view.
1107     */
1108    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1109
1110    /**
1111     * The scrollbar style to display the scrollbars at the edge of the view,
1112     * without increasing the padding. The scrollbars will be overlaid with
1113     * translucency.
1114     */
1115    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1116
1117    /**
1118     * The scrollbar style to display the scrollbars at the edge of the view,
1119     * increasing the padding of the view. The scrollbars will only overlap the
1120     * background, if any.
1121     */
1122    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1123
1124    /**
1125     * Mask to check if the scrollbar style is overlay or inset.
1126     * {@hide}
1127     */
1128    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1129
1130    /**
1131     * Mask to check if the scrollbar style is inside or outside.
1132     * {@hide}
1133     */
1134    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1135
1136    /**
1137     * Mask for scrollbar style.
1138     * {@hide}
1139     */
1140    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1141
1142    /**
1143     * View flag indicating that the screen should remain on while the
1144     * window containing this view is visible to the user.  This effectively
1145     * takes care of automatically setting the WindowManager's
1146     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1147     */
1148    public static final int KEEP_SCREEN_ON = 0x04000000;
1149
1150    /**
1151     * View flag indicating whether this view should have sound effects enabled
1152     * for events such as clicking and touching.
1153     */
1154    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1155
1156    /**
1157     * View flag indicating whether this view should have haptic feedback
1158     * enabled for events such as long presses.
1159     */
1160    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1161
1162    /**
1163     * <p>Indicates that the view hierarchy should stop saving state when
1164     * it reaches this view.  If state saving is initiated immediately at
1165     * the view, it will be allowed.
1166     * {@hide}
1167     */
1168    static final int PARENT_SAVE_DISABLED = 0x20000000;
1169
1170    /**
1171     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1172     * {@hide}
1173     */
1174    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1175
1176    /** @hide */
1177    @IntDef(flag = true,
1178            value = {
1179                FOCUSABLES_ALL,
1180                FOCUSABLES_TOUCH_MODE
1181            })
1182    @Retention(RetentionPolicy.SOURCE)
1183    public @interface FocusableMode {}
1184
1185    /**
1186     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1187     * should add all focusable Views regardless if they are focusable in touch mode.
1188     */
1189    public static final int FOCUSABLES_ALL = 0x00000000;
1190
1191    /**
1192     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1193     * should add only Views focusable in touch mode.
1194     */
1195    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1196
1197    /** @hide */
1198    @IntDef({
1199            FOCUS_BACKWARD,
1200            FOCUS_FORWARD,
1201            FOCUS_LEFT,
1202            FOCUS_UP,
1203            FOCUS_RIGHT,
1204            FOCUS_DOWN
1205    })
1206    @Retention(RetentionPolicy.SOURCE)
1207    public @interface FocusDirection {}
1208
1209    /** @hide */
1210    @IntDef({
1211            FOCUS_LEFT,
1212            FOCUS_UP,
1213            FOCUS_RIGHT,
1214            FOCUS_DOWN
1215    })
1216    @Retention(RetentionPolicy.SOURCE)
1217    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1218
1219    /**
1220     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1221     * item.
1222     */
1223    public static final int FOCUS_BACKWARD = 0x00000001;
1224
1225    /**
1226     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1227     * item.
1228     */
1229    public static final int FOCUS_FORWARD = 0x00000002;
1230
1231    /**
1232     * Use with {@link #focusSearch(int)}. Move focus to the left.
1233     */
1234    public static final int FOCUS_LEFT = 0x00000011;
1235
1236    /**
1237     * Use with {@link #focusSearch(int)}. Move focus up.
1238     */
1239    public static final int FOCUS_UP = 0x00000021;
1240
1241    /**
1242     * Use with {@link #focusSearch(int)}. Move focus to the right.
1243     */
1244    public static final int FOCUS_RIGHT = 0x00000042;
1245
1246    /**
1247     * Use with {@link #focusSearch(int)}. Move focus down.
1248     */
1249    public static final int FOCUS_DOWN = 0x00000082;
1250
1251    /**
1252     * Bits of {@link #getMeasuredWidthAndState()} and
1253     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1254     */
1255    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1256
1257    /**
1258     * Bits of {@link #getMeasuredWidthAndState()} and
1259     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1260     */
1261    public static final int MEASURED_STATE_MASK = 0xff000000;
1262
1263    /**
1264     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1265     * for functions that combine both width and height into a single int,
1266     * such as {@link #getMeasuredState()} and the childState argument of
1267     * {@link #resolveSizeAndState(int, int, int)}.
1268     */
1269    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1270
1271    /**
1272     * Bit of {@link #getMeasuredWidthAndState()} and
1273     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1274     * is smaller that the space the view would like to have.
1275     */
1276    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1277
1278    /**
1279     * Base View state sets
1280     */
1281    // Singles
1282    /**
1283     * Indicates the view has no states set. States are used with
1284     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1285     * view depending on its state.
1286     *
1287     * @see android.graphics.drawable.Drawable
1288     * @see #getDrawableState()
1289     */
1290    protected static final int[] EMPTY_STATE_SET;
1291    /**
1292     * Indicates the view is enabled. States are used with
1293     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1294     * view depending on its state.
1295     *
1296     * @see android.graphics.drawable.Drawable
1297     * @see #getDrawableState()
1298     */
1299    protected static final int[] ENABLED_STATE_SET;
1300    /**
1301     * Indicates the view is focused. States are used with
1302     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1303     * view depending on its state.
1304     *
1305     * @see android.graphics.drawable.Drawable
1306     * @see #getDrawableState()
1307     */
1308    protected static final int[] FOCUSED_STATE_SET;
1309    /**
1310     * Indicates the view is selected. States are used with
1311     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1312     * view depending on its state.
1313     *
1314     * @see android.graphics.drawable.Drawable
1315     * @see #getDrawableState()
1316     */
1317    protected static final int[] SELECTED_STATE_SET;
1318    /**
1319     * Indicates the view is pressed. States are used with
1320     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1321     * view depending on its state.
1322     *
1323     * @see android.graphics.drawable.Drawable
1324     * @see #getDrawableState()
1325     */
1326    protected static final int[] PRESSED_STATE_SET;
1327    /**
1328     * Indicates the view's window has focus. States are used with
1329     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1330     * view depending on its state.
1331     *
1332     * @see android.graphics.drawable.Drawable
1333     * @see #getDrawableState()
1334     */
1335    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1336    // Doubles
1337    /**
1338     * Indicates the view is enabled and has the focus.
1339     *
1340     * @see #ENABLED_STATE_SET
1341     * @see #FOCUSED_STATE_SET
1342     */
1343    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1344    /**
1345     * Indicates the view is enabled and selected.
1346     *
1347     * @see #ENABLED_STATE_SET
1348     * @see #SELECTED_STATE_SET
1349     */
1350    protected static final int[] ENABLED_SELECTED_STATE_SET;
1351    /**
1352     * Indicates the view is enabled and that its window has focus.
1353     *
1354     * @see #ENABLED_STATE_SET
1355     * @see #WINDOW_FOCUSED_STATE_SET
1356     */
1357    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1358    /**
1359     * Indicates the view is focused and selected.
1360     *
1361     * @see #FOCUSED_STATE_SET
1362     * @see #SELECTED_STATE_SET
1363     */
1364    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1365    /**
1366     * Indicates the view has the focus and that its window has the focus.
1367     *
1368     * @see #FOCUSED_STATE_SET
1369     * @see #WINDOW_FOCUSED_STATE_SET
1370     */
1371    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1372    /**
1373     * Indicates the view is selected and that its window has the focus.
1374     *
1375     * @see #SELECTED_STATE_SET
1376     * @see #WINDOW_FOCUSED_STATE_SET
1377     */
1378    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1379    // Triples
1380    /**
1381     * Indicates the view is enabled, focused and selected.
1382     *
1383     * @see #ENABLED_STATE_SET
1384     * @see #FOCUSED_STATE_SET
1385     * @see #SELECTED_STATE_SET
1386     */
1387    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1388    /**
1389     * Indicates the view is enabled, focused and its window has the focus.
1390     *
1391     * @see #ENABLED_STATE_SET
1392     * @see #FOCUSED_STATE_SET
1393     * @see #WINDOW_FOCUSED_STATE_SET
1394     */
1395    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1396    /**
1397     * Indicates the view is enabled, selected and its window has the focus.
1398     *
1399     * @see #ENABLED_STATE_SET
1400     * @see #SELECTED_STATE_SET
1401     * @see #WINDOW_FOCUSED_STATE_SET
1402     */
1403    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1404    /**
1405     * Indicates the view is focused, selected and its window has the focus.
1406     *
1407     * @see #FOCUSED_STATE_SET
1408     * @see #SELECTED_STATE_SET
1409     * @see #WINDOW_FOCUSED_STATE_SET
1410     */
1411    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1412    /**
1413     * Indicates the view is enabled, focused, selected and its window
1414     * has the focus.
1415     *
1416     * @see #ENABLED_STATE_SET
1417     * @see #FOCUSED_STATE_SET
1418     * @see #SELECTED_STATE_SET
1419     * @see #WINDOW_FOCUSED_STATE_SET
1420     */
1421    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1422    /**
1423     * Indicates the view is pressed and its window has the focus.
1424     *
1425     * @see #PRESSED_STATE_SET
1426     * @see #WINDOW_FOCUSED_STATE_SET
1427     */
1428    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1429    /**
1430     * Indicates the view is pressed and selected.
1431     *
1432     * @see #PRESSED_STATE_SET
1433     * @see #SELECTED_STATE_SET
1434     */
1435    protected static final int[] PRESSED_SELECTED_STATE_SET;
1436    /**
1437     * Indicates the view is pressed, selected and its window has the focus.
1438     *
1439     * @see #PRESSED_STATE_SET
1440     * @see #SELECTED_STATE_SET
1441     * @see #WINDOW_FOCUSED_STATE_SET
1442     */
1443    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1444    /**
1445     * Indicates the view is pressed and focused.
1446     *
1447     * @see #PRESSED_STATE_SET
1448     * @see #FOCUSED_STATE_SET
1449     */
1450    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1451    /**
1452     * Indicates the view is pressed, focused and its window has the focus.
1453     *
1454     * @see #PRESSED_STATE_SET
1455     * @see #FOCUSED_STATE_SET
1456     * @see #WINDOW_FOCUSED_STATE_SET
1457     */
1458    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1459    /**
1460     * Indicates the view is pressed, focused and selected.
1461     *
1462     * @see #PRESSED_STATE_SET
1463     * @see #SELECTED_STATE_SET
1464     * @see #FOCUSED_STATE_SET
1465     */
1466    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1467    /**
1468     * Indicates the view is pressed, focused, selected and its window has the focus.
1469     *
1470     * @see #PRESSED_STATE_SET
1471     * @see #FOCUSED_STATE_SET
1472     * @see #SELECTED_STATE_SET
1473     * @see #WINDOW_FOCUSED_STATE_SET
1474     */
1475    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1476    /**
1477     * Indicates the view is pressed and enabled.
1478     *
1479     * @see #PRESSED_STATE_SET
1480     * @see #ENABLED_STATE_SET
1481     */
1482    protected static final int[] PRESSED_ENABLED_STATE_SET;
1483    /**
1484     * Indicates the view is pressed, enabled and its window has the focus.
1485     *
1486     * @see #PRESSED_STATE_SET
1487     * @see #ENABLED_STATE_SET
1488     * @see #WINDOW_FOCUSED_STATE_SET
1489     */
1490    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1491    /**
1492     * Indicates the view is pressed, enabled and selected.
1493     *
1494     * @see #PRESSED_STATE_SET
1495     * @see #ENABLED_STATE_SET
1496     * @see #SELECTED_STATE_SET
1497     */
1498    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1499    /**
1500     * Indicates the view is pressed, enabled, selected and its window has the
1501     * focus.
1502     *
1503     * @see #PRESSED_STATE_SET
1504     * @see #ENABLED_STATE_SET
1505     * @see #SELECTED_STATE_SET
1506     * @see #WINDOW_FOCUSED_STATE_SET
1507     */
1508    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1509    /**
1510     * Indicates the view is pressed, enabled and focused.
1511     *
1512     * @see #PRESSED_STATE_SET
1513     * @see #ENABLED_STATE_SET
1514     * @see #FOCUSED_STATE_SET
1515     */
1516    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1517    /**
1518     * Indicates the view is pressed, enabled, focused and its window has the
1519     * focus.
1520     *
1521     * @see #PRESSED_STATE_SET
1522     * @see #ENABLED_STATE_SET
1523     * @see #FOCUSED_STATE_SET
1524     * @see #WINDOW_FOCUSED_STATE_SET
1525     */
1526    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1527    /**
1528     * Indicates the view is pressed, enabled, focused and selected.
1529     *
1530     * @see #PRESSED_STATE_SET
1531     * @see #ENABLED_STATE_SET
1532     * @see #SELECTED_STATE_SET
1533     * @see #FOCUSED_STATE_SET
1534     */
1535    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1536    /**
1537     * Indicates the view is pressed, enabled, focused, selected and its window
1538     * has the focus.
1539     *
1540     * @see #PRESSED_STATE_SET
1541     * @see #ENABLED_STATE_SET
1542     * @see #SELECTED_STATE_SET
1543     * @see #FOCUSED_STATE_SET
1544     * @see #WINDOW_FOCUSED_STATE_SET
1545     */
1546    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1547
1548    static {
1549        EMPTY_STATE_SET = StateSet.get(0);
1550
1551        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1552
1553        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1554        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1555                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1556
1557        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1558        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1559                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1560        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1561                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1562        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1563                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1564                        | StateSet.VIEW_STATE_FOCUSED);
1565
1566        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1567        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1568                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1569        ENABLED_SELECTED_STATE_SET = StateSet.get(
1570                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1571        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1572                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1573                        | StateSet.VIEW_STATE_ENABLED);
1574        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1575                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1576        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1577                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1578                        | StateSet.VIEW_STATE_ENABLED);
1579        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1580                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1581                        | StateSet.VIEW_STATE_ENABLED);
1582        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1583                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1584                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1585
1586        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1587        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1588                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1589        PRESSED_SELECTED_STATE_SET = StateSet.get(
1590                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1591        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1592                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1593                        | StateSet.VIEW_STATE_PRESSED);
1594        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1595                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1596        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1597                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1598                        | StateSet.VIEW_STATE_PRESSED);
1599        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1600                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1601                        | StateSet.VIEW_STATE_PRESSED);
1602        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1603                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1604                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1605        PRESSED_ENABLED_STATE_SET = StateSet.get(
1606                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1607        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1608                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1609                        | StateSet.VIEW_STATE_PRESSED);
1610        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1611                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1612                        | StateSet.VIEW_STATE_PRESSED);
1613        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1614                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1615                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1616        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1617                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1618                        | StateSet.VIEW_STATE_PRESSED);
1619        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1620                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1621                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1622        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1623                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1624                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1625        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1626                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1627                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1628                        | StateSet.VIEW_STATE_PRESSED);
1629    }
1630
1631    /**
1632     * Accessibility event types that are dispatched for text population.
1633     */
1634    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1635            AccessibilityEvent.TYPE_VIEW_CLICKED
1636            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1637            | AccessibilityEvent.TYPE_VIEW_SELECTED
1638            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1639            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1640            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1641            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1642            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1643            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1644            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1645            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1646
1647    /**
1648     * Temporary Rect currently for use in setBackground().  This will probably
1649     * be extended in the future to hold our own class with more than just
1650     * a Rect. :)
1651     */
1652    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1653
1654    /**
1655     * Map used to store views' tags.
1656     */
1657    private SparseArray<Object> mKeyedTags;
1658
1659    /**
1660     * The next available accessibility id.
1661     */
1662    private static int sNextAccessibilityViewId;
1663
1664    /**
1665     * The animation currently associated with this view.
1666     * @hide
1667     */
1668    protected Animation mCurrentAnimation = null;
1669
1670    /**
1671     * Width as measured during measure pass.
1672     * {@hide}
1673     */
1674    @ViewDebug.ExportedProperty(category = "measurement")
1675    int mMeasuredWidth;
1676
1677    /**
1678     * Height as measured during measure pass.
1679     * {@hide}
1680     */
1681    @ViewDebug.ExportedProperty(category = "measurement")
1682    int mMeasuredHeight;
1683
1684    /**
1685     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1686     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1687     * its display list. This flag, used only when hw accelerated, allows us to clear the
1688     * flag while retaining this information until it's needed (at getDisplayList() time and
1689     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1690     *
1691     * {@hide}
1692     */
1693    boolean mRecreateDisplayList = false;
1694
1695    /**
1696     * The view's identifier.
1697     * {@hide}
1698     *
1699     * @see #setId(int)
1700     * @see #getId()
1701     */
1702    @IdRes
1703    @ViewDebug.ExportedProperty(resolveId = true)
1704    int mID = NO_ID;
1705
1706    /**
1707     * The stable ID of this view for accessibility purposes.
1708     */
1709    int mAccessibilityViewId = NO_ID;
1710
1711    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1712
1713    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1714
1715    /**
1716     * The view's tag.
1717     * {@hide}
1718     *
1719     * @see #setTag(Object)
1720     * @see #getTag()
1721     */
1722    protected Object mTag = null;
1723
1724    // for mPrivateFlags:
1725    /** {@hide} */
1726    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1727    /** {@hide} */
1728    static final int PFLAG_FOCUSED                     = 0x00000002;
1729    /** {@hide} */
1730    static final int PFLAG_SELECTED                    = 0x00000004;
1731    /** {@hide} */
1732    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1733    /** {@hide} */
1734    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1735    /** {@hide} */
1736    static final int PFLAG_DRAWN                       = 0x00000020;
1737    /**
1738     * When this flag is set, this view is running an animation on behalf of its
1739     * children and should therefore not cancel invalidate requests, even if they
1740     * lie outside of this view's bounds.
1741     *
1742     * {@hide}
1743     */
1744    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1745    /** {@hide} */
1746    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1747    /** {@hide} */
1748    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1749    /** {@hide} */
1750    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1751    /** {@hide} */
1752    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1753    /** {@hide} */
1754    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1755    /** {@hide} */
1756    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1757
1758    private static final int PFLAG_PRESSED             = 0x00004000;
1759
1760    /** {@hide} */
1761    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1762    /**
1763     * Flag used to indicate that this view should be drawn once more (and only once
1764     * more) after its animation has completed.
1765     * {@hide}
1766     */
1767    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1768
1769    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1770
1771    /**
1772     * Indicates that the View returned true when onSetAlpha() was called and that
1773     * the alpha must be restored.
1774     * {@hide}
1775     */
1776    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1777
1778    /**
1779     * Set by {@link #setScrollContainer(boolean)}.
1780     */
1781    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1782
1783    /**
1784     * Set by {@link #setScrollContainer(boolean)}.
1785     */
1786    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1787
1788    /**
1789     * View flag indicating whether this view was invalidated (fully or partially.)
1790     *
1791     * @hide
1792     */
1793    static final int PFLAG_DIRTY                       = 0x00200000;
1794
1795    /**
1796     * View flag indicating whether this view was invalidated by an opaque
1797     * invalidate request.
1798     *
1799     * @hide
1800     */
1801    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1802
1803    /**
1804     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1805     *
1806     * @hide
1807     */
1808    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1809
1810    /**
1811     * Indicates whether the background is opaque.
1812     *
1813     * @hide
1814     */
1815    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1816
1817    /**
1818     * Indicates whether the scrollbars are opaque.
1819     *
1820     * @hide
1821     */
1822    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1823
1824    /**
1825     * Indicates whether the view is opaque.
1826     *
1827     * @hide
1828     */
1829    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1830
1831    /**
1832     * Indicates a prepressed state;
1833     * the short time between ACTION_DOWN and recognizing
1834     * a 'real' press. Prepressed is used to recognize quick taps
1835     * even when they are shorter than ViewConfiguration.getTapTimeout().
1836     *
1837     * @hide
1838     */
1839    private static final int PFLAG_PREPRESSED          = 0x02000000;
1840
1841    /**
1842     * Indicates whether the view is temporarily detached.
1843     *
1844     * @hide
1845     */
1846    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1847
1848    /**
1849     * Indicates that we should awaken scroll bars once attached
1850     *
1851     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1852     * during window attachment and it is no longer needed. Feel free to repurpose it.
1853     *
1854     * @hide
1855     */
1856    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1857
1858    /**
1859     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1860     * @hide
1861     */
1862    private static final int PFLAG_HOVERED             = 0x10000000;
1863
1864    /**
1865     * no longer needed, should be reused
1866     */
1867    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1868
1869    /** {@hide} */
1870    static final int PFLAG_ACTIVATED                   = 0x40000000;
1871
1872    /**
1873     * Indicates that this view was specifically invalidated, not just dirtied because some
1874     * child view was invalidated. The flag is used to determine when we need to recreate
1875     * a view's display list (as opposed to just returning a reference to its existing
1876     * display list).
1877     *
1878     * @hide
1879     */
1880    static final int PFLAG_INVALIDATED                 = 0x80000000;
1881
1882    /**
1883     * Masks for mPrivateFlags2, as generated by dumpFlags():
1884     *
1885     * |-------|-------|-------|-------|
1886     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1887     *                                1  PFLAG2_DRAG_HOVERED
1888     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1889     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1890     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1891     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1892     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1893     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1894     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1895     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1896     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1897     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1898     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1899     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1900     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1901     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1902     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1903     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1904     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1905     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1906     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1907     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1908     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1909     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1910     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1911     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1912     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1913     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1914     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1915     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1916     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1917     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1918     *    1                              PFLAG2_PADDING_RESOLVED
1919     *   1                               PFLAG2_DRAWABLE_RESOLVED
1920     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1921     * |-------|-------|-------|-------|
1922     */
1923
1924    /**
1925     * Indicates that this view has reported that it can accept the current drag's content.
1926     * Cleared when the drag operation concludes.
1927     * @hide
1928     */
1929    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1930
1931    /**
1932     * Indicates that this view is currently directly under the drag location in a
1933     * drag-and-drop operation involving content that it can accept.  Cleared when
1934     * the drag exits the view, or when the drag operation concludes.
1935     * @hide
1936     */
1937    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1938
1939    /** @hide */
1940    @IntDef({
1941        LAYOUT_DIRECTION_LTR,
1942        LAYOUT_DIRECTION_RTL,
1943        LAYOUT_DIRECTION_INHERIT,
1944        LAYOUT_DIRECTION_LOCALE
1945    })
1946    @Retention(RetentionPolicy.SOURCE)
1947    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1948    public @interface LayoutDir {}
1949
1950    /** @hide */
1951    @IntDef({
1952        LAYOUT_DIRECTION_LTR,
1953        LAYOUT_DIRECTION_RTL
1954    })
1955    @Retention(RetentionPolicy.SOURCE)
1956    public @interface ResolvedLayoutDir {}
1957
1958    /**
1959     * A flag to indicate that the layout direction of this view has not been defined yet.
1960     * @hide
1961     */
1962    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
1963
1964    /**
1965     * Horizontal layout direction of this view is from Left to Right.
1966     * Use with {@link #setLayoutDirection}.
1967     */
1968    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1969
1970    /**
1971     * Horizontal layout direction of this view is from Right to Left.
1972     * Use with {@link #setLayoutDirection}.
1973     */
1974    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1975
1976    /**
1977     * Horizontal layout direction of this view is inherited from its parent.
1978     * Use with {@link #setLayoutDirection}.
1979     */
1980    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1981
1982    /**
1983     * Horizontal layout direction of this view is from deduced from the default language
1984     * script for the locale. Use with {@link #setLayoutDirection}.
1985     */
1986    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1987
1988    /**
1989     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1990     * @hide
1991     */
1992    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1993
1994    /**
1995     * Mask for use with private flags indicating bits used for horizontal layout direction.
1996     * @hide
1997     */
1998    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1999
2000    /**
2001     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2002     * right-to-left direction.
2003     * @hide
2004     */
2005    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2006
2007    /**
2008     * Indicates whether the view horizontal layout direction has been resolved.
2009     * @hide
2010     */
2011    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2012
2013    /**
2014     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2015     * @hide
2016     */
2017    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2018            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2019
2020    /*
2021     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2022     * flag value.
2023     * @hide
2024     */
2025    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2026            LAYOUT_DIRECTION_LTR,
2027            LAYOUT_DIRECTION_RTL,
2028            LAYOUT_DIRECTION_INHERIT,
2029            LAYOUT_DIRECTION_LOCALE
2030    };
2031
2032    /**
2033     * Default horizontal layout direction.
2034     */
2035    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2036
2037    /**
2038     * Default horizontal layout direction.
2039     * @hide
2040     */
2041    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2042
2043    /**
2044     * Text direction is inherited through {@link ViewGroup}
2045     */
2046    public static final int TEXT_DIRECTION_INHERIT = 0;
2047
2048    /**
2049     * Text direction is using "first strong algorithm". The first strong directional character
2050     * determines the paragraph direction. If there is no strong directional character, the
2051     * paragraph direction is the view's resolved layout direction.
2052     */
2053    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2054
2055    /**
2056     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2057     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2058     * If there are neither, the paragraph direction is the view's resolved layout direction.
2059     */
2060    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2061
2062    /**
2063     * Text direction is forced to LTR.
2064     */
2065    public static final int TEXT_DIRECTION_LTR = 3;
2066
2067    /**
2068     * Text direction is forced to RTL.
2069     */
2070    public static final int TEXT_DIRECTION_RTL = 4;
2071
2072    /**
2073     * Text direction is coming from the system Locale.
2074     */
2075    public static final int TEXT_DIRECTION_LOCALE = 5;
2076
2077    /**
2078     * Text direction is using "first strong algorithm". The first strong directional character
2079     * determines the paragraph direction. If there is no strong directional character, the
2080     * paragraph direction is LTR.
2081     */
2082    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2083
2084    /**
2085     * Text direction is using "first strong algorithm". The first strong directional character
2086     * determines the paragraph direction. If there is no strong directional character, the
2087     * paragraph direction is RTL.
2088     */
2089    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2090
2091    /**
2092     * Default text direction is inherited
2093     */
2094    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2095
2096    /**
2097     * Default resolved text direction
2098     * @hide
2099     */
2100    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2101
2102    /**
2103     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2104     * @hide
2105     */
2106    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2107
2108    /**
2109     * Mask for use with private flags indicating bits used for text direction.
2110     * @hide
2111     */
2112    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2113            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2114
2115    /**
2116     * Array of text direction flags for mapping attribute "textDirection" to correct
2117     * flag value.
2118     * @hide
2119     */
2120    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2121            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2122            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2123            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2124            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2125            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2126            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2127            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2128            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2129    };
2130
2131    /**
2132     * Indicates whether the view text direction has been resolved.
2133     * @hide
2134     */
2135    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2136            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2137
2138    /**
2139     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2140     * @hide
2141     */
2142    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2143
2144    /**
2145     * Mask for use with private flags indicating bits used for resolved text direction.
2146     * @hide
2147     */
2148    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2149            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2150
2151    /**
2152     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2153     * @hide
2154     */
2155    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2156            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2157
2158    /** @hide */
2159    @IntDef({
2160        TEXT_ALIGNMENT_INHERIT,
2161        TEXT_ALIGNMENT_GRAVITY,
2162        TEXT_ALIGNMENT_CENTER,
2163        TEXT_ALIGNMENT_TEXT_START,
2164        TEXT_ALIGNMENT_TEXT_END,
2165        TEXT_ALIGNMENT_VIEW_START,
2166        TEXT_ALIGNMENT_VIEW_END
2167    })
2168    @Retention(RetentionPolicy.SOURCE)
2169    public @interface TextAlignment {}
2170
2171    /**
2172     * Default text alignment. The text alignment of this View is inherited from its parent.
2173     * Use with {@link #setTextAlignment(int)}
2174     */
2175    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2176
2177    /**
2178     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2179     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2180     *
2181     * Use with {@link #setTextAlignment(int)}
2182     */
2183    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2184
2185    /**
2186     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2187     *
2188     * Use with {@link #setTextAlignment(int)}
2189     */
2190    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2191
2192    /**
2193     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2194     *
2195     * Use with {@link #setTextAlignment(int)}
2196     */
2197    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2198
2199    /**
2200     * Center the paragraph, e.g. ALIGN_CENTER.
2201     *
2202     * Use with {@link #setTextAlignment(int)}
2203     */
2204    public static final int TEXT_ALIGNMENT_CENTER = 4;
2205
2206    /**
2207     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2208     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2209     *
2210     * Use with {@link #setTextAlignment(int)}
2211     */
2212    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2213
2214    /**
2215     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2216     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2217     *
2218     * Use with {@link #setTextAlignment(int)}
2219     */
2220    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2221
2222    /**
2223     * Default text alignment is inherited
2224     */
2225    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2226
2227    /**
2228     * Default resolved text alignment
2229     * @hide
2230     */
2231    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2232
2233    /**
2234      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2235      * @hide
2236      */
2237    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2238
2239    /**
2240      * Mask for use with private flags indicating bits used for text alignment.
2241      * @hide
2242      */
2243    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2244
2245    /**
2246     * Array of text direction flags for mapping attribute "textAlignment" to correct
2247     * flag value.
2248     * @hide
2249     */
2250    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2251            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2252            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2253            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2254            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2255            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2256            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2257            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2258    };
2259
2260    /**
2261     * Indicates whether the view text alignment has been resolved.
2262     * @hide
2263     */
2264    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2265
2266    /**
2267     * Bit shift to get the resolved text alignment.
2268     * @hide
2269     */
2270    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2271
2272    /**
2273     * Mask for use with private flags indicating bits used for text alignment.
2274     * @hide
2275     */
2276    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2277            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2278
2279    /**
2280     * Indicates whether if the view text alignment has been resolved to gravity
2281     */
2282    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2283            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2284
2285    // Accessiblity constants for mPrivateFlags2
2286
2287    /**
2288     * Shift for the bits in {@link #mPrivateFlags2} related to the
2289     * "importantForAccessibility" attribute.
2290     */
2291    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2292
2293    /**
2294     * Automatically determine whether a view is important for accessibility.
2295     */
2296    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2297
2298    /**
2299     * The view is important for accessibility.
2300     */
2301    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2302
2303    /**
2304     * The view is not important for accessibility.
2305     */
2306    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2307
2308    /**
2309     * The view is not important for accessibility, nor are any of its
2310     * descendant views.
2311     */
2312    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2313
2314    /**
2315     * The default whether the view is important for accessibility.
2316     */
2317    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2318
2319    /**
2320     * Mask for obtainig the bits which specify how to determine
2321     * whether a view is important for accessibility.
2322     */
2323    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2324        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2325        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2326        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2327
2328    /**
2329     * Shift for the bits in {@link #mPrivateFlags2} related to the
2330     * "accessibilityLiveRegion" attribute.
2331     */
2332    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2333
2334    /**
2335     * Live region mode specifying that accessibility services should not
2336     * automatically announce changes to this view. This is the default live
2337     * region mode for most views.
2338     * <p>
2339     * Use with {@link #setAccessibilityLiveRegion(int)}.
2340     */
2341    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2342
2343    /**
2344     * Live region mode specifying that accessibility services should announce
2345     * changes to this view.
2346     * <p>
2347     * Use with {@link #setAccessibilityLiveRegion(int)}.
2348     */
2349    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2350
2351    /**
2352     * Live region mode specifying that accessibility services should interrupt
2353     * ongoing speech to immediately announce changes to this view.
2354     * <p>
2355     * Use with {@link #setAccessibilityLiveRegion(int)}.
2356     */
2357    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2358
2359    /**
2360     * The default whether the view is important for accessibility.
2361     */
2362    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2363
2364    /**
2365     * Mask for obtaining the bits which specify a view's accessibility live
2366     * region mode.
2367     */
2368    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2369            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2370            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2371
2372    /**
2373     * Flag indicating whether a view has accessibility focus.
2374     */
2375    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2376
2377    /**
2378     * Flag whether the accessibility state of the subtree rooted at this view changed.
2379     */
2380    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2381
2382    /**
2383     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2384     * is used to check whether later changes to the view's transform should invalidate the
2385     * view to force the quickReject test to run again.
2386     */
2387    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2388
2389    /**
2390     * Flag indicating that start/end padding has been resolved into left/right padding
2391     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2392     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2393     * during measurement. In some special cases this is required such as when an adapter-based
2394     * view measures prospective children without attaching them to a window.
2395     */
2396    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2397
2398    /**
2399     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2400     */
2401    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2402
2403    /**
2404     * Indicates that the view is tracking some sort of transient state
2405     * that the app should not need to be aware of, but that the framework
2406     * should take special care to preserve.
2407     */
2408    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2409
2410    /**
2411     * Group of bits indicating that RTL properties resolution is done.
2412     */
2413    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2414            PFLAG2_TEXT_DIRECTION_RESOLVED |
2415            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2416            PFLAG2_PADDING_RESOLVED |
2417            PFLAG2_DRAWABLE_RESOLVED;
2418
2419    // There are a couple of flags left in mPrivateFlags2
2420
2421    /* End of masks for mPrivateFlags2 */
2422
2423    /**
2424     * Masks for mPrivateFlags3, as generated by dumpFlags():
2425     *
2426     * |-------|-------|-------|-------|
2427     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2428     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2429     *                               1   PFLAG3_IS_LAID_OUT
2430     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2431     *                             1     PFLAG3_CALLED_SUPER
2432     *                            1      PFLAG3_APPLYING_INSETS
2433     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2434     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2435     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2436     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2437     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2438     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2439     *                     1             PFLAG3_SCROLL_INDICATOR_START
2440     *                    1              PFLAG3_SCROLL_INDICATOR_END
2441     *                   1               PFLAG3_ASSIST_BLOCKED
2442     *                  1                PFLAG3_POINTER_ICON_NULL
2443     *                 1                 PFLAG3_POINTER_ICON_VALUE_START
2444     *           11111111                PFLAG3_POINTER_ICON_MASK
2445     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2446     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2447     *        1                          PFLAG3_TEMPORARY_DETACH
2448     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2449     * |-------|-------|-------|-------|
2450     */
2451
2452    /**
2453     * Flag indicating that view has a transform animation set on it. This is used to track whether
2454     * an animation is cleared between successive frames, in order to tell the associated
2455     * DisplayList to clear its animation matrix.
2456     */
2457    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2458
2459    /**
2460     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2461     * animation is cleared between successive frames, in order to tell the associated
2462     * DisplayList to restore its alpha value.
2463     */
2464    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2465
2466    /**
2467     * Flag indicating that the view has been through at least one layout since it
2468     * was last attached to a window.
2469     */
2470    static final int PFLAG3_IS_LAID_OUT = 0x4;
2471
2472    /**
2473     * Flag indicating that a call to measure() was skipped and should be done
2474     * instead when layout() is invoked.
2475     */
2476    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2477
2478    /**
2479     * Flag indicating that an overridden method correctly called down to
2480     * the superclass implementation as required by the API spec.
2481     */
2482    static final int PFLAG3_CALLED_SUPER = 0x10;
2483
2484    /**
2485     * Flag indicating that we're in the process of applying window insets.
2486     */
2487    static final int PFLAG3_APPLYING_INSETS = 0x20;
2488
2489    /**
2490     * Flag indicating that we're in the process of fitting system windows using the old method.
2491     */
2492    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2493
2494    /**
2495     * Flag indicating that nested scrolling is enabled for this view.
2496     * The view will optionally cooperate with views up its parent chain to allow for
2497     * integrated nested scrolling along the same axis.
2498     */
2499    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2500
2501    /**
2502     * Flag indicating that the bottom scroll indicator should be displayed
2503     * when this view can scroll up.
2504     */
2505    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2506
2507    /**
2508     * Flag indicating that the bottom scroll indicator should be displayed
2509     * when this view can scroll down.
2510     */
2511    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2512
2513    /**
2514     * Flag indicating that the left scroll indicator should be displayed
2515     * when this view can scroll left.
2516     */
2517    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2518
2519    /**
2520     * Flag indicating that the right scroll indicator should be displayed
2521     * when this view can scroll right.
2522     */
2523    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2524
2525    /**
2526     * Flag indicating that the start scroll indicator should be displayed
2527     * when this view can scroll in the start direction.
2528     */
2529    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2530
2531    /**
2532     * Flag indicating that the end scroll indicator should be displayed
2533     * when this view can scroll in the end direction.
2534     */
2535    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2536
2537    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2538
2539    static final int SCROLL_INDICATORS_NONE = 0x0000;
2540
2541    /**
2542     * Mask for use with setFlags indicating bits used for indicating which
2543     * scroll indicators are enabled.
2544     */
2545    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2546            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2547            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2548            | PFLAG3_SCROLL_INDICATOR_END;
2549
2550    /**
2551     * Left-shift required to translate between public scroll indicator flags
2552     * and internal PFLAGS3 flags. When used as a right-shift, translates
2553     * PFLAGS3 flags to public flags.
2554     */
2555    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2556
2557    /** @hide */
2558    @Retention(RetentionPolicy.SOURCE)
2559    @IntDef(flag = true,
2560            value = {
2561                    SCROLL_INDICATOR_TOP,
2562                    SCROLL_INDICATOR_BOTTOM,
2563                    SCROLL_INDICATOR_LEFT,
2564                    SCROLL_INDICATOR_RIGHT,
2565                    SCROLL_INDICATOR_START,
2566                    SCROLL_INDICATOR_END,
2567            })
2568    public @interface ScrollIndicators {}
2569
2570    /**
2571     * Scroll indicator direction for the top edge of the view.
2572     *
2573     * @see #setScrollIndicators(int)
2574     * @see #setScrollIndicators(int, int)
2575     * @see #getScrollIndicators()
2576     */
2577    public static final int SCROLL_INDICATOR_TOP =
2578            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2579
2580    /**
2581     * Scroll indicator direction for the bottom edge of the view.
2582     *
2583     * @see #setScrollIndicators(int)
2584     * @see #setScrollIndicators(int, int)
2585     * @see #getScrollIndicators()
2586     */
2587    public static final int SCROLL_INDICATOR_BOTTOM =
2588            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2589
2590    /**
2591     * Scroll indicator direction for the left edge of the view.
2592     *
2593     * @see #setScrollIndicators(int)
2594     * @see #setScrollIndicators(int, int)
2595     * @see #getScrollIndicators()
2596     */
2597    public static final int SCROLL_INDICATOR_LEFT =
2598            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2599
2600    /**
2601     * Scroll indicator direction for the right edge of the view.
2602     *
2603     * @see #setScrollIndicators(int)
2604     * @see #setScrollIndicators(int, int)
2605     * @see #getScrollIndicators()
2606     */
2607    public static final int SCROLL_INDICATOR_RIGHT =
2608            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2609
2610    /**
2611     * Scroll indicator direction for the starting edge of the view.
2612     * <p>
2613     * Resolved according to the view's layout direction, see
2614     * {@link #getLayoutDirection()} for more information.
2615     *
2616     * @see #setScrollIndicators(int)
2617     * @see #setScrollIndicators(int, int)
2618     * @see #getScrollIndicators()
2619     */
2620    public static final int SCROLL_INDICATOR_START =
2621            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2622
2623    /**
2624     * Scroll indicator direction for the ending edge of the view.
2625     * <p>
2626     * Resolved according to the view's layout direction, see
2627     * {@link #getLayoutDirection()} for more information.
2628     *
2629     * @see #setScrollIndicators(int)
2630     * @see #setScrollIndicators(int, int)
2631     * @see #getScrollIndicators()
2632     */
2633    public static final int SCROLL_INDICATOR_END =
2634            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2635
2636    /**
2637     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2638     * into this view.<p>
2639     */
2640    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2641
2642    /**
2643     * The mask for use with private flags indicating bits used for pointer icon shapes.
2644     */
2645    static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000;
2646
2647    /**
2648     * Left-shift used for pointer icon shape values in private flags.
2649     */
2650    static final int PFLAG3_POINTER_ICON_LSHIFT = 15;
2651
2652    /**
2653     * Value indicating no specific pointer icons.
2654     */
2655    private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT;
2656
2657    /**
2658     * Value indicating {@link PointerIcon.TYPE_NULL}.
2659     */
2660    private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT;
2661
2662    /**
2663     * The base value for other pointer icon shapes.
2664     */
2665    private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT;
2666
2667    /**
2668     * Whether this view has rendered elements that overlap (see {@link
2669     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2670     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2671     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2672     * determined by whatever {@link #hasOverlappingRendering()} returns.
2673     */
2674    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2675
2676    /**
2677     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2678     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2679     */
2680    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2681
2682    /**
2683     * Flag indicating that the view is temporarily detached from the parent view.
2684     *
2685     * @see #onStartTemporaryDetach()
2686     * @see #onFinishTemporaryDetach()
2687     */
2688    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2689
2690    /**
2691     * Flag indicating that the view does not wish to be revealed within its parent
2692     * hierarchy when it gains focus. Expressed in the negative since the historical
2693     * default behavior is to reveal on focus; this flag suppresses that behavior.
2694     *
2695     * @see #setRevealOnFocusHint(boolean)
2696     * @see #getRevealOnFocusHint()
2697     */
2698    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
2699
2700    /* End of masks for mPrivateFlags3 */
2701
2702    /**
2703     * Always allow a user to over-scroll this view, provided it is a
2704     * view that can scroll.
2705     *
2706     * @see #getOverScrollMode()
2707     * @see #setOverScrollMode(int)
2708     */
2709    public static final int OVER_SCROLL_ALWAYS = 0;
2710
2711    /**
2712     * Allow a user to over-scroll this view only if the content is large
2713     * enough to meaningfully scroll, provided it is a view that can scroll.
2714     *
2715     * @see #getOverScrollMode()
2716     * @see #setOverScrollMode(int)
2717     */
2718    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2719
2720    /**
2721     * Never allow a user to over-scroll this view.
2722     *
2723     * @see #getOverScrollMode()
2724     * @see #setOverScrollMode(int)
2725     */
2726    public static final int OVER_SCROLL_NEVER = 2;
2727
2728    /**
2729     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2730     * requested the system UI (status bar) to be visible (the default).
2731     *
2732     * @see #setSystemUiVisibility(int)
2733     */
2734    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2735
2736    /**
2737     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2738     * system UI to enter an unobtrusive "low profile" mode.
2739     *
2740     * <p>This is for use in games, book readers, video players, or any other
2741     * "immersive" application where the usual system chrome is deemed too distracting.
2742     *
2743     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2744     *
2745     * @see #setSystemUiVisibility(int)
2746     */
2747    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2748
2749    /**
2750     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2751     * system navigation be temporarily hidden.
2752     *
2753     * <p>This is an even less obtrusive state than that called for by
2754     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2755     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2756     * those to disappear. This is useful (in conjunction with the
2757     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2758     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2759     * window flags) for displaying content using every last pixel on the display.
2760     *
2761     * <p>There is a limitation: because navigation controls are so important, the least user
2762     * interaction will cause them to reappear immediately.  When this happens, both
2763     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2764     * so that both elements reappear at the same time.
2765     *
2766     * @see #setSystemUiVisibility(int)
2767     */
2768    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2769
2770    /**
2771     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2772     * into the normal fullscreen mode so that its content can take over the screen
2773     * while still allowing the user to interact with the application.
2774     *
2775     * <p>This has the same visual effect as
2776     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2777     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2778     * meaning that non-critical screen decorations (such as the status bar) will be
2779     * hidden while the user is in the View's window, focusing the experience on
2780     * that content.  Unlike the window flag, if you are using ActionBar in
2781     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2782     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2783     * hide the action bar.
2784     *
2785     * <p>This approach to going fullscreen is best used over the window flag when
2786     * it is a transient state -- that is, the application does this at certain
2787     * points in its user interaction where it wants to allow the user to focus
2788     * on content, but not as a continuous state.  For situations where the application
2789     * would like to simply stay full screen the entire time (such as a game that
2790     * wants to take over the screen), the
2791     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2792     * is usually a better approach.  The state set here will be removed by the system
2793     * in various situations (such as the user moving to another application) like
2794     * the other system UI states.
2795     *
2796     * <p>When using this flag, the application should provide some easy facility
2797     * for the user to go out of it.  A common example would be in an e-book
2798     * reader, where tapping on the screen brings back whatever screen and UI
2799     * decorations that had been hidden while the user was immersed in reading
2800     * the book.
2801     *
2802     * @see #setSystemUiVisibility(int)
2803     */
2804    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2805
2806    /**
2807     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2808     * flags, we would like a stable view of the content insets given to
2809     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2810     * will always represent the worst case that the application can expect
2811     * as a continuous state.  In the stock Android UI this is the space for
2812     * the system bar, nav bar, and status bar, but not more transient elements
2813     * such as an input method.
2814     *
2815     * The stable layout your UI sees is based on the system UI modes you can
2816     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2817     * then you will get a stable layout for changes of the
2818     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2819     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2820     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2821     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2822     * with a stable layout.  (Note that you should avoid using
2823     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2824     *
2825     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2826     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2827     * then a hidden status bar will be considered a "stable" state for purposes
2828     * here.  This allows your UI to continually hide the status bar, while still
2829     * using the system UI flags to hide the action bar while still retaining
2830     * a stable layout.  Note that changing the window fullscreen flag will never
2831     * provide a stable layout for a clean transition.
2832     *
2833     * <p>If you are using ActionBar in
2834     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2835     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2836     * insets it adds to those given to the application.
2837     */
2838    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2839
2840    /**
2841     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2842     * to be laid out as if it has requested
2843     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2844     * allows it to avoid artifacts when switching in and out of that mode, at
2845     * the expense that some of its user interface may be covered by screen
2846     * decorations when they are shown.  You can perform layout of your inner
2847     * UI elements to account for the navigation system UI through the
2848     * {@link #fitSystemWindows(Rect)} method.
2849     */
2850    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2851
2852    /**
2853     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2854     * to be laid out as if it has requested
2855     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2856     * allows it to avoid artifacts when switching in and out of that mode, at
2857     * the expense that some of its user interface may be covered by screen
2858     * decorations when they are shown.  You can perform layout of your inner
2859     * UI elements to account for non-fullscreen system UI through the
2860     * {@link #fitSystemWindows(Rect)} method.
2861     */
2862    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2863
2864    /**
2865     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2866     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2867     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2868     * user interaction.
2869     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2870     * has an effect when used in combination with that flag.</p>
2871     */
2872    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2873
2874    /**
2875     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2876     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2877     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2878     * experience while also hiding the system bars.  If this flag is not set,
2879     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2880     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2881     * if the user swipes from the top of the screen.
2882     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2883     * system gestures, such as swiping from the top of the screen.  These transient system bars
2884     * will overlay app’s content, may have some degree of transparency, and will automatically
2885     * hide after a short timeout.
2886     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2887     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2888     * with one or both of those flags.</p>
2889     */
2890    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2891
2892    /**
2893     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2894     * is compatible with light status bar backgrounds.
2895     *
2896     * <p>For this to take effect, the window must request
2897     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2898     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2899     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2900     *         FLAG_TRANSLUCENT_STATUS}.
2901     *
2902     * @see android.R.attr#windowLightStatusBar
2903     */
2904    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2905
2906    /**
2907     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2908     */
2909    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2910
2911    /**
2912     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2913     */
2914    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2915
2916    /**
2917     * @hide
2918     *
2919     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2920     * out of the public fields to keep the undefined bits out of the developer's way.
2921     *
2922     * Flag to make the status bar not expandable.  Unless you also
2923     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2924     */
2925    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2926
2927    /**
2928     * @hide
2929     *
2930     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2931     * out of the public fields to keep the undefined bits out of the developer's way.
2932     *
2933     * Flag to hide notification icons and scrolling ticker text.
2934     */
2935    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2936
2937    /**
2938     * @hide
2939     *
2940     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2941     * out of the public fields to keep the undefined bits out of the developer's way.
2942     *
2943     * Flag to disable incoming notification alerts.  This will not block
2944     * icons, but it will block sound, vibrating and other visual or aural notifications.
2945     */
2946    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2947
2948    /**
2949     * @hide
2950     *
2951     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2952     * out of the public fields to keep the undefined bits out of the developer's way.
2953     *
2954     * Flag to hide only the scrolling ticker.  Note that
2955     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2956     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2957     */
2958    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2959
2960    /**
2961     * @hide
2962     *
2963     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2964     * out of the public fields to keep the undefined bits out of the developer's way.
2965     *
2966     * Flag to hide the center system info area.
2967     */
2968    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2969
2970    /**
2971     * @hide
2972     *
2973     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2974     * out of the public fields to keep the undefined bits out of the developer's way.
2975     *
2976     * Flag to hide only the home button.  Don't use this
2977     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2978     */
2979    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2980
2981    /**
2982     * @hide
2983     *
2984     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2985     * out of the public fields to keep the undefined bits out of the developer's way.
2986     *
2987     * Flag to hide only the back button. Don't use this
2988     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2989     */
2990    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2991
2992    /**
2993     * @hide
2994     *
2995     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2996     * out of the public fields to keep the undefined bits out of the developer's way.
2997     *
2998     * Flag to hide only the clock.  You might use this if your activity has
2999     * its own clock making the status bar's clock redundant.
3000     */
3001    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3002
3003    /**
3004     * @hide
3005     *
3006     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3007     * out of the public fields to keep the undefined bits out of the developer's way.
3008     *
3009     * Flag to hide only the recent apps button. Don't use this
3010     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3011     */
3012    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3013
3014    /**
3015     * @hide
3016     *
3017     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3018     * out of the public fields to keep the undefined bits out of the developer's way.
3019     *
3020     * Flag to disable the global search gesture. Don't use this
3021     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3022     */
3023    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3024
3025    /**
3026     * @hide
3027     *
3028     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3029     * out of the public fields to keep the undefined bits out of the developer's way.
3030     *
3031     * Flag to specify that the status bar is displayed in transient mode.
3032     */
3033    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3034
3035    /**
3036     * @hide
3037     *
3038     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3039     * out of the public fields to keep the undefined bits out of the developer's way.
3040     *
3041     * Flag to specify that the navigation bar is displayed in transient mode.
3042     */
3043    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3044
3045    /**
3046     * @hide
3047     *
3048     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3049     * out of the public fields to keep the undefined bits out of the developer's way.
3050     *
3051     * Flag to specify that the hidden status bar would like to be shown.
3052     */
3053    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3054
3055    /**
3056     * @hide
3057     *
3058     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3059     * out of the public fields to keep the undefined bits out of the developer's way.
3060     *
3061     * Flag to specify that the hidden navigation bar would like to be shown.
3062     */
3063    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3064
3065    /**
3066     * @hide
3067     *
3068     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3069     * out of the public fields to keep the undefined bits out of the developer's way.
3070     *
3071     * Flag to specify that the status bar is displayed in translucent mode.
3072     */
3073    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3074
3075    /**
3076     * @hide
3077     *
3078     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3079     * out of the public fields to keep the undefined bits out of the developer's way.
3080     *
3081     * Flag to specify that the navigation bar is displayed in translucent mode.
3082     */
3083    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3084
3085    /**
3086     * @hide
3087     *
3088     * Whether Recents is visible or not.
3089     */
3090    public static final int RECENT_APPS_VISIBLE = 0x00004000;
3091
3092    /**
3093     * @hide
3094     *
3095     * Whether the TV's picture-in-picture is visible or not.
3096     */
3097    public static final int TV_PICTURE_IN_PICTURE_VISIBLE = 0x00010000;
3098
3099    /**
3100     * @hide
3101     *
3102     * Makes navigation bar transparent (but not the status bar).
3103     */
3104    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3105
3106    /**
3107     * @hide
3108     *
3109     * Makes status bar transparent (but not the navigation bar).
3110     */
3111    public static final int STATUS_BAR_TRANSPARENT = 0x0000008;
3112
3113    /**
3114     * @hide
3115     *
3116     * Makes both status bar and navigation bar transparent.
3117     */
3118    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3119            | STATUS_BAR_TRANSPARENT;
3120
3121    /**
3122     * @hide
3123     */
3124    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3125
3126    /**
3127     * These are the system UI flags that can be cleared by events outside
3128     * of an application.  Currently this is just the ability to tap on the
3129     * screen while hiding the navigation bar to have it return.
3130     * @hide
3131     */
3132    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3133            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3134            | SYSTEM_UI_FLAG_FULLSCREEN;
3135
3136    /**
3137     * Flags that can impact the layout in relation to system UI.
3138     */
3139    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3140            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3141            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3142
3143    /** @hide */
3144    @IntDef(flag = true,
3145            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3146    @Retention(RetentionPolicy.SOURCE)
3147    public @interface FindViewFlags {}
3148
3149    /**
3150     * Find views that render the specified text.
3151     *
3152     * @see #findViewsWithText(ArrayList, CharSequence, int)
3153     */
3154    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3155
3156    /**
3157     * Find find views that contain the specified content description.
3158     *
3159     * @see #findViewsWithText(ArrayList, CharSequence, int)
3160     */
3161    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3162
3163    /**
3164     * Find views that contain {@link AccessibilityNodeProvider}. Such
3165     * a View is a root of virtual view hierarchy and may contain the searched
3166     * text. If this flag is set Views with providers are automatically
3167     * added and it is a responsibility of the client to call the APIs of
3168     * the provider to determine whether the virtual tree rooted at this View
3169     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3170     * representing the virtual views with this text.
3171     *
3172     * @see #findViewsWithText(ArrayList, CharSequence, int)
3173     *
3174     * @hide
3175     */
3176    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3177
3178    /**
3179     * The undefined cursor position.
3180     *
3181     * @hide
3182     */
3183    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3184
3185    /**
3186     * Indicates that the screen has changed state and is now off.
3187     *
3188     * @see #onScreenStateChanged(int)
3189     */
3190    public static final int SCREEN_STATE_OFF = 0x0;
3191
3192    /**
3193     * Indicates that the screen has changed state and is now on.
3194     *
3195     * @see #onScreenStateChanged(int)
3196     */
3197    public static final int SCREEN_STATE_ON = 0x1;
3198
3199    /**
3200     * Indicates no axis of view scrolling.
3201     */
3202    public static final int SCROLL_AXIS_NONE = 0;
3203
3204    /**
3205     * Indicates scrolling along the horizontal axis.
3206     */
3207    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3208
3209    /**
3210     * Indicates scrolling along the vertical axis.
3211     */
3212    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3213
3214    /**
3215     * Controls the over-scroll mode for this view.
3216     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3217     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3218     * and {@link #OVER_SCROLL_NEVER}.
3219     */
3220    private int mOverScrollMode;
3221
3222    /**
3223     * The parent this view is attached to.
3224     * {@hide}
3225     *
3226     * @see #getParent()
3227     */
3228    protected ViewParent mParent;
3229
3230    /**
3231     * {@hide}
3232     */
3233    AttachInfo mAttachInfo;
3234
3235    /**
3236     * {@hide}
3237     */
3238    @ViewDebug.ExportedProperty(flagMapping = {
3239        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3240                name = "FORCE_LAYOUT"),
3241        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3242                name = "LAYOUT_REQUIRED"),
3243        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3244            name = "DRAWING_CACHE_INVALID", outputIf = false),
3245        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3246        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3247        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3248        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3249    }, formatToHexString = true)
3250    int mPrivateFlags;
3251    int mPrivateFlags2;
3252    int mPrivateFlags3;
3253
3254    /**
3255     * This view's request for the visibility of the status bar.
3256     * @hide
3257     */
3258    @ViewDebug.ExportedProperty(flagMapping = {
3259        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3260                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3261                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3262        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3263                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3264                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3265        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3266                                equals = SYSTEM_UI_FLAG_VISIBLE,
3267                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3268    }, formatToHexString = true)
3269    int mSystemUiVisibility;
3270
3271    /**
3272     * Reference count for transient state.
3273     * @see #setHasTransientState(boolean)
3274     */
3275    int mTransientStateCount = 0;
3276
3277    /**
3278     * Count of how many windows this view has been attached to.
3279     */
3280    int mWindowAttachCount;
3281
3282    /**
3283     * The layout parameters associated with this view and used by the parent
3284     * {@link android.view.ViewGroup} to determine how this view should be
3285     * laid out.
3286     * {@hide}
3287     */
3288    protected ViewGroup.LayoutParams mLayoutParams;
3289
3290    /**
3291     * The view flags hold various views states.
3292     * {@hide}
3293     */
3294    @ViewDebug.ExportedProperty(formatToHexString = true)
3295    int mViewFlags;
3296
3297    static class TransformationInfo {
3298        /**
3299         * The transform matrix for the View. This transform is calculated internally
3300         * based on the translation, rotation, and scale properties.
3301         *
3302         * Do *not* use this variable directly; instead call getMatrix(), which will
3303         * load the value from the View's RenderNode.
3304         */
3305        private final Matrix mMatrix = new Matrix();
3306
3307        /**
3308         * The inverse transform matrix for the View. This transform is calculated
3309         * internally based on the translation, rotation, and scale properties.
3310         *
3311         * Do *not* use this variable directly; instead call getInverseMatrix(),
3312         * which will load the value from the View's RenderNode.
3313         */
3314        private Matrix mInverseMatrix;
3315
3316        /**
3317         * The opacity of the View. This is a value from 0 to 1, where 0 means
3318         * completely transparent and 1 means completely opaque.
3319         */
3320        @ViewDebug.ExportedProperty
3321        float mAlpha = 1f;
3322
3323        /**
3324         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3325         * property only used by transitions, which is composited with the other alpha
3326         * values to calculate the final visual alpha value.
3327         */
3328        float mTransitionAlpha = 1f;
3329    }
3330
3331    TransformationInfo mTransformationInfo;
3332
3333    /**
3334     * Current clip bounds. to which all drawing of this view are constrained.
3335     */
3336    Rect mClipBounds = null;
3337
3338    private boolean mLastIsOpaque;
3339
3340    /**
3341     * The distance in pixels from the left edge of this view's parent
3342     * to the left edge of this view.
3343     * {@hide}
3344     */
3345    @ViewDebug.ExportedProperty(category = "layout")
3346    protected int mLeft;
3347    /**
3348     * The distance in pixels from the left edge of this view's parent
3349     * to the right edge of this view.
3350     * {@hide}
3351     */
3352    @ViewDebug.ExportedProperty(category = "layout")
3353    protected int mRight;
3354    /**
3355     * The distance in pixels from the top edge of this view's parent
3356     * to the top edge of this view.
3357     * {@hide}
3358     */
3359    @ViewDebug.ExportedProperty(category = "layout")
3360    protected int mTop;
3361    /**
3362     * The distance in pixels from the top edge of this view's parent
3363     * to the bottom edge of this view.
3364     * {@hide}
3365     */
3366    @ViewDebug.ExportedProperty(category = "layout")
3367    protected int mBottom;
3368
3369    /**
3370     * The offset, in pixels, by which the content of this view is scrolled
3371     * horizontally.
3372     * {@hide}
3373     */
3374    @ViewDebug.ExportedProperty(category = "scrolling")
3375    protected int mScrollX;
3376    /**
3377     * The offset, in pixels, by which the content of this view is scrolled
3378     * vertically.
3379     * {@hide}
3380     */
3381    @ViewDebug.ExportedProperty(category = "scrolling")
3382    protected int mScrollY;
3383
3384    /**
3385     * The left padding in pixels, that is the distance in pixels between the
3386     * left edge of this view and the left edge of its content.
3387     * {@hide}
3388     */
3389    @ViewDebug.ExportedProperty(category = "padding")
3390    protected int mPaddingLeft = 0;
3391    /**
3392     * The right padding in pixels, that is the distance in pixels between the
3393     * right edge of this view and the right edge of its content.
3394     * {@hide}
3395     */
3396    @ViewDebug.ExportedProperty(category = "padding")
3397    protected int mPaddingRight = 0;
3398    /**
3399     * The top padding in pixels, that is the distance in pixels between the
3400     * top edge of this view and the top edge of its content.
3401     * {@hide}
3402     */
3403    @ViewDebug.ExportedProperty(category = "padding")
3404    protected int mPaddingTop;
3405    /**
3406     * The bottom padding in pixels, that is the distance in pixels between the
3407     * bottom edge of this view and the bottom edge of its content.
3408     * {@hide}
3409     */
3410    @ViewDebug.ExportedProperty(category = "padding")
3411    protected int mPaddingBottom;
3412
3413    /**
3414     * The layout insets in pixels, that is the distance in pixels between the
3415     * visible edges of this view its bounds.
3416     */
3417    private Insets mLayoutInsets;
3418
3419    /**
3420     * Briefly describes the view and is primarily used for accessibility support.
3421     */
3422    private CharSequence mContentDescription;
3423
3424    /**
3425     * Specifies the id of a view for which this view serves as a label for
3426     * accessibility purposes.
3427     */
3428    private int mLabelForId = View.NO_ID;
3429
3430    /**
3431     * Predicate for matching labeled view id with its label for
3432     * accessibility purposes.
3433     */
3434    private MatchLabelForPredicate mMatchLabelForPredicate;
3435
3436    /**
3437     * Specifies a view before which this one is visited in accessibility traversal.
3438     */
3439    private int mAccessibilityTraversalBeforeId = NO_ID;
3440
3441    /**
3442     * Specifies a view after which this one is visited in accessibility traversal.
3443     */
3444    private int mAccessibilityTraversalAfterId = NO_ID;
3445
3446    /**
3447     * Predicate for matching a view by its id.
3448     */
3449    private MatchIdPredicate mMatchIdPredicate;
3450
3451    /**
3452     * Cache the paddingRight set by the user to append to the scrollbar's size.
3453     *
3454     * @hide
3455     */
3456    @ViewDebug.ExportedProperty(category = "padding")
3457    protected int mUserPaddingRight;
3458
3459    /**
3460     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3461     *
3462     * @hide
3463     */
3464    @ViewDebug.ExportedProperty(category = "padding")
3465    protected int mUserPaddingBottom;
3466
3467    /**
3468     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3469     *
3470     * @hide
3471     */
3472    @ViewDebug.ExportedProperty(category = "padding")
3473    protected int mUserPaddingLeft;
3474
3475    /**
3476     * Cache the paddingStart set by the user to append to the scrollbar's size.
3477     *
3478     */
3479    @ViewDebug.ExportedProperty(category = "padding")
3480    int mUserPaddingStart;
3481
3482    /**
3483     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3484     *
3485     */
3486    @ViewDebug.ExportedProperty(category = "padding")
3487    int mUserPaddingEnd;
3488
3489    /**
3490     * Cache initial left padding.
3491     *
3492     * @hide
3493     */
3494    int mUserPaddingLeftInitial;
3495
3496    /**
3497     * Cache initial right padding.
3498     *
3499     * @hide
3500     */
3501    int mUserPaddingRightInitial;
3502
3503    /**
3504     * Default undefined padding
3505     */
3506    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3507
3508    /**
3509     * Cache if a left padding has been defined
3510     */
3511    private boolean mLeftPaddingDefined = false;
3512
3513    /**
3514     * Cache if a right padding has been defined
3515     */
3516    private boolean mRightPaddingDefined = false;
3517
3518    /**
3519     * @hide
3520     */
3521    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3522    /**
3523     * @hide
3524     */
3525    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3526
3527    private LongSparseLongArray mMeasureCache;
3528
3529    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3530    private Drawable mBackground;
3531    private TintInfo mBackgroundTint;
3532
3533    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3534    private ForegroundInfo mForegroundInfo;
3535
3536    private Drawable mScrollIndicatorDrawable;
3537
3538    /**
3539     * RenderNode used for backgrounds.
3540     * <p>
3541     * When non-null and valid, this is expected to contain an up-to-date copy
3542     * of the background drawable. It is cleared on temporary detach, and reset
3543     * on cleanup.
3544     */
3545    private RenderNode mBackgroundRenderNode;
3546
3547    private int mBackgroundResource;
3548    private boolean mBackgroundSizeChanged;
3549
3550    private String mTransitionName;
3551
3552    static class TintInfo {
3553        ColorStateList mTintList;
3554        PorterDuff.Mode mTintMode;
3555        boolean mHasTintMode;
3556        boolean mHasTintList;
3557    }
3558
3559    private static class ForegroundInfo {
3560        private Drawable mDrawable;
3561        private TintInfo mTintInfo;
3562        private int mGravity = Gravity.FILL;
3563        private boolean mInsidePadding = true;
3564        private boolean mBoundsChanged = true;
3565        private final Rect mSelfBounds = new Rect();
3566        private final Rect mOverlayBounds = new Rect();
3567    }
3568
3569    static class ListenerInfo {
3570        /**
3571         * Listener used to dispatch focus change events.
3572         * This field should be made private, so it is hidden from the SDK.
3573         * {@hide}
3574         */
3575        protected OnFocusChangeListener mOnFocusChangeListener;
3576
3577        /**
3578         * Listeners for layout change events.
3579         */
3580        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3581
3582        protected OnScrollChangeListener mOnScrollChangeListener;
3583
3584        /**
3585         * Listeners for attach events.
3586         */
3587        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3588
3589        /**
3590         * Listener used to dispatch click events.
3591         * This field should be made private, so it is hidden from the SDK.
3592         * {@hide}
3593         */
3594        public OnClickListener mOnClickListener;
3595
3596        /**
3597         * Listener used to dispatch long click events.
3598         * This field should be made private, so it is hidden from the SDK.
3599         * {@hide}
3600         */
3601        protected OnLongClickListener mOnLongClickListener;
3602
3603        /**
3604         * Listener used to dispatch context click events. This field should be made private, so it
3605         * is hidden from the SDK.
3606         * {@hide}
3607         */
3608        protected OnContextClickListener mOnContextClickListener;
3609
3610        /**
3611         * Listener used to build the context menu.
3612         * This field should be made private, so it is hidden from the SDK.
3613         * {@hide}
3614         */
3615        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3616
3617        private OnKeyListener mOnKeyListener;
3618
3619        private OnTouchListener mOnTouchListener;
3620
3621        private OnHoverListener mOnHoverListener;
3622
3623        private OnGenericMotionListener mOnGenericMotionListener;
3624
3625        private OnDragListener mOnDragListener;
3626
3627        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3628
3629        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3630    }
3631
3632    ListenerInfo mListenerInfo;
3633
3634    // Temporary values used to hold (x,y) coordinates when delegating from the
3635    // two-arg performLongClick() method to the legacy no-arg version.
3636    private float mLongClickX = Float.NaN;
3637    private float mLongClickY = Float.NaN;
3638
3639    /**
3640     * The application environment this view lives in.
3641     * This field should be made private, so it is hidden from the SDK.
3642     * {@hide}
3643     */
3644    @ViewDebug.ExportedProperty(deepExport = true)
3645    protected Context mContext;
3646
3647    private final Resources mResources;
3648
3649    private ScrollabilityCache mScrollCache;
3650
3651    private int[] mDrawableState = null;
3652
3653    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3654
3655    /**
3656     * Animator that automatically runs based on state changes.
3657     */
3658    private StateListAnimator mStateListAnimator;
3659
3660    /**
3661     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3662     * the user may specify which view to go to next.
3663     */
3664    private int mNextFocusLeftId = View.NO_ID;
3665
3666    /**
3667     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3668     * the user may specify which view to go to next.
3669     */
3670    private int mNextFocusRightId = View.NO_ID;
3671
3672    /**
3673     * When this view has focus and the next focus is {@link #FOCUS_UP},
3674     * the user may specify which view to go to next.
3675     */
3676    private int mNextFocusUpId = View.NO_ID;
3677
3678    /**
3679     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3680     * the user may specify which view to go to next.
3681     */
3682    private int mNextFocusDownId = View.NO_ID;
3683
3684    /**
3685     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3686     * the user may specify which view to go to next.
3687     */
3688    int mNextFocusForwardId = View.NO_ID;
3689
3690    private CheckForLongPress mPendingCheckForLongPress;
3691    private CheckForTap mPendingCheckForTap = null;
3692    private PerformClick mPerformClick;
3693    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3694
3695    private UnsetPressedState mUnsetPressedState;
3696
3697    /**
3698     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3699     * up event while a long press is invoked as soon as the long press duration is reached, so
3700     * a long press could be performed before the tap is checked, in which case the tap's action
3701     * should not be invoked.
3702     */
3703    private boolean mHasPerformedLongPress;
3704
3705    /**
3706     * Whether a context click button is currently pressed down. This is true when the stylus is
3707     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3708     * pressed. This is false once the button is released or if the stylus has been lifted.
3709     */
3710    private boolean mInContextButtonPress;
3711
3712    /**
3713     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3714     * true after a stylus button press has occured, when the next up event should not be recognized
3715     * as a tap.
3716     */
3717    private boolean mIgnoreNextUpEvent;
3718
3719    /**
3720     * The minimum height of the view. We'll try our best to have the height
3721     * of this view to at least this amount.
3722     */
3723    @ViewDebug.ExportedProperty(category = "measurement")
3724    private int mMinHeight;
3725
3726    /**
3727     * The minimum width of the view. We'll try our best to have the width
3728     * of this view to at least this amount.
3729     */
3730    @ViewDebug.ExportedProperty(category = "measurement")
3731    private int mMinWidth;
3732
3733    /**
3734     * The delegate to handle touch events that are physically in this view
3735     * but should be handled by another view.
3736     */
3737    private TouchDelegate mTouchDelegate = null;
3738
3739    /**
3740     * Solid color to use as a background when creating the drawing cache. Enables
3741     * the cache to use 16 bit bitmaps instead of 32 bit.
3742     */
3743    private int mDrawingCacheBackgroundColor = 0;
3744
3745    /**
3746     * Special tree observer used when mAttachInfo is null.
3747     */
3748    private ViewTreeObserver mFloatingTreeObserver;
3749
3750    /**
3751     * Cache the touch slop from the context that created the view.
3752     */
3753    private int mTouchSlop;
3754
3755    /**
3756     * Object that handles automatic animation of view properties.
3757     */
3758    private ViewPropertyAnimator mAnimator = null;
3759
3760    /**
3761     * List of registered FrameMetricsObservers.
3762     */
3763    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3764
3765    /**
3766     * Flag indicating that a drag can cross window boundaries.  When
3767     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3768     * with this flag set, all visible applications with targetSdkVersion >=
3769     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3770     * in the drag operation and receive the dragged content.
3771     *
3772     * <p>If this is the only flag set, then the drag recipient will only have access to text data
3773     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3774     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
3775     */
3776    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3777
3778    /**
3779     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3780     * request read access to the content URI(s) contained in the {@link ClipData} object.
3781     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3782     */
3783    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3784
3785    /**
3786     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3787     * request write access to the content URI(s) contained in the {@link ClipData} object.
3788     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3789     */
3790    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3791
3792    /**
3793     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3794     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3795     * reboots until explicitly revoked with
3796     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3797     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3798     */
3799    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3800            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3801
3802    /**
3803     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3804     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3805     * match against the original granted URI.
3806     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3807     */
3808    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3809            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3810
3811    /**
3812     * Flag indicating that the drag shadow will be opaque.  When
3813     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3814     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3815     */
3816    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3817
3818    /**
3819     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3820     */
3821    private float mVerticalScrollFactor;
3822
3823    /**
3824     * Position of the vertical scroll bar.
3825     */
3826    private int mVerticalScrollbarPosition;
3827
3828    /**
3829     * Position the scroll bar at the default position as determined by the system.
3830     */
3831    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3832
3833    /**
3834     * Position the scroll bar along the left edge.
3835     */
3836    public static final int SCROLLBAR_POSITION_LEFT = 1;
3837
3838    /**
3839     * Position the scroll bar along the right edge.
3840     */
3841    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3842
3843    /**
3844     * Indicates that the view does not have a layer.
3845     *
3846     * @see #getLayerType()
3847     * @see #setLayerType(int, android.graphics.Paint)
3848     * @see #LAYER_TYPE_SOFTWARE
3849     * @see #LAYER_TYPE_HARDWARE
3850     */
3851    public static final int LAYER_TYPE_NONE = 0;
3852
3853    /**
3854     * <p>Indicates that the view has a software layer. A software layer is backed
3855     * by a bitmap and causes the view to be rendered using Android's software
3856     * rendering pipeline, even if hardware acceleration is enabled.</p>
3857     *
3858     * <p>Software layers have various usages:</p>
3859     * <p>When the application is not using hardware acceleration, a software layer
3860     * is useful to apply a specific color filter and/or blending mode and/or
3861     * translucency to a view and all its children.</p>
3862     * <p>When the application is using hardware acceleration, a software layer
3863     * is useful to render drawing primitives not supported by the hardware
3864     * accelerated pipeline. It can also be used to cache a complex view tree
3865     * into a texture and reduce the complexity of drawing operations. For instance,
3866     * when animating a complex view tree with a translation, a software layer can
3867     * be used to render the view tree only once.</p>
3868     * <p>Software layers should be avoided when the affected view tree updates
3869     * often. Every update will require to re-render the software layer, which can
3870     * potentially be slow (particularly when hardware acceleration is turned on
3871     * since the layer will have to be uploaded into a hardware texture after every
3872     * update.)</p>
3873     *
3874     * @see #getLayerType()
3875     * @see #setLayerType(int, android.graphics.Paint)
3876     * @see #LAYER_TYPE_NONE
3877     * @see #LAYER_TYPE_HARDWARE
3878     */
3879    public static final int LAYER_TYPE_SOFTWARE = 1;
3880
3881    /**
3882     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3883     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3884     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3885     * rendering pipeline, but only if hardware acceleration is turned on for the
3886     * view hierarchy. When hardware acceleration is turned off, hardware layers
3887     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3888     *
3889     * <p>A hardware layer is useful to apply a specific color filter and/or
3890     * blending mode and/or translucency to a view and all its children.</p>
3891     * <p>A hardware layer can be used to cache a complex view tree into a
3892     * texture and reduce the complexity of drawing operations. For instance,
3893     * when animating a complex view tree with a translation, a hardware layer can
3894     * be used to render the view tree only once.</p>
3895     * <p>A hardware layer can also be used to increase the rendering quality when
3896     * rotation transformations are applied on a view. It can also be used to
3897     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3898     *
3899     * @see #getLayerType()
3900     * @see #setLayerType(int, android.graphics.Paint)
3901     * @see #LAYER_TYPE_NONE
3902     * @see #LAYER_TYPE_SOFTWARE
3903     */
3904    public static final int LAYER_TYPE_HARDWARE = 2;
3905
3906    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3907            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3908            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3909            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3910    })
3911    int mLayerType = LAYER_TYPE_NONE;
3912    Paint mLayerPaint;
3913
3914    /**
3915     * Set to true when drawing cache is enabled and cannot be created.
3916     *
3917     * @hide
3918     */
3919    public boolean mCachingFailed;
3920    private Bitmap mDrawingCache;
3921    private Bitmap mUnscaledDrawingCache;
3922
3923    /**
3924     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3925     * <p>
3926     * When non-null and valid, this is expected to contain an up-to-date copy
3927     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3928     * cleanup.
3929     */
3930    final RenderNode mRenderNode;
3931
3932    /**
3933     * Set to true when the view is sending hover accessibility events because it
3934     * is the innermost hovered view.
3935     */
3936    private boolean mSendingHoverAccessibilityEvents;
3937
3938    /**
3939     * Delegate for injecting accessibility functionality.
3940     */
3941    AccessibilityDelegate mAccessibilityDelegate;
3942
3943    /**
3944     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3945     * and add/remove objects to/from the overlay directly through the Overlay methods.
3946     */
3947    ViewOverlay mOverlay;
3948
3949    /**
3950     * The currently active parent view for receiving delegated nested scrolling events.
3951     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3952     * by {@link #stopNestedScroll()} at the same point where we clear
3953     * requestDisallowInterceptTouchEvent.
3954     */
3955    private ViewParent mNestedScrollingParent;
3956
3957    /**
3958     * Consistency verifier for debugging purposes.
3959     * @hide
3960     */
3961    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3962            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3963                    new InputEventConsistencyVerifier(this, 0) : null;
3964
3965    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3966
3967    private int[] mTempNestedScrollConsumed;
3968
3969    /**
3970     * An overlay is going to draw this View instead of being drawn as part of this
3971     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3972     * when this view is invalidated.
3973     */
3974    GhostView mGhostView;
3975
3976    /**
3977     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3978     * @hide
3979     */
3980    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3981    public String[] mAttributes;
3982
3983    /**
3984     * Maps a Resource id to its name.
3985     */
3986    private static SparseArray<String> mAttributeMap;
3987
3988    /**
3989     * Queue of pending runnables. Used to postpone calls to post() until this
3990     * view is attached and has a handler.
3991     */
3992    private HandlerActionQueue mRunQueue;
3993
3994    /**
3995     * The pointer icon when the mouse hovers on this view. The default is null.
3996     */
3997    private PointerIcon mPointerIcon;
3998
3999    /**
4000     * @hide
4001     */
4002    String mStartActivityRequestWho;
4003
4004    @Nullable
4005    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4006
4007    /**
4008     * Simple constructor to use when creating a view from code.
4009     *
4010     * @param context The Context the view is running in, through which it can
4011     *        access the current theme, resources, etc.
4012     */
4013    public View(Context context) {
4014        mContext = context;
4015        mResources = context != null ? context.getResources() : null;
4016        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
4017        // Set some flags defaults
4018        mPrivateFlags2 =
4019                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4020                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4021                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4022                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4023                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4024                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4025        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4026        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4027        mUserPaddingStart = UNDEFINED_PADDING;
4028        mUserPaddingEnd = UNDEFINED_PADDING;
4029        mRenderNode = RenderNode.create(getClass().getName(), this);
4030
4031        if (!sCompatibilityDone && context != null) {
4032            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4033
4034            // Older apps may need this compatibility hack for measurement.
4035            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4036
4037            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4038            // of whether a layout was requested on that View.
4039            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4040
4041            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4042
4043            // In M and newer, our widgets can pass a "hint" value in the size
4044            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4045            // know what the expected parent size is going to be, so e.g. list items can size
4046            // themselves at 1/3 the size of their container. It breaks older apps though,
4047            // specifically apps that use some popular open source libraries.
4048            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4049
4050            // Old versions of the platform would give different results from
4051            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4052            // modes, so we always need to run an additional EXACTLY pass.
4053            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4054
4055            // Prior to N, layout params could change without requiring a
4056            // subsequent call to setLayoutParams() and they would usually
4057            // work. Partial layout breaks this assumption.
4058            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4059
4060            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4061            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4062            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4063
4064            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4065            // in apps so we target check it to avoid breaking existing apps.
4066            sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N;
4067
4068            sCompatibilityDone = true;
4069        }
4070    }
4071
4072    /**
4073     * Constructor that is called when inflating a view from XML. This is called
4074     * when a view is being constructed from an XML file, supplying attributes
4075     * that were specified in the XML file. This version uses a default style of
4076     * 0, so the only attribute values applied are those in the Context's Theme
4077     * and the given AttributeSet.
4078     *
4079     * <p>
4080     * The method onFinishInflate() will be called after all children have been
4081     * added.
4082     *
4083     * @param context The Context the view is running in, through which it can
4084     *        access the current theme, resources, etc.
4085     * @param attrs The attributes of the XML tag that is inflating the view.
4086     * @see #View(Context, AttributeSet, int)
4087     */
4088    public View(Context context, @Nullable AttributeSet attrs) {
4089        this(context, attrs, 0);
4090    }
4091
4092    /**
4093     * Perform inflation from XML and apply a class-specific base style from a
4094     * theme attribute. This constructor of View allows subclasses to use their
4095     * own base style when they are inflating. For example, a Button class's
4096     * constructor would call this version of the super class constructor and
4097     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4098     * allows the theme's button style to modify all of the base view attributes
4099     * (in particular its background) as well as the Button class's attributes.
4100     *
4101     * @param context The Context the view is running in, through which it can
4102     *        access the current theme, resources, etc.
4103     * @param attrs The attributes of the XML tag that is inflating the view.
4104     * @param defStyleAttr An attribute in the current theme that contains a
4105     *        reference to a style resource that supplies default values for
4106     *        the view. Can be 0 to not look for defaults.
4107     * @see #View(Context, AttributeSet)
4108     */
4109    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4110        this(context, attrs, defStyleAttr, 0);
4111    }
4112
4113    /**
4114     * Perform inflation from XML and apply a class-specific base style from a
4115     * theme attribute or style resource. This constructor of View allows
4116     * subclasses to use their own base style when they are inflating.
4117     * <p>
4118     * When determining the final value of a particular attribute, there are
4119     * four inputs that come into play:
4120     * <ol>
4121     * <li>Any attribute values in the given AttributeSet.
4122     * <li>The style resource specified in the AttributeSet (named "style").
4123     * <li>The default style specified by <var>defStyleAttr</var>.
4124     * <li>The default style specified by <var>defStyleRes</var>.
4125     * <li>The base values in this theme.
4126     * </ol>
4127     * <p>
4128     * Each of these inputs is considered in-order, with the first listed taking
4129     * precedence over the following ones. In other words, if in the
4130     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4131     * , then the button's text will <em>always</em> be black, regardless of
4132     * what is specified in any of the styles.
4133     *
4134     * @param context The Context the view is running in, through which it can
4135     *        access the current theme, resources, etc.
4136     * @param attrs The attributes of the XML tag that is inflating the view.
4137     * @param defStyleAttr An attribute in the current theme that contains a
4138     *        reference to a style resource that supplies default values for
4139     *        the view. Can be 0 to not look for defaults.
4140     * @param defStyleRes A resource identifier of a style resource that
4141     *        supplies default values for the view, used only if
4142     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4143     *        to not look for defaults.
4144     * @see #View(Context, AttributeSet, int)
4145     */
4146    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4147        this(context);
4148
4149        final TypedArray a = context.obtainStyledAttributes(
4150                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4151
4152        if (mDebugViewAttributes) {
4153            saveAttributeData(attrs, a);
4154        }
4155
4156        Drawable background = null;
4157
4158        int leftPadding = -1;
4159        int topPadding = -1;
4160        int rightPadding = -1;
4161        int bottomPadding = -1;
4162        int startPadding = UNDEFINED_PADDING;
4163        int endPadding = UNDEFINED_PADDING;
4164
4165        int padding = -1;
4166
4167        int viewFlagValues = 0;
4168        int viewFlagMasks = 0;
4169
4170        boolean setScrollContainer = false;
4171
4172        int x = 0;
4173        int y = 0;
4174
4175        float tx = 0;
4176        float ty = 0;
4177        float tz = 0;
4178        float elevation = 0;
4179        float rotation = 0;
4180        float rotationX = 0;
4181        float rotationY = 0;
4182        float sx = 1f;
4183        float sy = 1f;
4184        boolean transformSet = false;
4185
4186        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4187        int overScrollMode = mOverScrollMode;
4188        boolean initializeScrollbars = false;
4189        boolean initializeScrollIndicators = false;
4190
4191        boolean startPaddingDefined = false;
4192        boolean endPaddingDefined = false;
4193        boolean leftPaddingDefined = false;
4194        boolean rightPaddingDefined = false;
4195
4196        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4197
4198        final int N = a.getIndexCount();
4199        for (int i = 0; i < N; i++) {
4200            int attr = a.getIndex(i);
4201            switch (attr) {
4202                case com.android.internal.R.styleable.View_background:
4203                    background = a.getDrawable(attr);
4204                    break;
4205                case com.android.internal.R.styleable.View_padding:
4206                    padding = a.getDimensionPixelSize(attr, -1);
4207                    mUserPaddingLeftInitial = padding;
4208                    mUserPaddingRightInitial = padding;
4209                    leftPaddingDefined = true;
4210                    rightPaddingDefined = true;
4211                    break;
4212                 case com.android.internal.R.styleable.View_paddingLeft:
4213                    leftPadding = a.getDimensionPixelSize(attr, -1);
4214                    mUserPaddingLeftInitial = leftPadding;
4215                    leftPaddingDefined = true;
4216                    break;
4217                case com.android.internal.R.styleable.View_paddingTop:
4218                    topPadding = a.getDimensionPixelSize(attr, -1);
4219                    break;
4220                case com.android.internal.R.styleable.View_paddingRight:
4221                    rightPadding = a.getDimensionPixelSize(attr, -1);
4222                    mUserPaddingRightInitial = rightPadding;
4223                    rightPaddingDefined = true;
4224                    break;
4225                case com.android.internal.R.styleable.View_paddingBottom:
4226                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4227                    break;
4228                case com.android.internal.R.styleable.View_paddingStart:
4229                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4230                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4231                    break;
4232                case com.android.internal.R.styleable.View_paddingEnd:
4233                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4234                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4235                    break;
4236                case com.android.internal.R.styleable.View_scrollX:
4237                    x = a.getDimensionPixelOffset(attr, 0);
4238                    break;
4239                case com.android.internal.R.styleable.View_scrollY:
4240                    y = a.getDimensionPixelOffset(attr, 0);
4241                    break;
4242                case com.android.internal.R.styleable.View_alpha:
4243                    setAlpha(a.getFloat(attr, 1f));
4244                    break;
4245                case com.android.internal.R.styleable.View_transformPivotX:
4246                    setPivotX(a.getDimension(attr, 0));
4247                    break;
4248                case com.android.internal.R.styleable.View_transformPivotY:
4249                    setPivotY(a.getDimension(attr, 0));
4250                    break;
4251                case com.android.internal.R.styleable.View_translationX:
4252                    tx = a.getDimension(attr, 0);
4253                    transformSet = true;
4254                    break;
4255                case com.android.internal.R.styleable.View_translationY:
4256                    ty = a.getDimension(attr, 0);
4257                    transformSet = true;
4258                    break;
4259                case com.android.internal.R.styleable.View_translationZ:
4260                    tz = a.getDimension(attr, 0);
4261                    transformSet = true;
4262                    break;
4263                case com.android.internal.R.styleable.View_elevation:
4264                    elevation = a.getDimension(attr, 0);
4265                    transformSet = true;
4266                    break;
4267                case com.android.internal.R.styleable.View_rotation:
4268                    rotation = a.getFloat(attr, 0);
4269                    transformSet = true;
4270                    break;
4271                case com.android.internal.R.styleable.View_rotationX:
4272                    rotationX = a.getFloat(attr, 0);
4273                    transformSet = true;
4274                    break;
4275                case com.android.internal.R.styleable.View_rotationY:
4276                    rotationY = a.getFloat(attr, 0);
4277                    transformSet = true;
4278                    break;
4279                case com.android.internal.R.styleable.View_scaleX:
4280                    sx = a.getFloat(attr, 1f);
4281                    transformSet = true;
4282                    break;
4283                case com.android.internal.R.styleable.View_scaleY:
4284                    sy = a.getFloat(attr, 1f);
4285                    transformSet = true;
4286                    break;
4287                case com.android.internal.R.styleable.View_id:
4288                    mID = a.getResourceId(attr, NO_ID);
4289                    break;
4290                case com.android.internal.R.styleable.View_tag:
4291                    mTag = a.getText(attr);
4292                    break;
4293                case com.android.internal.R.styleable.View_fitsSystemWindows:
4294                    if (a.getBoolean(attr, false)) {
4295                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4296                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4297                    }
4298                    break;
4299                case com.android.internal.R.styleable.View_focusable:
4300                    if (a.getBoolean(attr, false)) {
4301                        viewFlagValues |= FOCUSABLE;
4302                        viewFlagMasks |= FOCUSABLE_MASK;
4303                    }
4304                    break;
4305                case com.android.internal.R.styleable.View_focusableInTouchMode:
4306                    if (a.getBoolean(attr, false)) {
4307                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4308                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4309                    }
4310                    break;
4311                case com.android.internal.R.styleable.View_clickable:
4312                    if (a.getBoolean(attr, false)) {
4313                        viewFlagValues |= CLICKABLE;
4314                        viewFlagMasks |= CLICKABLE;
4315                    }
4316                    break;
4317                case com.android.internal.R.styleable.View_longClickable:
4318                    if (a.getBoolean(attr, false)) {
4319                        viewFlagValues |= LONG_CLICKABLE;
4320                        viewFlagMasks |= LONG_CLICKABLE;
4321                    }
4322                    break;
4323                case com.android.internal.R.styleable.View_contextClickable:
4324                    if (a.getBoolean(attr, false)) {
4325                        viewFlagValues |= CONTEXT_CLICKABLE;
4326                        viewFlagMasks |= CONTEXT_CLICKABLE;
4327                    }
4328                    break;
4329                case com.android.internal.R.styleable.View_saveEnabled:
4330                    if (!a.getBoolean(attr, true)) {
4331                        viewFlagValues |= SAVE_DISABLED;
4332                        viewFlagMasks |= SAVE_DISABLED_MASK;
4333                    }
4334                    break;
4335                case com.android.internal.R.styleable.View_duplicateParentState:
4336                    if (a.getBoolean(attr, false)) {
4337                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4338                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4339                    }
4340                    break;
4341                case com.android.internal.R.styleable.View_visibility:
4342                    final int visibility = a.getInt(attr, 0);
4343                    if (visibility != 0) {
4344                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4345                        viewFlagMasks |= VISIBILITY_MASK;
4346                    }
4347                    break;
4348                case com.android.internal.R.styleable.View_layoutDirection:
4349                    // Clear any layout direction flags (included resolved bits) already set
4350                    mPrivateFlags2 &=
4351                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4352                    // Set the layout direction flags depending on the value of the attribute
4353                    final int layoutDirection = a.getInt(attr, -1);
4354                    final int value = (layoutDirection != -1) ?
4355                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4356                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4357                    break;
4358                case com.android.internal.R.styleable.View_drawingCacheQuality:
4359                    final int cacheQuality = a.getInt(attr, 0);
4360                    if (cacheQuality != 0) {
4361                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4362                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4363                    }
4364                    break;
4365                case com.android.internal.R.styleable.View_contentDescription:
4366                    setContentDescription(a.getString(attr));
4367                    break;
4368                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4369                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4370                    break;
4371                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4372                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4373                    break;
4374                case com.android.internal.R.styleable.View_labelFor:
4375                    setLabelFor(a.getResourceId(attr, NO_ID));
4376                    break;
4377                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4378                    if (!a.getBoolean(attr, true)) {
4379                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4380                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4381                    }
4382                    break;
4383                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4384                    if (!a.getBoolean(attr, true)) {
4385                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4386                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4387                    }
4388                    break;
4389                case R.styleable.View_scrollbars:
4390                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4391                    if (scrollbars != SCROLLBARS_NONE) {
4392                        viewFlagValues |= scrollbars;
4393                        viewFlagMasks |= SCROLLBARS_MASK;
4394                        initializeScrollbars = true;
4395                    }
4396                    break;
4397                //noinspection deprecation
4398                case R.styleable.View_fadingEdge:
4399                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4400                        // Ignore the attribute starting with ICS
4401                        break;
4402                    }
4403                    // With builds < ICS, fall through and apply fading edges
4404                case R.styleable.View_requiresFadingEdge:
4405                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4406                    if (fadingEdge != FADING_EDGE_NONE) {
4407                        viewFlagValues |= fadingEdge;
4408                        viewFlagMasks |= FADING_EDGE_MASK;
4409                        initializeFadingEdgeInternal(a);
4410                    }
4411                    break;
4412                case R.styleable.View_scrollbarStyle:
4413                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4414                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4415                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4416                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4417                    }
4418                    break;
4419                case R.styleable.View_isScrollContainer:
4420                    setScrollContainer = true;
4421                    if (a.getBoolean(attr, false)) {
4422                        setScrollContainer(true);
4423                    }
4424                    break;
4425                case com.android.internal.R.styleable.View_keepScreenOn:
4426                    if (a.getBoolean(attr, false)) {
4427                        viewFlagValues |= KEEP_SCREEN_ON;
4428                        viewFlagMasks |= KEEP_SCREEN_ON;
4429                    }
4430                    break;
4431                case R.styleable.View_filterTouchesWhenObscured:
4432                    if (a.getBoolean(attr, false)) {
4433                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4434                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4435                    }
4436                    break;
4437                case R.styleable.View_nextFocusLeft:
4438                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4439                    break;
4440                case R.styleable.View_nextFocusRight:
4441                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4442                    break;
4443                case R.styleable.View_nextFocusUp:
4444                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4445                    break;
4446                case R.styleable.View_nextFocusDown:
4447                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4448                    break;
4449                case R.styleable.View_nextFocusForward:
4450                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4451                    break;
4452                case R.styleable.View_minWidth:
4453                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4454                    break;
4455                case R.styleable.View_minHeight:
4456                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4457                    break;
4458                case R.styleable.View_onClick:
4459                    if (context.isRestricted()) {
4460                        throw new IllegalStateException("The android:onClick attribute cannot "
4461                                + "be used within a restricted context");
4462                    }
4463
4464                    final String handlerName = a.getString(attr);
4465                    if (handlerName != null) {
4466                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4467                    }
4468                    break;
4469                case R.styleable.View_overScrollMode:
4470                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4471                    break;
4472                case R.styleable.View_verticalScrollbarPosition:
4473                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4474                    break;
4475                case R.styleable.View_layerType:
4476                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4477                    break;
4478                case R.styleable.View_textDirection:
4479                    // Clear any text direction flag already set
4480                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4481                    // Set the text direction flags depending on the value of the attribute
4482                    final int textDirection = a.getInt(attr, -1);
4483                    if (textDirection != -1) {
4484                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4485                    }
4486                    break;
4487                case R.styleable.View_textAlignment:
4488                    // Clear any text alignment flag already set
4489                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4490                    // Set the text alignment flag depending on the value of the attribute
4491                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4492                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4493                    break;
4494                case R.styleable.View_importantForAccessibility:
4495                    setImportantForAccessibility(a.getInt(attr,
4496                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4497                    break;
4498                case R.styleable.View_accessibilityLiveRegion:
4499                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4500                    break;
4501                case R.styleable.View_transitionName:
4502                    setTransitionName(a.getString(attr));
4503                    break;
4504                case R.styleable.View_nestedScrollingEnabled:
4505                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4506                    break;
4507                case R.styleable.View_stateListAnimator:
4508                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4509                            a.getResourceId(attr, 0)));
4510                    break;
4511                case R.styleable.View_backgroundTint:
4512                    // This will get applied later during setBackground().
4513                    if (mBackgroundTint == null) {
4514                        mBackgroundTint = new TintInfo();
4515                    }
4516                    mBackgroundTint.mTintList = a.getColorStateList(
4517                            R.styleable.View_backgroundTint);
4518                    mBackgroundTint.mHasTintList = true;
4519                    break;
4520                case R.styleable.View_backgroundTintMode:
4521                    // This will get applied later during setBackground().
4522                    if (mBackgroundTint == null) {
4523                        mBackgroundTint = new TintInfo();
4524                    }
4525                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4526                            R.styleable.View_backgroundTintMode, -1), null);
4527                    mBackgroundTint.mHasTintMode = true;
4528                    break;
4529                case R.styleable.View_outlineProvider:
4530                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4531                            PROVIDER_BACKGROUND));
4532                    break;
4533                case R.styleable.View_foreground:
4534                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4535                        setForeground(a.getDrawable(attr));
4536                    }
4537                    break;
4538                case R.styleable.View_foregroundGravity:
4539                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4540                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4541                    }
4542                    break;
4543                case R.styleable.View_foregroundTintMode:
4544                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4545                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4546                    }
4547                    break;
4548                case R.styleable.View_foregroundTint:
4549                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4550                        setForegroundTintList(a.getColorStateList(attr));
4551                    }
4552                    break;
4553                case R.styleable.View_foregroundInsidePadding:
4554                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4555                        if (mForegroundInfo == null) {
4556                            mForegroundInfo = new ForegroundInfo();
4557                        }
4558                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4559                                mForegroundInfo.mInsidePadding);
4560                    }
4561                    break;
4562                case R.styleable.View_scrollIndicators:
4563                    final int scrollIndicators =
4564                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4565                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4566                    if (scrollIndicators != 0) {
4567                        mPrivateFlags3 |= scrollIndicators;
4568                        initializeScrollIndicators = true;
4569                    }
4570                    break;
4571                case R.styleable.View_pointerIcon:
4572                    final int resourceId = a.getResourceId(attr, 0);
4573                    if (resourceId != 0) {
4574                        setPointerIcon(PointerIcon.load(
4575                                context.getResources(), resourceId));
4576                    } else {
4577                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4578                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4579                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4580                        }
4581                    }
4582                    break;
4583                case R.styleable.View_forceHasOverlappingRendering:
4584                    if (a.peekValue(attr) != null) {
4585                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4586                    }
4587                    break;
4588
4589            }
4590        }
4591
4592        setOverScrollMode(overScrollMode);
4593
4594        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4595        // the resolved layout direction). Those cached values will be used later during padding
4596        // resolution.
4597        mUserPaddingStart = startPadding;
4598        mUserPaddingEnd = endPadding;
4599
4600        if (background != null) {
4601            setBackground(background);
4602        }
4603
4604        // setBackground above will record that padding is currently provided by the background.
4605        // If we have padding specified via xml, record that here instead and use it.
4606        mLeftPaddingDefined = leftPaddingDefined;
4607        mRightPaddingDefined = rightPaddingDefined;
4608
4609        if (padding >= 0) {
4610            leftPadding = padding;
4611            topPadding = padding;
4612            rightPadding = padding;
4613            bottomPadding = padding;
4614            mUserPaddingLeftInitial = padding;
4615            mUserPaddingRightInitial = padding;
4616        }
4617
4618        if (isRtlCompatibilityMode()) {
4619            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4620            // left / right padding are used if defined (meaning here nothing to do). If they are not
4621            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4622            // start / end and resolve them as left / right (layout direction is not taken into account).
4623            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4624            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4625            // defined.
4626            if (!mLeftPaddingDefined && startPaddingDefined) {
4627                leftPadding = startPadding;
4628            }
4629            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4630            if (!mRightPaddingDefined && endPaddingDefined) {
4631                rightPadding = endPadding;
4632            }
4633            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4634        } else {
4635            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4636            // values defined. Otherwise, left /right values are used.
4637            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4638            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4639            // defined.
4640            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4641
4642            if (mLeftPaddingDefined && !hasRelativePadding) {
4643                mUserPaddingLeftInitial = leftPadding;
4644            }
4645            if (mRightPaddingDefined && !hasRelativePadding) {
4646                mUserPaddingRightInitial = rightPadding;
4647            }
4648        }
4649
4650        internalSetPadding(
4651                mUserPaddingLeftInitial,
4652                topPadding >= 0 ? topPadding : mPaddingTop,
4653                mUserPaddingRightInitial,
4654                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4655
4656        if (viewFlagMasks != 0) {
4657            setFlags(viewFlagValues, viewFlagMasks);
4658        }
4659
4660        if (initializeScrollbars) {
4661            initializeScrollbarsInternal(a);
4662        }
4663
4664        if (initializeScrollIndicators) {
4665            initializeScrollIndicatorsInternal();
4666        }
4667
4668        a.recycle();
4669
4670        // Needs to be called after mViewFlags is set
4671        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4672            recomputePadding();
4673        }
4674
4675        if (x != 0 || y != 0) {
4676            scrollTo(x, y);
4677        }
4678
4679        if (transformSet) {
4680            setTranslationX(tx);
4681            setTranslationY(ty);
4682            setTranslationZ(tz);
4683            setElevation(elevation);
4684            setRotation(rotation);
4685            setRotationX(rotationX);
4686            setRotationY(rotationY);
4687            setScaleX(sx);
4688            setScaleY(sy);
4689        }
4690
4691        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4692            setScrollContainer(true);
4693        }
4694
4695        computeOpaqueFlags();
4696    }
4697
4698    /**
4699     * An implementation of OnClickListener that attempts to lazily load a
4700     * named click handling method from a parent or ancestor context.
4701     */
4702    private static class DeclaredOnClickListener implements OnClickListener {
4703        private final View mHostView;
4704        private final String mMethodName;
4705
4706        private Method mResolvedMethod;
4707        private Context mResolvedContext;
4708
4709        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4710            mHostView = hostView;
4711            mMethodName = methodName;
4712        }
4713
4714        @Override
4715        public void onClick(@NonNull View v) {
4716            if (mResolvedMethod == null) {
4717                resolveMethod(mHostView.getContext(), mMethodName);
4718            }
4719
4720            try {
4721                mResolvedMethod.invoke(mResolvedContext, v);
4722            } catch (IllegalAccessException e) {
4723                throw new IllegalStateException(
4724                        "Could not execute non-public method for android:onClick", e);
4725            } catch (InvocationTargetException e) {
4726                throw new IllegalStateException(
4727                        "Could not execute method for android:onClick", e);
4728            }
4729        }
4730
4731        @NonNull
4732        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4733            while (context != null) {
4734                try {
4735                    if (!context.isRestricted()) {
4736                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4737                        if (method != null) {
4738                            mResolvedMethod = method;
4739                            mResolvedContext = context;
4740                            return;
4741                        }
4742                    }
4743                } catch (NoSuchMethodException e) {
4744                    // Failed to find method, keep searching up the hierarchy.
4745                }
4746
4747                if (context instanceof ContextWrapper) {
4748                    context = ((ContextWrapper) context).getBaseContext();
4749                } else {
4750                    // Can't search up the hierarchy, null out and fail.
4751                    context = null;
4752                }
4753            }
4754
4755            final int id = mHostView.getId();
4756            final String idText = id == NO_ID ? "" : " with id '"
4757                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4758            throw new IllegalStateException("Could not find method " + mMethodName
4759                    + "(View) in a parent or ancestor Context for android:onClick "
4760                    + "attribute defined on view " + mHostView.getClass() + idText);
4761        }
4762    }
4763
4764    /**
4765     * Non-public constructor for use in testing
4766     */
4767    View() {
4768        mResources = null;
4769        mRenderNode = RenderNode.create(getClass().getName(), this);
4770    }
4771
4772    private static SparseArray<String> getAttributeMap() {
4773        if (mAttributeMap == null) {
4774            mAttributeMap = new SparseArray<>();
4775        }
4776        return mAttributeMap;
4777    }
4778
4779    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4780        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4781        final int indexCount = t.getIndexCount();
4782        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4783
4784        int i = 0;
4785
4786        // Store raw XML attributes.
4787        for (int j = 0; j < attrsCount; ++j) {
4788            attributes[i] = attrs.getAttributeName(j);
4789            attributes[i + 1] = attrs.getAttributeValue(j);
4790            i += 2;
4791        }
4792
4793        // Store resolved styleable attributes.
4794        final Resources res = t.getResources();
4795        final SparseArray<String> attributeMap = getAttributeMap();
4796        for (int j = 0; j < indexCount; ++j) {
4797            final int index = t.getIndex(j);
4798            if (!t.hasValueOrEmpty(index)) {
4799                // Value is undefined. Skip it.
4800                continue;
4801            }
4802
4803            final int resourceId = t.getResourceId(index, 0);
4804            if (resourceId == 0) {
4805                // Value is not a reference. Skip it.
4806                continue;
4807            }
4808
4809            String resourceName = attributeMap.get(resourceId);
4810            if (resourceName == null) {
4811                try {
4812                    resourceName = res.getResourceName(resourceId);
4813                } catch (Resources.NotFoundException e) {
4814                    resourceName = "0x" + Integer.toHexString(resourceId);
4815                }
4816                attributeMap.put(resourceId, resourceName);
4817            }
4818
4819            attributes[i] = resourceName;
4820            attributes[i + 1] = t.getString(index);
4821            i += 2;
4822        }
4823
4824        // Trim to fit contents.
4825        final String[] trimmed = new String[i];
4826        System.arraycopy(attributes, 0, trimmed, 0, i);
4827        mAttributes = trimmed;
4828    }
4829
4830    public String toString() {
4831        StringBuilder out = new StringBuilder(128);
4832        out.append(getClass().getName());
4833        out.append('{');
4834        out.append(Integer.toHexString(System.identityHashCode(this)));
4835        out.append(' ');
4836        switch (mViewFlags&VISIBILITY_MASK) {
4837            case VISIBLE: out.append('V'); break;
4838            case INVISIBLE: out.append('I'); break;
4839            case GONE: out.append('G'); break;
4840            default: out.append('.'); break;
4841        }
4842        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4843        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4844        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4845        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4846        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4847        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4848        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4849        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4850        out.append(' ');
4851        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4852        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4853        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4854        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4855            out.append('p');
4856        } else {
4857            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4858        }
4859        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4860        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4861        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4862        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4863        out.append(' ');
4864        out.append(mLeft);
4865        out.append(',');
4866        out.append(mTop);
4867        out.append('-');
4868        out.append(mRight);
4869        out.append(',');
4870        out.append(mBottom);
4871        final int id = getId();
4872        if (id != NO_ID) {
4873            out.append(" #");
4874            out.append(Integer.toHexString(id));
4875            final Resources r = mResources;
4876            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
4877                try {
4878                    String pkgname;
4879                    switch (id&0xff000000) {
4880                        case 0x7f000000:
4881                            pkgname="app";
4882                            break;
4883                        case 0x01000000:
4884                            pkgname="android";
4885                            break;
4886                        default:
4887                            pkgname = r.getResourcePackageName(id);
4888                            break;
4889                    }
4890                    String typename = r.getResourceTypeName(id);
4891                    String entryname = r.getResourceEntryName(id);
4892                    out.append(" ");
4893                    out.append(pkgname);
4894                    out.append(":");
4895                    out.append(typename);
4896                    out.append("/");
4897                    out.append(entryname);
4898                } catch (Resources.NotFoundException e) {
4899                }
4900            }
4901        }
4902        out.append("}");
4903        return out.toString();
4904    }
4905
4906    /**
4907     * <p>
4908     * Initializes the fading edges from a given set of styled attributes. This
4909     * method should be called by subclasses that need fading edges and when an
4910     * instance of these subclasses is created programmatically rather than
4911     * being inflated from XML. This method is automatically called when the XML
4912     * is inflated.
4913     * </p>
4914     *
4915     * @param a the styled attributes set to initialize the fading edges from
4916     *
4917     * @removed
4918     */
4919    protected void initializeFadingEdge(TypedArray a) {
4920        // This method probably shouldn't have been included in the SDK to begin with.
4921        // It relies on 'a' having been initialized using an attribute filter array that is
4922        // not publicly available to the SDK. The old method has been renamed
4923        // to initializeFadingEdgeInternal and hidden for framework use only;
4924        // this one initializes using defaults to make it safe to call for apps.
4925
4926        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4927
4928        initializeFadingEdgeInternal(arr);
4929
4930        arr.recycle();
4931    }
4932
4933    /**
4934     * <p>
4935     * Initializes the fading edges from a given set of styled attributes. This
4936     * method should be called by subclasses that need fading edges and when an
4937     * instance of these subclasses is created programmatically rather than
4938     * being inflated from XML. This method is automatically called when the XML
4939     * is inflated.
4940     * </p>
4941     *
4942     * @param a the styled attributes set to initialize the fading edges from
4943     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4944     */
4945    protected void initializeFadingEdgeInternal(TypedArray a) {
4946        initScrollCache();
4947
4948        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4949                R.styleable.View_fadingEdgeLength,
4950                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4951    }
4952
4953    /**
4954     * Returns the size of the vertical faded edges used to indicate that more
4955     * content in this view is visible.
4956     *
4957     * @return The size in pixels of the vertical faded edge or 0 if vertical
4958     *         faded edges are not enabled for this view.
4959     * @attr ref android.R.styleable#View_fadingEdgeLength
4960     */
4961    public int getVerticalFadingEdgeLength() {
4962        if (isVerticalFadingEdgeEnabled()) {
4963            ScrollabilityCache cache = mScrollCache;
4964            if (cache != null) {
4965                return cache.fadingEdgeLength;
4966            }
4967        }
4968        return 0;
4969    }
4970
4971    /**
4972     * Set the size of the faded edge used to indicate that more content in this
4973     * view is available.  Will not change whether the fading edge is enabled; use
4974     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4975     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4976     * for the vertical or horizontal fading edges.
4977     *
4978     * @param length The size in pixels of the faded edge used to indicate that more
4979     *        content in this view is visible.
4980     */
4981    public void setFadingEdgeLength(int length) {
4982        initScrollCache();
4983        mScrollCache.fadingEdgeLength = length;
4984    }
4985
4986    /**
4987     * Returns the size of the horizontal faded edges used to indicate that more
4988     * content in this view is visible.
4989     *
4990     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4991     *         faded edges are not enabled for this view.
4992     * @attr ref android.R.styleable#View_fadingEdgeLength
4993     */
4994    public int getHorizontalFadingEdgeLength() {
4995        if (isHorizontalFadingEdgeEnabled()) {
4996            ScrollabilityCache cache = mScrollCache;
4997            if (cache != null) {
4998                return cache.fadingEdgeLength;
4999            }
5000        }
5001        return 0;
5002    }
5003
5004    /**
5005     * Returns the width of the vertical scrollbar.
5006     *
5007     * @return The width in pixels of the vertical scrollbar or 0 if there
5008     *         is no vertical scrollbar.
5009     */
5010    public int getVerticalScrollbarWidth() {
5011        ScrollabilityCache cache = mScrollCache;
5012        if (cache != null) {
5013            ScrollBarDrawable scrollBar = cache.scrollBar;
5014            if (scrollBar != null) {
5015                int size = scrollBar.getSize(true);
5016                if (size <= 0) {
5017                    size = cache.scrollBarSize;
5018                }
5019                return size;
5020            }
5021            return 0;
5022        }
5023        return 0;
5024    }
5025
5026    /**
5027     * Returns the height of the horizontal scrollbar.
5028     *
5029     * @return The height in pixels of the horizontal scrollbar or 0 if
5030     *         there is no horizontal scrollbar.
5031     */
5032    protected int getHorizontalScrollbarHeight() {
5033        ScrollabilityCache cache = mScrollCache;
5034        if (cache != null) {
5035            ScrollBarDrawable scrollBar = cache.scrollBar;
5036            if (scrollBar != null) {
5037                int size = scrollBar.getSize(false);
5038                if (size <= 0) {
5039                    size = cache.scrollBarSize;
5040                }
5041                return size;
5042            }
5043            return 0;
5044        }
5045        return 0;
5046    }
5047
5048    /**
5049     * <p>
5050     * Initializes the scrollbars from a given set of styled attributes. This
5051     * method should be called by subclasses that need scrollbars and when an
5052     * instance of these subclasses is created programmatically rather than
5053     * being inflated from XML. This method is automatically called when the XML
5054     * is inflated.
5055     * </p>
5056     *
5057     * @param a the styled attributes set to initialize the scrollbars from
5058     *
5059     * @removed
5060     */
5061    protected void initializeScrollbars(TypedArray a) {
5062        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5063        // using the View filter array which is not available to the SDK. As such, internal
5064        // framework usage now uses initializeScrollbarsInternal and we grab a default
5065        // TypedArray with the right filter instead here.
5066        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5067
5068        initializeScrollbarsInternal(arr);
5069
5070        // We ignored the method parameter. Recycle the one we actually did use.
5071        arr.recycle();
5072    }
5073
5074    /**
5075     * <p>
5076     * Initializes the scrollbars from a given set of styled attributes. This
5077     * method should be called by subclasses that need scrollbars and when an
5078     * instance of these subclasses is created programmatically rather than
5079     * being inflated from XML. This method is automatically called when the XML
5080     * is inflated.
5081     * </p>
5082     *
5083     * @param a the styled attributes set to initialize the scrollbars from
5084     * @hide
5085     */
5086    protected void initializeScrollbarsInternal(TypedArray a) {
5087        initScrollCache();
5088
5089        final ScrollabilityCache scrollabilityCache = mScrollCache;
5090
5091        if (scrollabilityCache.scrollBar == null) {
5092            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5093            scrollabilityCache.scrollBar.setState(getDrawableState());
5094            scrollabilityCache.scrollBar.setCallback(this);
5095        }
5096
5097        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5098
5099        if (!fadeScrollbars) {
5100            scrollabilityCache.state = ScrollabilityCache.ON;
5101        }
5102        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5103
5104
5105        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5106                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5107                        .getScrollBarFadeDuration());
5108        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5109                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5110                ViewConfiguration.getScrollDefaultDelay());
5111
5112
5113        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5114                com.android.internal.R.styleable.View_scrollbarSize,
5115                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5116
5117        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5118        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5119
5120        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5121        if (thumb != null) {
5122            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5123        }
5124
5125        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5126                false);
5127        if (alwaysDraw) {
5128            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5129        }
5130
5131        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5132        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5133
5134        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5135        if (thumb != null) {
5136            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5137        }
5138
5139        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5140                false);
5141        if (alwaysDraw) {
5142            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5143        }
5144
5145        // Apply layout direction to the new Drawables if needed
5146        final int layoutDirection = getLayoutDirection();
5147        if (track != null) {
5148            track.setLayoutDirection(layoutDirection);
5149        }
5150        if (thumb != null) {
5151            thumb.setLayoutDirection(layoutDirection);
5152        }
5153
5154        // Re-apply user/background padding so that scrollbar(s) get added
5155        resolvePadding();
5156    }
5157
5158    private void initializeScrollIndicatorsInternal() {
5159        // Some day maybe we'll break this into top/left/start/etc. and let the
5160        // client control it. Until then, you can have any scroll indicator you
5161        // want as long as it's a 1dp foreground-colored rectangle.
5162        if (mScrollIndicatorDrawable == null) {
5163            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5164        }
5165    }
5166
5167    /**
5168     * <p>
5169     * Initalizes the scrollability cache if necessary.
5170     * </p>
5171     */
5172    private void initScrollCache() {
5173        if (mScrollCache == null) {
5174            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5175        }
5176    }
5177
5178    private ScrollabilityCache getScrollCache() {
5179        initScrollCache();
5180        return mScrollCache;
5181    }
5182
5183    /**
5184     * Set the position of the vertical scroll bar. Should be one of
5185     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5186     * {@link #SCROLLBAR_POSITION_RIGHT}.
5187     *
5188     * @param position Where the vertical scroll bar should be positioned.
5189     */
5190    public void setVerticalScrollbarPosition(int position) {
5191        if (mVerticalScrollbarPosition != position) {
5192            mVerticalScrollbarPosition = position;
5193            computeOpaqueFlags();
5194            resolvePadding();
5195        }
5196    }
5197
5198    /**
5199     * @return The position where the vertical scroll bar will show, if applicable.
5200     * @see #setVerticalScrollbarPosition(int)
5201     */
5202    public int getVerticalScrollbarPosition() {
5203        return mVerticalScrollbarPosition;
5204    }
5205
5206    boolean isOnScrollbar(float x, float y) {
5207        if (mScrollCache == null) {
5208            return false;
5209        }
5210        x += getScrollX();
5211        y += getScrollY();
5212        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5213            final Rect bounds = mScrollCache.mScrollBarBounds;
5214            getVerticalScrollBarBounds(bounds);
5215            if (bounds.contains((int)x, (int)y)) {
5216                return true;
5217            }
5218        }
5219        if (isHorizontalScrollBarEnabled()) {
5220            final Rect bounds = mScrollCache.mScrollBarBounds;
5221            getHorizontalScrollBarBounds(bounds);
5222            if (bounds.contains((int)x, (int)y)) {
5223                return true;
5224            }
5225        }
5226        return false;
5227    }
5228
5229    boolean isOnScrollbarThumb(float x, float y) {
5230        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5231    }
5232
5233    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5234        if (mScrollCache == null) {
5235            return false;
5236        }
5237        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5238            x += getScrollX();
5239            y += getScrollY();
5240            final Rect bounds = mScrollCache.mScrollBarBounds;
5241            getVerticalScrollBarBounds(bounds);
5242            final int range = computeVerticalScrollRange();
5243            final int offset = computeVerticalScrollOffset();
5244            final int extent = computeVerticalScrollExtent();
5245            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5246                    extent, range);
5247            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5248                    extent, range, offset);
5249            final int thumbTop = bounds.top + thumbOffset;
5250            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5251                    && y <= thumbTop + thumbLength) {
5252                return true;
5253            }
5254        }
5255        return false;
5256    }
5257
5258    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5259        if (mScrollCache == null) {
5260            return false;
5261        }
5262        if (isHorizontalScrollBarEnabled()) {
5263            x += getScrollX();
5264            y += getScrollY();
5265            final Rect bounds = mScrollCache.mScrollBarBounds;
5266            getHorizontalScrollBarBounds(bounds);
5267            final int range = computeHorizontalScrollRange();
5268            final int offset = computeHorizontalScrollOffset();
5269            final int extent = computeHorizontalScrollExtent();
5270            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5271                    extent, range);
5272            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5273                    extent, range, offset);
5274            final int thumbLeft = bounds.left + thumbOffset;
5275            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5276                    && y <= bounds.bottom) {
5277                return true;
5278            }
5279        }
5280        return false;
5281    }
5282
5283    boolean isDraggingScrollBar() {
5284        return mScrollCache != null
5285                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5286    }
5287
5288    /**
5289     * Sets the state of all scroll indicators.
5290     * <p>
5291     * See {@link #setScrollIndicators(int, int)} for usage information.
5292     *
5293     * @param indicators a bitmask of indicators that should be enabled, or
5294     *                   {@code 0} to disable all indicators
5295     * @see #setScrollIndicators(int, int)
5296     * @see #getScrollIndicators()
5297     * @attr ref android.R.styleable#View_scrollIndicators
5298     */
5299    public void setScrollIndicators(@ScrollIndicators int indicators) {
5300        setScrollIndicators(indicators,
5301                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5302    }
5303
5304    /**
5305     * Sets the state of the scroll indicators specified by the mask. To change
5306     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5307     * <p>
5308     * When a scroll indicator is enabled, it will be displayed if the view
5309     * can scroll in the direction of the indicator.
5310     * <p>
5311     * Multiple indicator types may be enabled or disabled by passing the
5312     * logical OR of the desired types. If multiple types are specified, they
5313     * will all be set to the same enabled state.
5314     * <p>
5315     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5316     *
5317     * @param indicators the indicator direction, or the logical OR of multiple
5318     *             indicator directions. One or more of:
5319     *             <ul>
5320     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5321     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5322     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5323     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5324     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5325     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5326     *             </ul>
5327     * @see #setScrollIndicators(int)
5328     * @see #getScrollIndicators()
5329     * @attr ref android.R.styleable#View_scrollIndicators
5330     */
5331    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5332        // Shift and sanitize mask.
5333        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5334        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5335
5336        // Shift and mask indicators.
5337        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5338        indicators &= mask;
5339
5340        // Merge with non-masked flags.
5341        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5342
5343        if (mPrivateFlags3 != updatedFlags) {
5344            mPrivateFlags3 = updatedFlags;
5345
5346            if (indicators != 0) {
5347                initializeScrollIndicatorsInternal();
5348            }
5349            invalidate();
5350        }
5351    }
5352
5353    /**
5354     * Returns a bitmask representing the enabled scroll indicators.
5355     * <p>
5356     * For example, if the top and left scroll indicators are enabled and all
5357     * other indicators are disabled, the return value will be
5358     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5359     * <p>
5360     * To check whether the bottom scroll indicator is enabled, use the value
5361     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5362     *
5363     * @return a bitmask representing the enabled scroll indicators
5364     */
5365    @ScrollIndicators
5366    public int getScrollIndicators() {
5367        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5368                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5369    }
5370
5371    ListenerInfo getListenerInfo() {
5372        if (mListenerInfo != null) {
5373            return mListenerInfo;
5374        }
5375        mListenerInfo = new ListenerInfo();
5376        return mListenerInfo;
5377    }
5378
5379    /**
5380     * Register a callback to be invoked when the scroll X or Y positions of
5381     * this view change.
5382     * <p>
5383     * <b>Note:</b> Some views handle scrolling independently from View and may
5384     * have their own separate listeners for scroll-type events. For example,
5385     * {@link android.widget.ListView ListView} allows clients to register an
5386     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5387     * to listen for changes in list scroll position.
5388     *
5389     * @param l The listener to notify when the scroll X or Y position changes.
5390     * @see android.view.View#getScrollX()
5391     * @see android.view.View#getScrollY()
5392     */
5393    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5394        getListenerInfo().mOnScrollChangeListener = l;
5395    }
5396
5397    /**
5398     * Register a callback to be invoked when focus of this view changed.
5399     *
5400     * @param l The callback that will run.
5401     */
5402    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5403        getListenerInfo().mOnFocusChangeListener = l;
5404    }
5405
5406    /**
5407     * Add a listener that will be called when the bounds of the view change due to
5408     * layout processing.
5409     *
5410     * @param listener The listener that will be called when layout bounds change.
5411     */
5412    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5413        ListenerInfo li = getListenerInfo();
5414        if (li.mOnLayoutChangeListeners == null) {
5415            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5416        }
5417        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5418            li.mOnLayoutChangeListeners.add(listener);
5419        }
5420    }
5421
5422    /**
5423     * Remove a listener for layout changes.
5424     *
5425     * @param listener The listener for layout bounds change.
5426     */
5427    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5428        ListenerInfo li = mListenerInfo;
5429        if (li == null || li.mOnLayoutChangeListeners == null) {
5430            return;
5431        }
5432        li.mOnLayoutChangeListeners.remove(listener);
5433    }
5434
5435    /**
5436     * Add a listener for attach state changes.
5437     *
5438     * This listener will be called whenever this view is attached or detached
5439     * from a window. Remove the listener using
5440     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5441     *
5442     * @param listener Listener to attach
5443     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5444     */
5445    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5446        ListenerInfo li = getListenerInfo();
5447        if (li.mOnAttachStateChangeListeners == null) {
5448            li.mOnAttachStateChangeListeners
5449                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5450        }
5451        li.mOnAttachStateChangeListeners.add(listener);
5452    }
5453
5454    /**
5455     * Remove a listener for attach state changes. The listener will receive no further
5456     * notification of window attach/detach events.
5457     *
5458     * @param listener Listener to remove
5459     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5460     */
5461    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5462        ListenerInfo li = mListenerInfo;
5463        if (li == null || li.mOnAttachStateChangeListeners == null) {
5464            return;
5465        }
5466        li.mOnAttachStateChangeListeners.remove(listener);
5467    }
5468
5469    /**
5470     * Returns the focus-change callback registered for this view.
5471     *
5472     * @return The callback, or null if one is not registered.
5473     */
5474    public OnFocusChangeListener getOnFocusChangeListener() {
5475        ListenerInfo li = mListenerInfo;
5476        return li != null ? li.mOnFocusChangeListener : null;
5477    }
5478
5479    /**
5480     * Register a callback to be invoked when this view is clicked. If this view is not
5481     * clickable, it becomes clickable.
5482     *
5483     * @param l The callback that will run
5484     *
5485     * @see #setClickable(boolean)
5486     */
5487    public void setOnClickListener(@Nullable OnClickListener l) {
5488        if (!isClickable()) {
5489            setClickable(true);
5490        }
5491        getListenerInfo().mOnClickListener = l;
5492    }
5493
5494    /**
5495     * Return whether this view has an attached OnClickListener.  Returns
5496     * true if there is a listener, false if there is none.
5497     */
5498    public boolean hasOnClickListeners() {
5499        ListenerInfo li = mListenerInfo;
5500        return (li != null && li.mOnClickListener != null);
5501    }
5502
5503    /**
5504     * Register a callback to be invoked when this view is clicked and held. If this view is not
5505     * long clickable, it becomes long clickable.
5506     *
5507     * @param l The callback that will run
5508     *
5509     * @see #setLongClickable(boolean)
5510     */
5511    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5512        if (!isLongClickable()) {
5513            setLongClickable(true);
5514        }
5515        getListenerInfo().mOnLongClickListener = l;
5516    }
5517
5518    /**
5519     * Register a callback to be invoked when this view is context clicked. If the view is not
5520     * context clickable, it becomes context clickable.
5521     *
5522     * @param l The callback that will run
5523     * @see #setContextClickable(boolean)
5524     */
5525    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5526        if (!isContextClickable()) {
5527            setContextClickable(true);
5528        }
5529        getListenerInfo().mOnContextClickListener = l;
5530    }
5531
5532    /**
5533     * Register a callback to be invoked when the context menu for this view is
5534     * being built. If this view is not long clickable, it becomes long clickable.
5535     *
5536     * @param l The callback that will run
5537     *
5538     */
5539    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5540        if (!isLongClickable()) {
5541            setLongClickable(true);
5542        }
5543        getListenerInfo().mOnCreateContextMenuListener = l;
5544    }
5545
5546    /**
5547     * Set an observer to collect stats for each frame rendered for this view.
5548     *
5549     * @hide
5550     */
5551    public void addFrameMetricsListener(Window window,
5552            Window.OnFrameMetricsAvailableListener listener,
5553            Handler handler) {
5554        if (mAttachInfo != null) {
5555            if (mAttachInfo.mHardwareRenderer != null) {
5556                if (mFrameMetricsObservers == null) {
5557                    mFrameMetricsObservers = new ArrayList<>();
5558                }
5559
5560                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5561                        handler.getLooper(), listener);
5562                mFrameMetricsObservers.add(fmo);
5563                mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo);
5564            } else {
5565                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5566            }
5567        } else {
5568            if (mFrameMetricsObservers == null) {
5569                mFrameMetricsObservers = new ArrayList<>();
5570            }
5571
5572            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5573                    handler.getLooper(), listener);
5574            mFrameMetricsObservers.add(fmo);
5575        }
5576    }
5577
5578    /**
5579     * Remove observer configured to collect frame stats for this view.
5580     *
5581     * @hide
5582     */
5583    public void removeFrameMetricsListener(
5584            Window.OnFrameMetricsAvailableListener listener) {
5585        ThreadedRenderer renderer = getHardwareRenderer();
5586        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5587        if (fmo == null) {
5588            throw new IllegalArgumentException(
5589                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5590        }
5591
5592        if (mFrameMetricsObservers != null) {
5593            mFrameMetricsObservers.remove(fmo);
5594            if (renderer != null) {
5595                renderer.removeFrameMetricsObserver(fmo);
5596            }
5597        }
5598    }
5599
5600    private void registerPendingFrameMetricsObservers() {
5601        if (mFrameMetricsObservers != null) {
5602            ThreadedRenderer renderer = getHardwareRenderer();
5603            if (renderer != null) {
5604                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5605                    renderer.addFrameMetricsObserver(fmo);
5606                }
5607            } else {
5608                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5609            }
5610        }
5611    }
5612
5613    private FrameMetricsObserver findFrameMetricsObserver(
5614            Window.OnFrameMetricsAvailableListener listener) {
5615        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5616            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5617            if (observer.mListener == listener) {
5618                return observer;
5619            }
5620        }
5621
5622        return null;
5623    }
5624
5625    /**
5626     * Call this view's OnClickListener, if it is defined.  Performs all normal
5627     * actions associated with clicking: reporting accessibility event, playing
5628     * a sound, etc.
5629     *
5630     * @return True there was an assigned OnClickListener that was called, false
5631     *         otherwise is returned.
5632     */
5633    public boolean performClick() {
5634        final boolean result;
5635        final ListenerInfo li = mListenerInfo;
5636        if (li != null && li.mOnClickListener != null) {
5637            playSoundEffect(SoundEffectConstants.CLICK);
5638            li.mOnClickListener.onClick(this);
5639            result = true;
5640        } else {
5641            result = false;
5642        }
5643
5644        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5645        return result;
5646    }
5647
5648    /**
5649     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5650     * this only calls the listener, and does not do any associated clicking
5651     * actions like reporting an accessibility event.
5652     *
5653     * @return True there was an assigned OnClickListener that was called, false
5654     *         otherwise is returned.
5655     */
5656    public boolean callOnClick() {
5657        ListenerInfo li = mListenerInfo;
5658        if (li != null && li.mOnClickListener != null) {
5659            li.mOnClickListener.onClick(this);
5660            return true;
5661        }
5662        return false;
5663    }
5664
5665    /**
5666     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5667     * context menu if the OnLongClickListener did not consume the event.
5668     *
5669     * @return {@code true} if one of the above receivers consumed the event,
5670     *         {@code false} otherwise
5671     */
5672    public boolean performLongClick() {
5673        return performLongClickInternal(mLongClickX, mLongClickY);
5674    }
5675
5676    /**
5677     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5678     * context menu if the OnLongClickListener did not consume the event,
5679     * anchoring it to an (x,y) coordinate.
5680     *
5681     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5682     *          to disable anchoring
5683     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5684     *          to disable anchoring
5685     * @return {@code true} if one of the above receivers consumed the event,
5686     *         {@code false} otherwise
5687     */
5688    public boolean performLongClick(float x, float y) {
5689        mLongClickX = x;
5690        mLongClickY = y;
5691        final boolean handled = performLongClick();
5692        mLongClickX = Float.NaN;
5693        mLongClickY = Float.NaN;
5694        return handled;
5695    }
5696
5697    /**
5698     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5699     * context menu if the OnLongClickListener did not consume the event,
5700     * optionally anchoring it to an (x,y) coordinate.
5701     *
5702     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5703     *          to disable anchoring
5704     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5705     *          to disable anchoring
5706     * @return {@code true} if one of the above receivers consumed the event,
5707     *         {@code false} otherwise
5708     */
5709    private boolean performLongClickInternal(float x, float y) {
5710        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5711
5712        boolean handled = false;
5713        final ListenerInfo li = mListenerInfo;
5714        if (li != null && li.mOnLongClickListener != null) {
5715            handled = li.mOnLongClickListener.onLongClick(View.this);
5716        }
5717        if (!handled) {
5718            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5719            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5720        }
5721        if (handled) {
5722            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5723        }
5724        return handled;
5725    }
5726
5727    /**
5728     * Call this view's OnContextClickListener, if it is defined.
5729     *
5730     * @param x the x coordinate of the context click
5731     * @param y the y coordinate of the context click
5732     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5733     *         otherwise.
5734     */
5735    public boolean performContextClick(float x, float y) {
5736        return performContextClick();
5737    }
5738
5739    /**
5740     * Call this view's OnContextClickListener, if it is defined.
5741     *
5742     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5743     *         otherwise.
5744     */
5745    public boolean performContextClick() {
5746        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5747
5748        boolean handled = false;
5749        ListenerInfo li = mListenerInfo;
5750        if (li != null && li.mOnContextClickListener != null) {
5751            handled = li.mOnContextClickListener.onContextClick(View.this);
5752        }
5753        if (handled) {
5754            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5755        }
5756        return handled;
5757    }
5758
5759    /**
5760     * Performs button-related actions during a touch down event.
5761     *
5762     * @param event The event.
5763     * @return True if the down was consumed.
5764     *
5765     * @hide
5766     */
5767    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5768        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5769            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5770            showContextMenu(event.getX(), event.getY());
5771            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5772            return true;
5773        }
5774        return false;
5775    }
5776
5777    /**
5778     * Shows the context menu for this view.
5779     *
5780     * @return {@code true} if the context menu was shown, {@code false}
5781     *         otherwise
5782     * @see #showContextMenu(float, float)
5783     */
5784    public boolean showContextMenu() {
5785        return getParent().showContextMenuForChild(this);
5786    }
5787
5788    /**
5789     * Shows the context menu for this view anchored to the specified
5790     * view-relative coordinate.
5791     *
5792     * @param x the X coordinate in pixels relative to the view to which the
5793     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5794     * @param y the Y coordinate in pixels relative to the view to which the
5795     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5796     * @return {@code true} if the context menu was shown, {@code false}
5797     *         otherwise
5798     */
5799    public boolean showContextMenu(float x, float y) {
5800        return getParent().showContextMenuForChild(this, x, y);
5801    }
5802
5803    /**
5804     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5805     *
5806     * @param callback Callback that will control the lifecycle of the action mode
5807     * @return The new action mode if it is started, null otherwise
5808     *
5809     * @see ActionMode
5810     * @see #startActionMode(android.view.ActionMode.Callback, int)
5811     */
5812    public ActionMode startActionMode(ActionMode.Callback callback) {
5813        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5814    }
5815
5816    /**
5817     * Start an action mode with the given type.
5818     *
5819     * @param callback Callback that will control the lifecycle of the action mode
5820     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5821     * @return The new action mode if it is started, null otherwise
5822     *
5823     * @see ActionMode
5824     */
5825    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5826        ViewParent parent = getParent();
5827        if (parent == null) return null;
5828        try {
5829            return parent.startActionModeForChild(this, callback, type);
5830        } catch (AbstractMethodError ame) {
5831            // Older implementations of custom views might not implement this.
5832            return parent.startActionModeForChild(this, callback);
5833        }
5834    }
5835
5836    /**
5837     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5838     * Context, creating a unique View identifier to retrieve the result.
5839     *
5840     * @param intent The Intent to be started.
5841     * @param requestCode The request code to use.
5842     * @hide
5843     */
5844    public void startActivityForResult(Intent intent, int requestCode) {
5845        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5846        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5847    }
5848
5849    /**
5850     * If this View corresponds to the calling who, dispatches the activity result.
5851     * @param who The identifier for the targeted View to receive the result.
5852     * @param requestCode The integer request code originally supplied to
5853     *                    startActivityForResult(), allowing you to identify who this
5854     *                    result came from.
5855     * @param resultCode The integer result code returned by the child activity
5856     *                   through its setResult().
5857     * @param data An Intent, which can return result data to the caller
5858     *               (various data can be attached to Intent "extras").
5859     * @return {@code true} if the activity result was dispatched.
5860     * @hide
5861     */
5862    public boolean dispatchActivityResult(
5863            String who, int requestCode, int resultCode, Intent data) {
5864        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5865            onActivityResult(requestCode, resultCode, data);
5866            mStartActivityRequestWho = null;
5867            return true;
5868        }
5869        return false;
5870    }
5871
5872    /**
5873     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5874     *
5875     * @param requestCode The integer request code originally supplied to
5876     *                    startActivityForResult(), allowing you to identify who this
5877     *                    result came from.
5878     * @param resultCode The integer result code returned by the child activity
5879     *                   through its setResult().
5880     * @param data An Intent, which can return result data to the caller
5881     *               (various data can be attached to Intent "extras").
5882     * @hide
5883     */
5884    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5885        // Do nothing.
5886    }
5887
5888    /**
5889     * Register a callback to be invoked when a hardware key is pressed in this view.
5890     * Key presses in software input methods will generally not trigger the methods of
5891     * this listener.
5892     * @param l the key listener to attach to this view
5893     */
5894    public void setOnKeyListener(OnKeyListener l) {
5895        getListenerInfo().mOnKeyListener = l;
5896    }
5897
5898    /**
5899     * Register a callback to be invoked when a touch event is sent to this view.
5900     * @param l the touch listener to attach to this view
5901     */
5902    public void setOnTouchListener(OnTouchListener l) {
5903        getListenerInfo().mOnTouchListener = l;
5904    }
5905
5906    /**
5907     * Register a callback to be invoked when a generic motion event is sent to this view.
5908     * @param l the generic motion listener to attach to this view
5909     */
5910    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5911        getListenerInfo().mOnGenericMotionListener = l;
5912    }
5913
5914    /**
5915     * Register a callback to be invoked when a hover event is sent to this view.
5916     * @param l the hover listener to attach to this view
5917     */
5918    public void setOnHoverListener(OnHoverListener l) {
5919        getListenerInfo().mOnHoverListener = l;
5920    }
5921
5922    /**
5923     * Register a drag event listener callback object for this View. The parameter is
5924     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5925     * View, the system calls the
5926     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5927     * @param l An implementation of {@link android.view.View.OnDragListener}.
5928     */
5929    public void setOnDragListener(OnDragListener l) {
5930        getListenerInfo().mOnDragListener = l;
5931    }
5932
5933    /**
5934     * Give this view focus. This will cause
5935     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5936     *
5937     * Note: this does not check whether this {@link View} should get focus, it just
5938     * gives it focus no matter what.  It should only be called internally by framework
5939     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5940     *
5941     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5942     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5943     *        focus moved when requestFocus() is called. It may not always
5944     *        apply, in which case use the default View.FOCUS_DOWN.
5945     * @param previouslyFocusedRect The rectangle of the view that had focus
5946     *        prior in this View's coordinate system.
5947     */
5948    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5949        if (DBG) {
5950            System.out.println(this + " requestFocus()");
5951        }
5952
5953        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5954            mPrivateFlags |= PFLAG_FOCUSED;
5955
5956            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5957
5958            if (mParent != null) {
5959                mParent.requestChildFocus(this, this);
5960            }
5961
5962            if (mAttachInfo != null) {
5963                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5964            }
5965
5966            onFocusChanged(true, direction, previouslyFocusedRect);
5967            refreshDrawableState();
5968        }
5969    }
5970
5971    /**
5972     * Sets this view's preference for reveal behavior when it gains focus.
5973     *
5974     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
5975     * this view would prefer to be brought fully into view when it gains focus.
5976     * For example, a text field that a user is meant to type into. Other views such
5977     * as scrolling containers may prefer to opt-out of this behavior.</p>
5978     *
5979     * <p>The default value for views is true, though subclasses may change this
5980     * based on their preferred behavior.</p>
5981     *
5982     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
5983     *
5984     * @see #getRevealOnFocusHint()
5985     */
5986    public final void setRevealOnFocusHint(boolean revealOnFocus) {
5987        if (revealOnFocus) {
5988            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
5989        } else {
5990            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
5991        }
5992    }
5993
5994    /**
5995     * Returns this view's preference for reveal behavior when it gains focus.
5996     *
5997     * <p>When this method returns true for a child view requesting focus, ancestor
5998     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
5999     * should make a best effort to make the newly focused child fully visible to the user.
6000     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6001     * other properties affecting visibility to the user as part of the focus change.</p>
6002     *
6003     * @return true if this view would prefer to become fully visible when it gains focus,
6004     *         false if it would prefer not to disrupt scroll positioning
6005     *
6006     * @see #setRevealOnFocusHint(boolean)
6007     */
6008    public final boolean getRevealOnFocusHint() {
6009        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6010    }
6011
6012    /**
6013     * Populates <code>outRect</code> with the hotspot bounds. By default,
6014     * the hotspot bounds are identical to the screen bounds.
6015     *
6016     * @param outRect rect to populate with hotspot bounds
6017     * @hide Only for internal use by views and widgets.
6018     */
6019    public void getHotspotBounds(Rect outRect) {
6020        final Drawable background = getBackground();
6021        if (background != null) {
6022            background.getHotspotBounds(outRect);
6023        } else {
6024            getBoundsOnScreen(outRect);
6025        }
6026    }
6027
6028    /**
6029     * Request that a rectangle of this view be visible on the screen,
6030     * scrolling if necessary just enough.
6031     *
6032     * <p>A View should call this if it maintains some notion of which part
6033     * of its content is interesting.  For example, a text editing view
6034     * should call this when its cursor moves.
6035     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6036     * It should not be affected by which part of the View is currently visible or its scroll
6037     * position.
6038     *
6039     * @param rectangle The rectangle in the View's content coordinate space
6040     * @return Whether any parent scrolled.
6041     */
6042    public boolean requestRectangleOnScreen(Rect rectangle) {
6043        return requestRectangleOnScreen(rectangle, false);
6044    }
6045
6046    /**
6047     * Request that a rectangle of this view be visible on the screen,
6048     * scrolling if necessary just enough.
6049     *
6050     * <p>A View should call this if it maintains some notion of which part
6051     * of its content is interesting.  For example, a text editing view
6052     * should call this when its cursor moves.
6053     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6054     * It should not be affected by which part of the View is currently visible or its scroll
6055     * position.
6056     * <p>When <code>immediate</code> is set to true, scrolling will not be
6057     * animated.
6058     *
6059     * @param rectangle The rectangle in the View's content coordinate space
6060     * @param immediate True to forbid animated scrolling, false otherwise
6061     * @return Whether any parent scrolled.
6062     */
6063    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6064        if (mParent == null) {
6065            return false;
6066        }
6067
6068        View child = this;
6069
6070        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6071        position.set(rectangle);
6072
6073        ViewParent parent = mParent;
6074        boolean scrolled = false;
6075        while (parent != null) {
6076            rectangle.set((int) position.left, (int) position.top,
6077                    (int) position.right, (int) position.bottom);
6078
6079            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6080
6081            if (!(parent instanceof View)) {
6082                break;
6083            }
6084
6085            // move it from child's content coordinate space to parent's content coordinate space
6086            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6087
6088            child = (View) parent;
6089            parent = child.getParent();
6090        }
6091
6092        return scrolled;
6093    }
6094
6095    /**
6096     * Called when this view wants to give up focus. If focus is cleared
6097     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6098     * <p>
6099     * <strong>Note:</strong> When a View clears focus the framework is trying
6100     * to give focus to the first focusable View from the top. Hence, if this
6101     * View is the first from the top that can take focus, then all callbacks
6102     * related to clearing focus will be invoked after which the framework will
6103     * give focus to this view.
6104     * </p>
6105     */
6106    public void clearFocus() {
6107        if (DBG) {
6108            System.out.println(this + " clearFocus()");
6109        }
6110
6111        clearFocusInternal(null, true, true);
6112    }
6113
6114    /**
6115     * Clears focus from the view, optionally propagating the change up through
6116     * the parent hierarchy and requesting that the root view place new focus.
6117     *
6118     * @param propagate whether to propagate the change up through the parent
6119     *            hierarchy
6120     * @param refocus when propagate is true, specifies whether to request the
6121     *            root view place new focus
6122     */
6123    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6124        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6125            mPrivateFlags &= ~PFLAG_FOCUSED;
6126
6127            if (propagate && mParent != null) {
6128                mParent.clearChildFocus(this);
6129            }
6130
6131            onFocusChanged(false, 0, null);
6132            refreshDrawableState();
6133
6134            if (propagate && (!refocus || !rootViewRequestFocus())) {
6135                notifyGlobalFocusCleared(this);
6136            }
6137        }
6138    }
6139
6140    void notifyGlobalFocusCleared(View oldFocus) {
6141        if (oldFocus != null && mAttachInfo != null) {
6142            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6143        }
6144    }
6145
6146    boolean rootViewRequestFocus() {
6147        final View root = getRootView();
6148        return root != null && root.requestFocus();
6149    }
6150
6151    /**
6152     * Called internally by the view system when a new view is getting focus.
6153     * This is what clears the old focus.
6154     * <p>
6155     * <b>NOTE:</b> The parent view's focused child must be updated manually
6156     * after calling this method. Otherwise, the view hierarchy may be left in
6157     * an inconstent state.
6158     */
6159    void unFocus(View focused) {
6160        if (DBG) {
6161            System.out.println(this + " unFocus()");
6162        }
6163
6164        clearFocusInternal(focused, false, false);
6165    }
6166
6167    /**
6168     * Returns true if this view has focus itself, or is the ancestor of the
6169     * view that has focus.
6170     *
6171     * @return True if this view has or contains focus, false otherwise.
6172     */
6173    @ViewDebug.ExportedProperty(category = "focus")
6174    public boolean hasFocus() {
6175        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6176    }
6177
6178    /**
6179     * Returns true if this view is focusable or if it contains a reachable View
6180     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6181     * is a View whose parents do not block descendants focus.
6182     *
6183     * Only {@link #VISIBLE} views are considered focusable.
6184     *
6185     * @return True if the view is focusable or if the view contains a focusable
6186     *         View, false otherwise.
6187     *
6188     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6189     * @see ViewGroup#getTouchscreenBlocksFocus()
6190     */
6191    public boolean hasFocusable() {
6192        if (!isFocusableInTouchMode()) {
6193            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6194                final ViewGroup g = (ViewGroup) p;
6195                if (g.shouldBlockFocusForTouchscreen()) {
6196                    return false;
6197                }
6198            }
6199        }
6200        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6201    }
6202
6203    /**
6204     * Called by the view system when the focus state of this view changes.
6205     * When the focus change event is caused by directional navigation, direction
6206     * and previouslyFocusedRect provide insight into where the focus is coming from.
6207     * When overriding, be sure to call up through to the super class so that
6208     * the standard focus handling will occur.
6209     *
6210     * @param gainFocus True if the View has focus; false otherwise.
6211     * @param direction The direction focus has moved when requestFocus()
6212     *                  is called to give this view focus. Values are
6213     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6214     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6215     *                  It may not always apply, in which case use the default.
6216     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6217     *        system, of the previously focused view.  If applicable, this will be
6218     *        passed in as finer grained information about where the focus is coming
6219     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6220     */
6221    @CallSuper
6222    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6223            @Nullable Rect previouslyFocusedRect) {
6224        if (gainFocus) {
6225            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6226        } else {
6227            notifyViewAccessibilityStateChangedIfNeeded(
6228                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6229        }
6230
6231        InputMethodManager imm = InputMethodManager.peekInstance();
6232        if (!gainFocus) {
6233            if (isPressed()) {
6234                setPressed(false);
6235            }
6236            if (imm != null && mAttachInfo != null
6237                    && mAttachInfo.mHasWindowFocus) {
6238                imm.focusOut(this);
6239            }
6240            onFocusLost();
6241        } else if (imm != null && mAttachInfo != null
6242                && mAttachInfo.mHasWindowFocus) {
6243            imm.focusIn(this);
6244        }
6245
6246        invalidate(true);
6247        ListenerInfo li = mListenerInfo;
6248        if (li != null && li.mOnFocusChangeListener != null) {
6249            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6250        }
6251
6252        if (mAttachInfo != null) {
6253            mAttachInfo.mKeyDispatchState.reset(this);
6254        }
6255    }
6256
6257    /**
6258     * Sends an accessibility event of the given type. If accessibility is
6259     * not enabled this method has no effect. The default implementation calls
6260     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6261     * to populate information about the event source (this View), then calls
6262     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6263     * populate the text content of the event source including its descendants,
6264     * and last calls
6265     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6266     * on its parent to request sending of the event to interested parties.
6267     * <p>
6268     * If an {@link AccessibilityDelegate} has been specified via calling
6269     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6270     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6271     * responsible for handling this call.
6272     * </p>
6273     *
6274     * @param eventType The type of the event to send, as defined by several types from
6275     * {@link android.view.accessibility.AccessibilityEvent}, such as
6276     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6277     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6278     *
6279     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6280     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6281     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6282     * @see AccessibilityDelegate
6283     */
6284    public void sendAccessibilityEvent(int eventType) {
6285        if (mAccessibilityDelegate != null) {
6286            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6287        } else {
6288            sendAccessibilityEventInternal(eventType);
6289        }
6290    }
6291
6292    /**
6293     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6294     * {@link AccessibilityEvent} to make an announcement which is related to some
6295     * sort of a context change for which none of the events representing UI transitions
6296     * is a good fit. For example, announcing a new page in a book. If accessibility
6297     * is not enabled this method does nothing.
6298     *
6299     * @param text The announcement text.
6300     */
6301    public void announceForAccessibility(CharSequence text) {
6302        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6303            AccessibilityEvent event = AccessibilityEvent.obtain(
6304                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6305            onInitializeAccessibilityEvent(event);
6306            event.getText().add(text);
6307            event.setContentDescription(null);
6308            mParent.requestSendAccessibilityEvent(this, event);
6309        }
6310    }
6311
6312    /**
6313     * @see #sendAccessibilityEvent(int)
6314     *
6315     * Note: Called from the default {@link AccessibilityDelegate}.
6316     *
6317     * @hide
6318     */
6319    public void sendAccessibilityEventInternal(int eventType) {
6320        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6321            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6322        }
6323    }
6324
6325    /**
6326     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6327     * takes as an argument an empty {@link AccessibilityEvent} and does not
6328     * perform a check whether accessibility is enabled.
6329     * <p>
6330     * If an {@link AccessibilityDelegate} has been specified via calling
6331     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6332     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6333     * is responsible for handling this call.
6334     * </p>
6335     *
6336     * @param event The event to send.
6337     *
6338     * @see #sendAccessibilityEvent(int)
6339     */
6340    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6341        if (mAccessibilityDelegate != null) {
6342            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6343        } else {
6344            sendAccessibilityEventUncheckedInternal(event);
6345        }
6346    }
6347
6348    /**
6349     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6350     *
6351     * Note: Called from the default {@link AccessibilityDelegate}.
6352     *
6353     * @hide
6354     */
6355    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6356        if (!isShown()) {
6357            return;
6358        }
6359        onInitializeAccessibilityEvent(event);
6360        // Only a subset of accessibility events populates text content.
6361        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6362            dispatchPopulateAccessibilityEvent(event);
6363        }
6364        // In the beginning we called #isShown(), so we know that getParent() is not null.
6365        getParent().requestSendAccessibilityEvent(this, event);
6366    }
6367
6368    /**
6369     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6370     * to its children for adding their text content to the event. Note that the
6371     * event text is populated in a separate dispatch path since we add to the
6372     * event not only the text of the source but also the text of all its descendants.
6373     * A typical implementation will call
6374     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6375     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6376     * on each child. Override this method if custom population of the event text
6377     * content is required.
6378     * <p>
6379     * If an {@link AccessibilityDelegate} has been specified via calling
6380     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6381     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6382     * is responsible for handling this call.
6383     * </p>
6384     * <p>
6385     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6386     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6387     * </p>
6388     *
6389     * @param event The event.
6390     *
6391     * @return True if the event population was completed.
6392     */
6393    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6394        if (mAccessibilityDelegate != null) {
6395            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6396        } else {
6397            return dispatchPopulateAccessibilityEventInternal(event);
6398        }
6399    }
6400
6401    /**
6402     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6403     *
6404     * Note: Called from the default {@link AccessibilityDelegate}.
6405     *
6406     * @hide
6407     */
6408    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6409        onPopulateAccessibilityEvent(event);
6410        return false;
6411    }
6412
6413    /**
6414     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6415     * giving a chance to this View to populate the accessibility event with its
6416     * text content. While this method is free to modify event
6417     * attributes other than text content, doing so should normally be performed in
6418     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6419     * <p>
6420     * Example: Adding formatted date string to an accessibility event in addition
6421     *          to the text added by the super implementation:
6422     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6423     *     super.onPopulateAccessibilityEvent(event);
6424     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6425     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6426     *         mCurrentDate.getTimeInMillis(), flags);
6427     *     event.getText().add(selectedDateUtterance);
6428     * }</pre>
6429     * <p>
6430     * If an {@link AccessibilityDelegate} has been specified via calling
6431     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6432     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6433     * is responsible for handling this call.
6434     * </p>
6435     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6436     * information to the event, in case the default implementation has basic information to add.
6437     * </p>
6438     *
6439     * @param event The accessibility event which to populate.
6440     *
6441     * @see #sendAccessibilityEvent(int)
6442     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6443     */
6444    @CallSuper
6445    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6446        if (mAccessibilityDelegate != null) {
6447            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6448        } else {
6449            onPopulateAccessibilityEventInternal(event);
6450        }
6451    }
6452
6453    /**
6454     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6455     *
6456     * Note: Called from the default {@link AccessibilityDelegate}.
6457     *
6458     * @hide
6459     */
6460    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6461    }
6462
6463    /**
6464     * Initializes an {@link AccessibilityEvent} with information about
6465     * this View which is the event source. In other words, the source of
6466     * an accessibility event is the view whose state change triggered firing
6467     * the event.
6468     * <p>
6469     * Example: Setting the password property of an event in addition
6470     *          to properties set by the super implementation:
6471     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6472     *     super.onInitializeAccessibilityEvent(event);
6473     *     event.setPassword(true);
6474     * }</pre>
6475     * <p>
6476     * If an {@link AccessibilityDelegate} has been specified via calling
6477     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6478     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6479     * is responsible for handling this call.
6480     * </p>
6481     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6482     * information to the event, in case the default implementation has basic information to add.
6483     * </p>
6484     * @param event The event to initialize.
6485     *
6486     * @see #sendAccessibilityEvent(int)
6487     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6488     */
6489    @CallSuper
6490    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6491        if (mAccessibilityDelegate != null) {
6492            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6493        } else {
6494            onInitializeAccessibilityEventInternal(event);
6495        }
6496    }
6497
6498    /**
6499     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6500     *
6501     * Note: Called from the default {@link AccessibilityDelegate}.
6502     *
6503     * @hide
6504     */
6505    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6506        event.setSource(this);
6507        event.setClassName(getAccessibilityClassName());
6508        event.setPackageName(getContext().getPackageName());
6509        event.setEnabled(isEnabled());
6510        event.setContentDescription(mContentDescription);
6511
6512        switch (event.getEventType()) {
6513            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6514                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6515                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6516                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6517                event.setItemCount(focusablesTempList.size());
6518                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6519                if (mAttachInfo != null) {
6520                    focusablesTempList.clear();
6521                }
6522            } break;
6523            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6524                CharSequence text = getIterableTextForAccessibility();
6525                if (text != null && text.length() > 0) {
6526                    event.setFromIndex(getAccessibilitySelectionStart());
6527                    event.setToIndex(getAccessibilitySelectionEnd());
6528                    event.setItemCount(text.length());
6529                }
6530            } break;
6531        }
6532    }
6533
6534    /**
6535     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6536     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6537     * This method is responsible for obtaining an accessibility node info from a
6538     * pool of reusable instances and calling
6539     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6540     * initialize the former.
6541     * <p>
6542     * Note: The client is responsible for recycling the obtained instance by calling
6543     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6544     * </p>
6545     *
6546     * @return A populated {@link AccessibilityNodeInfo}.
6547     *
6548     * @see AccessibilityNodeInfo
6549     */
6550    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6551        if (mAccessibilityDelegate != null) {
6552            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6553        } else {
6554            return createAccessibilityNodeInfoInternal();
6555        }
6556    }
6557
6558    /**
6559     * @see #createAccessibilityNodeInfo()
6560     *
6561     * @hide
6562     */
6563    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6564        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6565        if (provider != null) {
6566            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6567        } else {
6568            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6569            onInitializeAccessibilityNodeInfo(info);
6570            return info;
6571        }
6572    }
6573
6574    /**
6575     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6576     * The base implementation sets:
6577     * <ul>
6578     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6579     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6580     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6581     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6582     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6583     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6584     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6585     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6586     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6587     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6588     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6589     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6590     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6591     * </ul>
6592     * <p>
6593     * Subclasses should override this method, call the super implementation,
6594     * and set additional attributes.
6595     * </p>
6596     * <p>
6597     * If an {@link AccessibilityDelegate} has been specified via calling
6598     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6599     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6600     * is responsible for handling this call.
6601     * </p>
6602     *
6603     * @param info The instance to initialize.
6604     */
6605    @CallSuper
6606    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6607        if (mAccessibilityDelegate != null) {
6608            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6609        } else {
6610            onInitializeAccessibilityNodeInfoInternal(info);
6611        }
6612    }
6613
6614    /**
6615     * Gets the location of this view in screen coordinates.
6616     *
6617     * @param outRect The output location
6618     * @hide
6619     */
6620    public void getBoundsOnScreen(Rect outRect) {
6621        getBoundsOnScreen(outRect, false);
6622    }
6623
6624    /**
6625     * Gets the location of this view in screen coordinates.
6626     *
6627     * @param outRect The output location
6628     * @param clipToParent Whether to clip child bounds to the parent ones.
6629     * @hide
6630     */
6631    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6632        if (mAttachInfo == null) {
6633            return;
6634        }
6635
6636        RectF position = mAttachInfo.mTmpTransformRect;
6637        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6638
6639        if (!hasIdentityMatrix()) {
6640            getMatrix().mapRect(position);
6641        }
6642
6643        position.offset(mLeft, mTop);
6644
6645        ViewParent parent = mParent;
6646        while (parent instanceof View) {
6647            View parentView = (View) parent;
6648
6649            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6650
6651            if (clipToParent) {
6652                position.left = Math.max(position.left, 0);
6653                position.top = Math.max(position.top, 0);
6654                position.right = Math.min(position.right, parentView.getWidth());
6655                position.bottom = Math.min(position.bottom, parentView.getHeight());
6656            }
6657
6658            if (!parentView.hasIdentityMatrix()) {
6659                parentView.getMatrix().mapRect(position);
6660            }
6661
6662            position.offset(parentView.mLeft, parentView.mTop);
6663
6664            parent = parentView.mParent;
6665        }
6666
6667        if (parent instanceof ViewRootImpl) {
6668            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6669            position.offset(0, -viewRootImpl.mCurScrollY);
6670        }
6671
6672        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6673
6674        outRect.set(Math.round(position.left), Math.round(position.top),
6675                Math.round(position.right), Math.round(position.bottom));
6676    }
6677
6678    /**
6679     * Return the class name of this object to be used for accessibility purposes.
6680     * Subclasses should only override this if they are implementing something that
6681     * should be seen as a completely new class of view when used by accessibility,
6682     * unrelated to the class it is deriving from.  This is used to fill in
6683     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6684     */
6685    public CharSequence getAccessibilityClassName() {
6686        return View.class.getName();
6687    }
6688
6689    /**
6690     * Called when assist structure is being retrieved from a view as part of
6691     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6692     * @param structure Fill in with structured view data.  The default implementation
6693     * fills in all data that can be inferred from the view itself.
6694     */
6695    public void onProvideStructure(ViewStructure structure) {
6696        final int id = mID;
6697        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6698                && (id&0x0000ffff) != 0) {
6699            String pkg, type, entry;
6700            try {
6701                final Resources res = getResources();
6702                entry = res.getResourceEntryName(id);
6703                type = res.getResourceTypeName(id);
6704                pkg = res.getResourcePackageName(id);
6705            } catch (Resources.NotFoundException e) {
6706                entry = type = pkg = null;
6707            }
6708            structure.setId(id, pkg, type, entry);
6709        } else {
6710            structure.setId(id, null, null, null);
6711        }
6712        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6713        if (!hasIdentityMatrix()) {
6714            structure.setTransformation(getMatrix());
6715        }
6716        structure.setElevation(getZ());
6717        structure.setVisibility(getVisibility());
6718        structure.setEnabled(isEnabled());
6719        if (isClickable()) {
6720            structure.setClickable(true);
6721        }
6722        if (isFocusable()) {
6723            structure.setFocusable(true);
6724        }
6725        if (isFocused()) {
6726            structure.setFocused(true);
6727        }
6728        if (isAccessibilityFocused()) {
6729            structure.setAccessibilityFocused(true);
6730        }
6731        if (isSelected()) {
6732            structure.setSelected(true);
6733        }
6734        if (isActivated()) {
6735            structure.setActivated(true);
6736        }
6737        if (isLongClickable()) {
6738            structure.setLongClickable(true);
6739        }
6740        if (this instanceof Checkable) {
6741            structure.setCheckable(true);
6742            if (((Checkable)this).isChecked()) {
6743                structure.setChecked(true);
6744            }
6745        }
6746        if (isContextClickable()) {
6747            structure.setContextClickable(true);
6748        }
6749        structure.setClassName(getAccessibilityClassName().toString());
6750        structure.setContentDescription(getContentDescription());
6751    }
6752
6753    /**
6754     * Called when assist structure is being retrieved from a view as part of
6755     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6756     * generate additional virtual structure under this view.  The defaullt implementation
6757     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6758     * view's virtual accessibility nodes, if any.  You can override this for a more
6759     * optimal implementation providing this data.
6760     */
6761    public void onProvideVirtualStructure(ViewStructure structure) {
6762        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6763        if (provider != null) {
6764            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6765            structure.setChildCount(1);
6766            ViewStructure root = structure.newChild(0);
6767            populateVirtualStructure(root, provider, info);
6768            info.recycle();
6769        }
6770    }
6771
6772    private void populateVirtualStructure(ViewStructure structure,
6773            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6774        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6775                null, null, null);
6776        Rect rect = structure.getTempRect();
6777        info.getBoundsInParent(rect);
6778        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6779        structure.setVisibility(VISIBLE);
6780        structure.setEnabled(info.isEnabled());
6781        if (info.isClickable()) {
6782            structure.setClickable(true);
6783        }
6784        if (info.isFocusable()) {
6785            structure.setFocusable(true);
6786        }
6787        if (info.isFocused()) {
6788            structure.setFocused(true);
6789        }
6790        if (info.isAccessibilityFocused()) {
6791            structure.setAccessibilityFocused(true);
6792        }
6793        if (info.isSelected()) {
6794            structure.setSelected(true);
6795        }
6796        if (info.isLongClickable()) {
6797            structure.setLongClickable(true);
6798        }
6799        if (info.isCheckable()) {
6800            structure.setCheckable(true);
6801            if (info.isChecked()) {
6802                structure.setChecked(true);
6803            }
6804        }
6805        if (info.isContextClickable()) {
6806            structure.setContextClickable(true);
6807        }
6808        CharSequence cname = info.getClassName();
6809        structure.setClassName(cname != null ? cname.toString() : null);
6810        structure.setContentDescription(info.getContentDescription());
6811        if (info.getText() != null || info.getError() != null) {
6812            structure.setText(info.getText(), info.getTextSelectionStart(),
6813                    info.getTextSelectionEnd());
6814        }
6815        final int NCHILDREN = info.getChildCount();
6816        if (NCHILDREN > 0) {
6817            structure.setChildCount(NCHILDREN);
6818            for (int i=0; i<NCHILDREN; i++) {
6819                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6820                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6821                ViewStructure child = structure.newChild(i);
6822                populateVirtualStructure(child, provider, cinfo);
6823                cinfo.recycle();
6824            }
6825        }
6826    }
6827
6828    /**
6829     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6830     * implementation calls {@link #onProvideStructure} and
6831     * {@link #onProvideVirtualStructure}.
6832     */
6833    public void dispatchProvideStructure(ViewStructure structure) {
6834        if (!isAssistBlocked()) {
6835            onProvideStructure(structure);
6836            onProvideVirtualStructure(structure);
6837        } else {
6838            structure.setClassName(getAccessibilityClassName().toString());
6839            structure.setAssistBlocked(true);
6840        }
6841    }
6842
6843    /**
6844     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6845     *
6846     * Note: Called from the default {@link AccessibilityDelegate}.
6847     *
6848     * @hide
6849     */
6850    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6851        if (mAttachInfo == null) {
6852            return;
6853        }
6854
6855        Rect bounds = mAttachInfo.mTmpInvalRect;
6856
6857        getDrawingRect(bounds);
6858        info.setBoundsInParent(bounds);
6859
6860        getBoundsOnScreen(bounds, true);
6861        info.setBoundsInScreen(bounds);
6862
6863        ViewParent parent = getParentForAccessibility();
6864        if (parent instanceof View) {
6865            info.setParent((View) parent);
6866        }
6867
6868        if (mID != View.NO_ID) {
6869            View rootView = getRootView();
6870            if (rootView == null) {
6871                rootView = this;
6872            }
6873
6874            View label = rootView.findLabelForView(this, mID);
6875            if (label != null) {
6876                info.setLabeledBy(label);
6877            }
6878
6879            if ((mAttachInfo.mAccessibilityFetchFlags
6880                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6881                    && Resources.resourceHasPackage(mID)) {
6882                try {
6883                    String viewId = getResources().getResourceName(mID);
6884                    info.setViewIdResourceName(viewId);
6885                } catch (Resources.NotFoundException nfe) {
6886                    /* ignore */
6887                }
6888            }
6889        }
6890
6891        if (mLabelForId != View.NO_ID) {
6892            View rootView = getRootView();
6893            if (rootView == null) {
6894                rootView = this;
6895            }
6896            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6897            if (labeled != null) {
6898                info.setLabelFor(labeled);
6899            }
6900        }
6901
6902        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6903            View rootView = getRootView();
6904            if (rootView == null) {
6905                rootView = this;
6906            }
6907            View next = rootView.findViewInsideOutShouldExist(this,
6908                    mAccessibilityTraversalBeforeId);
6909            if (next != null && next.includeForAccessibility()) {
6910                info.setTraversalBefore(next);
6911            }
6912        }
6913
6914        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6915            View rootView = getRootView();
6916            if (rootView == null) {
6917                rootView = this;
6918            }
6919            View next = rootView.findViewInsideOutShouldExist(this,
6920                    mAccessibilityTraversalAfterId);
6921            if (next != null && next.includeForAccessibility()) {
6922                info.setTraversalAfter(next);
6923            }
6924        }
6925
6926        info.setVisibleToUser(isVisibleToUser());
6927
6928        if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags
6929                & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) {
6930            info.setImportantForAccessibility(isImportantForAccessibility());
6931        } else {
6932            info.setImportantForAccessibility(true);
6933        }
6934
6935        info.setPackageName(mContext.getPackageName());
6936        info.setClassName(getAccessibilityClassName());
6937        info.setContentDescription(getContentDescription());
6938
6939        info.setEnabled(isEnabled());
6940        info.setClickable(isClickable());
6941        info.setFocusable(isFocusable());
6942        info.setFocused(isFocused());
6943        info.setAccessibilityFocused(isAccessibilityFocused());
6944        info.setSelected(isSelected());
6945        info.setLongClickable(isLongClickable());
6946        info.setContextClickable(isContextClickable());
6947        info.setLiveRegion(getAccessibilityLiveRegion());
6948
6949        // TODO: These make sense only if we are in an AdapterView but all
6950        // views can be selected. Maybe from accessibility perspective
6951        // we should report as selectable view in an AdapterView.
6952        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6953        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6954
6955        if (isFocusable()) {
6956            if (isFocused()) {
6957                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6958            } else {
6959                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6960            }
6961        }
6962
6963        if (!isAccessibilityFocused()) {
6964            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6965        } else {
6966            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6967        }
6968
6969        if (isClickable() && isEnabled()) {
6970            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6971        }
6972
6973        if (isLongClickable() && isEnabled()) {
6974            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6975        }
6976
6977        if (isContextClickable() && isEnabled()) {
6978            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6979        }
6980
6981        CharSequence text = getIterableTextForAccessibility();
6982        if (text != null && text.length() > 0) {
6983            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6984
6985            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6986            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6987            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6988            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6989                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6990                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6991        }
6992
6993        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6994        populateAccessibilityNodeInfoDrawingOrderInParent(info);
6995    }
6996
6997    /**
6998     * Determine the order in which this view will be drawn relative to its siblings for a11y
6999     *
7000     * @param info The info whose drawing order should be populated
7001     */
7002    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7003        /*
7004         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7005         * drawing order may not be well-defined, and some Views with custom drawing order may
7006         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7007         */
7008        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7009            info.setDrawingOrder(0);
7010            return;
7011        }
7012        int drawingOrderInParent = 1;
7013        // Iterate up the hierarchy if parents are not important for a11y
7014        View viewAtDrawingLevel = this;
7015        final ViewParent parent = getParentForAccessibility();
7016        while (viewAtDrawingLevel != parent) {
7017            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7018            if (!(currentParent instanceof ViewGroup)) {
7019                // Should only happen for the Decor
7020                drawingOrderInParent = 0;
7021                break;
7022            } else {
7023                final ViewGroup parentGroup = (ViewGroup) currentParent;
7024                final int childCount = parentGroup.getChildCount();
7025                if (childCount > 1) {
7026                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7027                    if (preorderedList != null) {
7028                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7029                        for (int i = 0; i < childDrawIndex; i++) {
7030                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7031                        }
7032                    } else {
7033                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7034                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7035                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7036                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7037                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7038                        if (childDrawIndex != 0) {
7039                            for (int i = 0; i < numChildrenToIterate; i++) {
7040                                final int otherDrawIndex = (customOrder ?
7041                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7042                                if (otherDrawIndex < childDrawIndex) {
7043                                    drawingOrderInParent +=
7044                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7045                                }
7046                            }
7047                        }
7048                    }
7049                }
7050            }
7051            viewAtDrawingLevel = (View) currentParent;
7052        }
7053        info.setDrawingOrder(drawingOrderInParent);
7054    }
7055
7056    private static int numViewsForAccessibility(View view) {
7057        if (view != null) {
7058            if (view.includeForAccessibility()) {
7059                return 1;
7060            } else if (view instanceof ViewGroup) {
7061                return ((ViewGroup) view).getNumChildrenForAccessibility();
7062            }
7063        }
7064        return 0;
7065    }
7066
7067    private View findLabelForView(View view, int labeledId) {
7068        if (mMatchLabelForPredicate == null) {
7069            mMatchLabelForPredicate = new MatchLabelForPredicate();
7070        }
7071        mMatchLabelForPredicate.mLabeledId = labeledId;
7072        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7073    }
7074
7075    /**
7076     * Computes whether this view is visible to the user. Such a view is
7077     * attached, visible, all its predecessors are visible, it is not clipped
7078     * entirely by its predecessors, and has an alpha greater than zero.
7079     *
7080     * @return Whether the view is visible on the screen.
7081     *
7082     * @hide
7083     */
7084    protected boolean isVisibleToUser() {
7085        return isVisibleToUser(null);
7086    }
7087
7088    /**
7089     * Computes whether the given portion of this view is visible to the user.
7090     * Such a view is attached, visible, all its predecessors are visible,
7091     * has an alpha greater than zero, and the specified portion is not
7092     * clipped entirely by its predecessors.
7093     *
7094     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7095     *                    <code>null</code>, and the entire view will be tested in this case.
7096     *                    When <code>true</code> is returned by the function, the actual visible
7097     *                    region will be stored in this parameter; that is, if boundInView is fully
7098     *                    contained within the view, no modification will be made, otherwise regions
7099     *                    outside of the visible area of the view will be clipped.
7100     *
7101     * @return Whether the specified portion of the view is visible on the screen.
7102     *
7103     * @hide
7104     */
7105    protected boolean isVisibleToUser(Rect boundInView) {
7106        if (mAttachInfo != null) {
7107            // Attached to invisible window means this view is not visible.
7108            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7109                return false;
7110            }
7111            // An invisible predecessor or one with alpha zero means
7112            // that this view is not visible to the user.
7113            Object current = this;
7114            while (current instanceof View) {
7115                View view = (View) current;
7116                // We have attach info so this view is attached and there is no
7117                // need to check whether we reach to ViewRootImpl on the way up.
7118                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7119                        view.getVisibility() != VISIBLE) {
7120                    return false;
7121                }
7122                current = view.mParent;
7123            }
7124            // Check if the view is entirely covered by its predecessors.
7125            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7126            Point offset = mAttachInfo.mPoint;
7127            if (!getGlobalVisibleRect(visibleRect, offset)) {
7128                return false;
7129            }
7130            // Check if the visible portion intersects the rectangle of interest.
7131            if (boundInView != null) {
7132                visibleRect.offset(-offset.x, -offset.y);
7133                return boundInView.intersect(visibleRect);
7134            }
7135            return true;
7136        }
7137        return false;
7138    }
7139
7140    /**
7141     * Returns the delegate for implementing accessibility support via
7142     * composition. For more details see {@link AccessibilityDelegate}.
7143     *
7144     * @return The delegate, or null if none set.
7145     *
7146     * @hide
7147     */
7148    public AccessibilityDelegate getAccessibilityDelegate() {
7149        return mAccessibilityDelegate;
7150    }
7151
7152    /**
7153     * Sets a delegate for implementing accessibility support via composition
7154     * (as opposed to inheritance). For more details, see
7155     * {@link AccessibilityDelegate}.
7156     * <p>
7157     * <strong>Note:</strong> On platform versions prior to
7158     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7159     * views in the {@code android.widget.*} package are called <i>before</i>
7160     * host methods. This prevents certain properties such as class name from
7161     * being modified by overriding
7162     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7163     * as any changes will be overwritten by the host class.
7164     * <p>
7165     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7166     * methods are called <i>after</i> host methods, which all properties to be
7167     * modified without being overwritten by the host class.
7168     *
7169     * @param delegate the object to which accessibility method calls should be
7170     *                 delegated
7171     * @see AccessibilityDelegate
7172     */
7173    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7174        mAccessibilityDelegate = delegate;
7175    }
7176
7177    /**
7178     * Gets the provider for managing a virtual view hierarchy rooted at this View
7179     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7180     * that explore the window content.
7181     * <p>
7182     * If this method returns an instance, this instance is responsible for managing
7183     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7184     * View including the one representing the View itself. Similarly the returned
7185     * instance is responsible for performing accessibility actions on any virtual
7186     * view or the root view itself.
7187     * </p>
7188     * <p>
7189     * If an {@link AccessibilityDelegate} has been specified via calling
7190     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7191     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7192     * is responsible for handling this call.
7193     * </p>
7194     *
7195     * @return The provider.
7196     *
7197     * @see AccessibilityNodeProvider
7198     */
7199    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7200        if (mAccessibilityDelegate != null) {
7201            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7202        } else {
7203            return null;
7204        }
7205    }
7206
7207    /**
7208     * Gets the unique identifier of this view on the screen for accessibility purposes.
7209     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
7210     *
7211     * @return The view accessibility id.
7212     *
7213     * @hide
7214     */
7215    public int getAccessibilityViewId() {
7216        if (mAccessibilityViewId == NO_ID) {
7217            mAccessibilityViewId = sNextAccessibilityViewId++;
7218        }
7219        return mAccessibilityViewId;
7220    }
7221
7222    /**
7223     * Gets the unique identifier of the window in which this View reseides.
7224     *
7225     * @return The window accessibility id.
7226     *
7227     * @hide
7228     */
7229    public int getAccessibilityWindowId() {
7230        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7231                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7232    }
7233
7234    /**
7235     * Returns the {@link View}'s content description.
7236     * <p>
7237     * <strong>Note:</strong> Do not override this method, as it will have no
7238     * effect on the content description presented to accessibility services.
7239     * You must call {@link #setContentDescription(CharSequence)} to modify the
7240     * content description.
7241     *
7242     * @return the content description
7243     * @see #setContentDescription(CharSequence)
7244     * @attr ref android.R.styleable#View_contentDescription
7245     */
7246    @ViewDebug.ExportedProperty(category = "accessibility")
7247    public CharSequence getContentDescription() {
7248        return mContentDescription;
7249    }
7250
7251    /**
7252     * Sets the {@link View}'s content description.
7253     * <p>
7254     * A content description briefly describes the view and is primarily used
7255     * for accessibility support to determine how a view should be presented to
7256     * the user. In the case of a view with no textual representation, such as
7257     * {@link android.widget.ImageButton}, a useful content description
7258     * explains what the view does. For example, an image button with a phone
7259     * icon that is used to place a call may use "Call" as its content
7260     * description. An image of a floppy disk that is used to save a file may
7261     * use "Save".
7262     *
7263     * @param contentDescription The content description.
7264     * @see #getContentDescription()
7265     * @attr ref android.R.styleable#View_contentDescription
7266     */
7267    @RemotableViewMethod
7268    public void setContentDescription(CharSequence contentDescription) {
7269        if (mContentDescription == null) {
7270            if (contentDescription == null) {
7271                return;
7272            }
7273        } else if (mContentDescription.equals(contentDescription)) {
7274            return;
7275        }
7276        mContentDescription = contentDescription;
7277        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7278        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7279            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7280            notifySubtreeAccessibilityStateChangedIfNeeded();
7281        } else {
7282            notifyViewAccessibilityStateChangedIfNeeded(
7283                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7284        }
7285    }
7286
7287    /**
7288     * Sets the id of a view before which this one is visited in accessibility traversal.
7289     * A screen-reader must visit the content of this view before the content of the one
7290     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7291     * will traverse the entire content of B before traversing the entire content of A,
7292     * regardles of what traversal strategy it is using.
7293     * <p>
7294     * Views that do not have specified before/after relationships are traversed in order
7295     * determined by the screen-reader.
7296     * </p>
7297     * <p>
7298     * Setting that this view is before a view that is not important for accessibility
7299     * or if this view is not important for accessibility will have no effect as the
7300     * screen-reader is not aware of unimportant views.
7301     * </p>
7302     *
7303     * @param beforeId The id of a view this one precedes in accessibility traversal.
7304     *
7305     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7306     *
7307     * @see #setImportantForAccessibility(int)
7308     */
7309    @RemotableViewMethod
7310    public void setAccessibilityTraversalBefore(int beforeId) {
7311        if (mAccessibilityTraversalBeforeId == beforeId) {
7312            return;
7313        }
7314        mAccessibilityTraversalBeforeId = beforeId;
7315        notifyViewAccessibilityStateChangedIfNeeded(
7316                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7317    }
7318
7319    /**
7320     * Gets the id of a view before which this one is visited in accessibility traversal.
7321     *
7322     * @return The id of a view this one precedes in accessibility traversal if
7323     *         specified, otherwise {@link #NO_ID}.
7324     *
7325     * @see #setAccessibilityTraversalBefore(int)
7326     */
7327    public int getAccessibilityTraversalBefore() {
7328        return mAccessibilityTraversalBeforeId;
7329    }
7330
7331    /**
7332     * Sets the id of a view after which this one is visited in accessibility traversal.
7333     * A screen-reader must visit the content of the other view before the content of this
7334     * one. For example, if view B is set to be after view A, then a screen-reader
7335     * will traverse the entire content of A before traversing the entire content of B,
7336     * regardles of what traversal strategy it is using.
7337     * <p>
7338     * Views that do not have specified before/after relationships are traversed in order
7339     * determined by the screen-reader.
7340     * </p>
7341     * <p>
7342     * Setting that this view is after a view that is not important for accessibility
7343     * or if this view is not important for accessibility will have no effect as the
7344     * screen-reader is not aware of unimportant views.
7345     * </p>
7346     *
7347     * @param afterId The id of a view this one succedees in accessibility traversal.
7348     *
7349     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7350     *
7351     * @see #setImportantForAccessibility(int)
7352     */
7353    @RemotableViewMethod
7354    public void setAccessibilityTraversalAfter(int afterId) {
7355        if (mAccessibilityTraversalAfterId == afterId) {
7356            return;
7357        }
7358        mAccessibilityTraversalAfterId = afterId;
7359        notifyViewAccessibilityStateChangedIfNeeded(
7360                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7361    }
7362
7363    /**
7364     * Gets the id of a view after which this one is visited in accessibility traversal.
7365     *
7366     * @return The id of a view this one succeedes in accessibility traversal if
7367     *         specified, otherwise {@link #NO_ID}.
7368     *
7369     * @see #setAccessibilityTraversalAfter(int)
7370     */
7371    public int getAccessibilityTraversalAfter() {
7372        return mAccessibilityTraversalAfterId;
7373    }
7374
7375    /**
7376     * Gets the id of a view for which this view serves as a label for
7377     * accessibility purposes.
7378     *
7379     * @return The labeled view id.
7380     */
7381    @ViewDebug.ExportedProperty(category = "accessibility")
7382    public int getLabelFor() {
7383        return mLabelForId;
7384    }
7385
7386    /**
7387     * Sets the id of a view for which this view serves as a label for
7388     * accessibility purposes.
7389     *
7390     * @param id The labeled view id.
7391     */
7392    @RemotableViewMethod
7393    public void setLabelFor(@IdRes int id) {
7394        if (mLabelForId == id) {
7395            return;
7396        }
7397        mLabelForId = id;
7398        if (mLabelForId != View.NO_ID
7399                && mID == View.NO_ID) {
7400            mID = generateViewId();
7401        }
7402        notifyViewAccessibilityStateChangedIfNeeded(
7403                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7404    }
7405
7406    /**
7407     * Invoked whenever this view loses focus, either by losing window focus or by losing
7408     * focus within its window. This method can be used to clear any state tied to the
7409     * focus. For instance, if a button is held pressed with the trackball and the window
7410     * loses focus, this method can be used to cancel the press.
7411     *
7412     * Subclasses of View overriding this method should always call super.onFocusLost().
7413     *
7414     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7415     * @see #onWindowFocusChanged(boolean)
7416     *
7417     * @hide pending API council approval
7418     */
7419    @CallSuper
7420    protected void onFocusLost() {
7421        resetPressedState();
7422    }
7423
7424    private void resetPressedState() {
7425        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7426            return;
7427        }
7428
7429        if (isPressed()) {
7430            setPressed(false);
7431
7432            if (!mHasPerformedLongPress) {
7433                removeLongPressCallback();
7434            }
7435        }
7436    }
7437
7438    /**
7439     * Returns true if this view has focus
7440     *
7441     * @return True if this view has focus, false otherwise.
7442     */
7443    @ViewDebug.ExportedProperty(category = "focus")
7444    public boolean isFocused() {
7445        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7446    }
7447
7448    /**
7449     * Find the view in the hierarchy rooted at this view that currently has
7450     * focus.
7451     *
7452     * @return The view that currently has focus, or null if no focused view can
7453     *         be found.
7454     */
7455    public View findFocus() {
7456        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7457    }
7458
7459    /**
7460     * Indicates whether this view is one of the set of scrollable containers in
7461     * its window.
7462     *
7463     * @return whether this view is one of the set of scrollable containers in
7464     * its window
7465     *
7466     * @attr ref android.R.styleable#View_isScrollContainer
7467     */
7468    public boolean isScrollContainer() {
7469        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7470    }
7471
7472    /**
7473     * Change whether this view is one of the set of scrollable containers in
7474     * its window.  This will be used to determine whether the window can
7475     * resize or must pan when a soft input area is open -- scrollable
7476     * containers allow the window to use resize mode since the container
7477     * will appropriately shrink.
7478     *
7479     * @attr ref android.R.styleable#View_isScrollContainer
7480     */
7481    public void setScrollContainer(boolean isScrollContainer) {
7482        if (isScrollContainer) {
7483            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7484                mAttachInfo.mScrollContainers.add(this);
7485                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7486            }
7487            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7488        } else {
7489            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7490                mAttachInfo.mScrollContainers.remove(this);
7491            }
7492            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7493        }
7494    }
7495
7496    /**
7497     * Returns the quality of the drawing cache.
7498     *
7499     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7500     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7501     *
7502     * @see #setDrawingCacheQuality(int)
7503     * @see #setDrawingCacheEnabled(boolean)
7504     * @see #isDrawingCacheEnabled()
7505     *
7506     * @attr ref android.R.styleable#View_drawingCacheQuality
7507     */
7508    @DrawingCacheQuality
7509    public int getDrawingCacheQuality() {
7510        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7511    }
7512
7513    /**
7514     * Set the drawing cache quality of this view. This value is used only when the
7515     * drawing cache is enabled
7516     *
7517     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7518     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7519     *
7520     * @see #getDrawingCacheQuality()
7521     * @see #setDrawingCacheEnabled(boolean)
7522     * @see #isDrawingCacheEnabled()
7523     *
7524     * @attr ref android.R.styleable#View_drawingCacheQuality
7525     */
7526    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7527        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7528    }
7529
7530    /**
7531     * Returns whether the screen should remain on, corresponding to the current
7532     * value of {@link #KEEP_SCREEN_ON}.
7533     *
7534     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7535     *
7536     * @see #setKeepScreenOn(boolean)
7537     *
7538     * @attr ref android.R.styleable#View_keepScreenOn
7539     */
7540    public boolean getKeepScreenOn() {
7541        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7542    }
7543
7544    /**
7545     * Controls whether the screen should remain on, modifying the
7546     * value of {@link #KEEP_SCREEN_ON}.
7547     *
7548     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7549     *
7550     * @see #getKeepScreenOn()
7551     *
7552     * @attr ref android.R.styleable#View_keepScreenOn
7553     */
7554    public void setKeepScreenOn(boolean keepScreenOn) {
7555        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7556    }
7557
7558    /**
7559     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7560     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7561     *
7562     * @attr ref android.R.styleable#View_nextFocusLeft
7563     */
7564    public int getNextFocusLeftId() {
7565        return mNextFocusLeftId;
7566    }
7567
7568    /**
7569     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7570     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7571     * decide automatically.
7572     *
7573     * @attr ref android.R.styleable#View_nextFocusLeft
7574     */
7575    public void setNextFocusLeftId(int nextFocusLeftId) {
7576        mNextFocusLeftId = nextFocusLeftId;
7577    }
7578
7579    /**
7580     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7581     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7582     *
7583     * @attr ref android.R.styleable#View_nextFocusRight
7584     */
7585    public int getNextFocusRightId() {
7586        return mNextFocusRightId;
7587    }
7588
7589    /**
7590     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7591     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7592     * decide automatically.
7593     *
7594     * @attr ref android.R.styleable#View_nextFocusRight
7595     */
7596    public void setNextFocusRightId(int nextFocusRightId) {
7597        mNextFocusRightId = nextFocusRightId;
7598    }
7599
7600    /**
7601     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7602     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7603     *
7604     * @attr ref android.R.styleable#View_nextFocusUp
7605     */
7606    public int getNextFocusUpId() {
7607        return mNextFocusUpId;
7608    }
7609
7610    /**
7611     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7612     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7613     * decide automatically.
7614     *
7615     * @attr ref android.R.styleable#View_nextFocusUp
7616     */
7617    public void setNextFocusUpId(int nextFocusUpId) {
7618        mNextFocusUpId = nextFocusUpId;
7619    }
7620
7621    /**
7622     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7623     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7624     *
7625     * @attr ref android.R.styleable#View_nextFocusDown
7626     */
7627    public int getNextFocusDownId() {
7628        return mNextFocusDownId;
7629    }
7630
7631    /**
7632     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7633     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7634     * decide automatically.
7635     *
7636     * @attr ref android.R.styleable#View_nextFocusDown
7637     */
7638    public void setNextFocusDownId(int nextFocusDownId) {
7639        mNextFocusDownId = nextFocusDownId;
7640    }
7641
7642    /**
7643     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7644     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7645     *
7646     * @attr ref android.R.styleable#View_nextFocusForward
7647     */
7648    public int getNextFocusForwardId() {
7649        return mNextFocusForwardId;
7650    }
7651
7652    /**
7653     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7654     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7655     * decide automatically.
7656     *
7657     * @attr ref android.R.styleable#View_nextFocusForward
7658     */
7659    public void setNextFocusForwardId(int nextFocusForwardId) {
7660        mNextFocusForwardId = nextFocusForwardId;
7661    }
7662
7663    /**
7664     * Returns the visibility of this view and all of its ancestors
7665     *
7666     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7667     */
7668    public boolean isShown() {
7669        View current = this;
7670        //noinspection ConstantConditions
7671        do {
7672            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7673                return false;
7674            }
7675            ViewParent parent = current.mParent;
7676            if (parent == null) {
7677                return false; // We are not attached to the view root
7678            }
7679            if (!(parent instanceof View)) {
7680                return true;
7681            }
7682            current = (View) parent;
7683        } while (current != null);
7684
7685        return false;
7686    }
7687
7688    /**
7689     * Called by the view hierarchy when the content insets for a window have
7690     * changed, to allow it to adjust its content to fit within those windows.
7691     * The content insets tell you the space that the status bar, input method,
7692     * and other system windows infringe on the application's window.
7693     *
7694     * <p>You do not normally need to deal with this function, since the default
7695     * window decoration given to applications takes care of applying it to the
7696     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7697     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7698     * and your content can be placed under those system elements.  You can then
7699     * use this method within your view hierarchy if you have parts of your UI
7700     * which you would like to ensure are not being covered.
7701     *
7702     * <p>The default implementation of this method simply applies the content
7703     * insets to the view's padding, consuming that content (modifying the
7704     * insets to be 0), and returning true.  This behavior is off by default, but can
7705     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7706     *
7707     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7708     * insets object is propagated down the hierarchy, so any changes made to it will
7709     * be seen by all following views (including potentially ones above in
7710     * the hierarchy since this is a depth-first traversal).  The first view
7711     * that returns true will abort the entire traversal.
7712     *
7713     * <p>The default implementation works well for a situation where it is
7714     * used with a container that covers the entire window, allowing it to
7715     * apply the appropriate insets to its content on all edges.  If you need
7716     * a more complicated layout (such as two different views fitting system
7717     * windows, one on the top of the window, and one on the bottom),
7718     * you can override the method and handle the insets however you would like.
7719     * Note that the insets provided by the framework are always relative to the
7720     * far edges of the window, not accounting for the location of the called view
7721     * within that window.  (In fact when this method is called you do not yet know
7722     * where the layout will place the view, as it is done before layout happens.)
7723     *
7724     * <p>Note: unlike many View methods, there is no dispatch phase to this
7725     * call.  If you are overriding it in a ViewGroup and want to allow the
7726     * call to continue to your children, you must be sure to call the super
7727     * implementation.
7728     *
7729     * <p>Here is a sample layout that makes use of fitting system windows
7730     * to have controls for a video view placed inside of the window decorations
7731     * that it hides and shows.  This can be used with code like the second
7732     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7733     *
7734     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7735     *
7736     * @param insets Current content insets of the window.  Prior to
7737     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7738     * the insets or else you and Android will be unhappy.
7739     *
7740     * @return {@code true} if this view applied the insets and it should not
7741     * continue propagating further down the hierarchy, {@code false} otherwise.
7742     * @see #getFitsSystemWindows()
7743     * @see #setFitsSystemWindows(boolean)
7744     * @see #setSystemUiVisibility(int)
7745     *
7746     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7747     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7748     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7749     * to implement handling their own insets.
7750     */
7751    protected boolean fitSystemWindows(Rect insets) {
7752        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7753            if (insets == null) {
7754                // Null insets by definition have already been consumed.
7755                // This call cannot apply insets since there are none to apply,
7756                // so return false.
7757                return false;
7758            }
7759            // If we're not in the process of dispatching the newer apply insets call,
7760            // that means we're not in the compatibility path. Dispatch into the newer
7761            // apply insets path and take things from there.
7762            try {
7763                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7764                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7765            } finally {
7766                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7767            }
7768        } else {
7769            // We're being called from the newer apply insets path.
7770            // Perform the standard fallback behavior.
7771            return fitSystemWindowsInt(insets);
7772        }
7773    }
7774
7775    private boolean fitSystemWindowsInt(Rect insets) {
7776        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7777            mUserPaddingStart = UNDEFINED_PADDING;
7778            mUserPaddingEnd = UNDEFINED_PADDING;
7779            Rect localInsets = sThreadLocal.get();
7780            if (localInsets == null) {
7781                localInsets = new Rect();
7782                sThreadLocal.set(localInsets);
7783            }
7784            boolean res = computeFitSystemWindows(insets, localInsets);
7785            mUserPaddingLeftInitial = localInsets.left;
7786            mUserPaddingRightInitial = localInsets.right;
7787            internalSetPadding(localInsets.left, localInsets.top,
7788                    localInsets.right, localInsets.bottom);
7789            return res;
7790        }
7791        return false;
7792    }
7793
7794    /**
7795     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7796     *
7797     * <p>This method should be overridden by views that wish to apply a policy different from or
7798     * in addition to the default behavior. Clients that wish to force a view subtree
7799     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7800     *
7801     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7802     * it will be called during dispatch instead of this method. The listener may optionally
7803     * call this method from its own implementation if it wishes to apply the view's default
7804     * insets policy in addition to its own.</p>
7805     *
7806     * <p>Implementations of this method should either return the insets parameter unchanged
7807     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7808     * that this view applied itself. This allows new inset types added in future platform
7809     * versions to pass through existing implementations unchanged without being erroneously
7810     * consumed.</p>
7811     *
7812     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7813     * property is set then the view will consume the system window insets and apply them
7814     * as padding for the view.</p>
7815     *
7816     * @param insets Insets to apply
7817     * @return The supplied insets with any applied insets consumed
7818     */
7819    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7820        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7821            // We weren't called from within a direct call to fitSystemWindows,
7822            // call into it as a fallback in case we're in a class that overrides it
7823            // and has logic to perform.
7824            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7825                return insets.consumeSystemWindowInsets();
7826            }
7827        } else {
7828            // We were called from within a direct call to fitSystemWindows.
7829            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7830                return insets.consumeSystemWindowInsets();
7831            }
7832        }
7833        return insets;
7834    }
7835
7836    /**
7837     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7838     * window insets to this view. The listener's
7839     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7840     * method will be called instead of the view's
7841     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7842     *
7843     * @param listener Listener to set
7844     *
7845     * @see #onApplyWindowInsets(WindowInsets)
7846     */
7847    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7848        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7849    }
7850
7851    /**
7852     * Request to apply the given window insets to this view or another view in its subtree.
7853     *
7854     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7855     * obscured by window decorations or overlays. This can include the status and navigation bars,
7856     * action bars, input methods and more. New inset categories may be added in the future.
7857     * The method returns the insets provided minus any that were applied by this view or its
7858     * children.</p>
7859     *
7860     * <p>Clients wishing to provide custom behavior should override the
7861     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7862     * {@link OnApplyWindowInsetsListener} via the
7863     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7864     * method.</p>
7865     *
7866     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7867     * </p>
7868     *
7869     * @param insets Insets to apply
7870     * @return The provided insets minus the insets that were consumed
7871     */
7872    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7873        try {
7874            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7875            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7876                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7877            } else {
7878                return onApplyWindowInsets(insets);
7879            }
7880        } finally {
7881            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7882        }
7883    }
7884
7885    /**
7886     * Compute the view's coordinate within the surface.
7887     *
7888     * <p>Computes the coordinates of this view in its surface. The argument
7889     * must be an array of two integers. After the method returns, the array
7890     * contains the x and y location in that order.</p>
7891     * @hide
7892     * @param location an array of two integers in which to hold the coordinates
7893     */
7894    public void getLocationInSurface(@Size(2) int[] location) {
7895        getLocationInWindow(location);
7896        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
7897            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
7898            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
7899        }
7900    }
7901
7902    /**
7903     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7904     * only available if the view is attached.
7905     *
7906     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7907     */
7908    public WindowInsets getRootWindowInsets() {
7909        if (mAttachInfo != null) {
7910            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7911        }
7912        return null;
7913    }
7914
7915    /**
7916     * @hide Compute the insets that should be consumed by this view and the ones
7917     * that should propagate to those under it.
7918     */
7919    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7920        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7921                || mAttachInfo == null
7922                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7923                        && !mAttachInfo.mOverscanRequested)) {
7924            outLocalInsets.set(inoutInsets);
7925            inoutInsets.set(0, 0, 0, 0);
7926            return true;
7927        } else {
7928            // The application wants to take care of fitting system window for
7929            // the content...  however we still need to take care of any overscan here.
7930            final Rect overscan = mAttachInfo.mOverscanInsets;
7931            outLocalInsets.set(overscan);
7932            inoutInsets.left -= overscan.left;
7933            inoutInsets.top -= overscan.top;
7934            inoutInsets.right -= overscan.right;
7935            inoutInsets.bottom -= overscan.bottom;
7936            return false;
7937        }
7938    }
7939
7940    /**
7941     * Compute insets that should be consumed by this view and the ones that should propagate
7942     * to those under it.
7943     *
7944     * @param in Insets currently being processed by this View, likely received as a parameter
7945     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7946     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7947     *                       by this view
7948     * @return Insets that should be passed along to views under this one
7949     */
7950    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7951        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7952                || mAttachInfo == null
7953                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7954            outLocalInsets.set(in.getSystemWindowInsets());
7955            return in.consumeSystemWindowInsets();
7956        } else {
7957            outLocalInsets.set(0, 0, 0, 0);
7958            return in;
7959        }
7960    }
7961
7962    /**
7963     * Sets whether or not this view should account for system screen decorations
7964     * such as the status bar and inset its content; that is, controlling whether
7965     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7966     * executed.  See that method for more details.
7967     *
7968     * <p>Note that if you are providing your own implementation of
7969     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7970     * flag to true -- your implementation will be overriding the default
7971     * implementation that checks this flag.
7972     *
7973     * @param fitSystemWindows If true, then the default implementation of
7974     * {@link #fitSystemWindows(Rect)} will be executed.
7975     *
7976     * @attr ref android.R.styleable#View_fitsSystemWindows
7977     * @see #getFitsSystemWindows()
7978     * @see #fitSystemWindows(Rect)
7979     * @see #setSystemUiVisibility(int)
7980     */
7981    public void setFitsSystemWindows(boolean fitSystemWindows) {
7982        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7983    }
7984
7985    /**
7986     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7987     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7988     * will be executed.
7989     *
7990     * @return {@code true} if the default implementation of
7991     * {@link #fitSystemWindows(Rect)} will be executed.
7992     *
7993     * @attr ref android.R.styleable#View_fitsSystemWindows
7994     * @see #setFitsSystemWindows(boolean)
7995     * @see #fitSystemWindows(Rect)
7996     * @see #setSystemUiVisibility(int)
7997     */
7998    @ViewDebug.ExportedProperty
7999    public boolean getFitsSystemWindows() {
8000        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8001    }
8002
8003    /** @hide */
8004    public boolean fitsSystemWindows() {
8005        return getFitsSystemWindows();
8006    }
8007
8008    /**
8009     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8010     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8011     */
8012    public void requestFitSystemWindows() {
8013        if (mParent != null) {
8014            mParent.requestFitSystemWindows();
8015        }
8016    }
8017
8018    /**
8019     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8020     */
8021    public void requestApplyInsets() {
8022        requestFitSystemWindows();
8023    }
8024
8025    /**
8026     * For use by PhoneWindow to make its own system window fitting optional.
8027     * @hide
8028     */
8029    public void makeOptionalFitsSystemWindows() {
8030        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8031    }
8032
8033    /**
8034     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8035     * treat them as such.
8036     * @hide
8037     */
8038    public void getOutsets(Rect outOutsetRect) {
8039        if (mAttachInfo != null) {
8040            outOutsetRect.set(mAttachInfo.mOutsets);
8041        } else {
8042            outOutsetRect.setEmpty();
8043        }
8044    }
8045
8046    /**
8047     * Returns the visibility status for this view.
8048     *
8049     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8050     * @attr ref android.R.styleable#View_visibility
8051     */
8052    @ViewDebug.ExportedProperty(mapping = {
8053        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
8054        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
8055        @ViewDebug.IntToString(from = GONE,      to = "GONE")
8056    })
8057    @Visibility
8058    public int getVisibility() {
8059        return mViewFlags & VISIBILITY_MASK;
8060    }
8061
8062    /**
8063     * Set the enabled state of this view.
8064     *
8065     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8066     * @attr ref android.R.styleable#View_visibility
8067     */
8068    @RemotableViewMethod
8069    public void setVisibility(@Visibility int visibility) {
8070        setFlags(visibility, VISIBILITY_MASK);
8071    }
8072
8073    /**
8074     * Returns the enabled status for this view. The interpretation of the
8075     * enabled state varies by subclass.
8076     *
8077     * @return True if this view is enabled, false otherwise.
8078     */
8079    @ViewDebug.ExportedProperty
8080    public boolean isEnabled() {
8081        return (mViewFlags & ENABLED_MASK) == ENABLED;
8082    }
8083
8084    /**
8085     * Set the enabled state of this view. The interpretation of the enabled
8086     * state varies by subclass.
8087     *
8088     * @param enabled True if this view is enabled, false otherwise.
8089     */
8090    @RemotableViewMethod
8091    public void setEnabled(boolean enabled) {
8092        if (enabled == isEnabled()) return;
8093
8094        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8095
8096        /*
8097         * The View most likely has to change its appearance, so refresh
8098         * the drawable state.
8099         */
8100        refreshDrawableState();
8101
8102        // Invalidate too, since the default behavior for views is to be
8103        // be drawn at 50% alpha rather than to change the drawable.
8104        invalidate(true);
8105
8106        if (!enabled) {
8107            cancelPendingInputEvents();
8108        }
8109    }
8110
8111    /**
8112     * Set whether this view can receive the focus.
8113     *
8114     * Setting this to false will also ensure that this view is not focusable
8115     * in touch mode.
8116     *
8117     * @param focusable If true, this view can receive the focus.
8118     *
8119     * @see #setFocusableInTouchMode(boolean)
8120     * @attr ref android.R.styleable#View_focusable
8121     */
8122    public void setFocusable(boolean focusable) {
8123        if (!focusable) {
8124            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8125        }
8126        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8127    }
8128
8129    /**
8130     * Set whether this view can receive focus while in touch mode.
8131     *
8132     * Setting this to true will also ensure that this view is focusable.
8133     *
8134     * @param focusableInTouchMode If true, this view can receive the focus while
8135     *   in touch mode.
8136     *
8137     * @see #setFocusable(boolean)
8138     * @attr ref android.R.styleable#View_focusableInTouchMode
8139     */
8140    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8141        // Focusable in touch mode should always be set before the focusable flag
8142        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8143        // which, in touch mode, will not successfully request focus on this view
8144        // because the focusable in touch mode flag is not set
8145        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8146        if (focusableInTouchMode) {
8147            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8148        }
8149    }
8150
8151    /**
8152     * Set whether this view should have sound effects enabled for events such as
8153     * clicking and touching.
8154     *
8155     * <p>You may wish to disable sound effects for a view if you already play sounds,
8156     * for instance, a dial key that plays dtmf tones.
8157     *
8158     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8159     * @see #isSoundEffectsEnabled()
8160     * @see #playSoundEffect(int)
8161     * @attr ref android.R.styleable#View_soundEffectsEnabled
8162     */
8163    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8164        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8165    }
8166
8167    /**
8168     * @return whether this view should have sound effects enabled for events such as
8169     *     clicking and touching.
8170     *
8171     * @see #setSoundEffectsEnabled(boolean)
8172     * @see #playSoundEffect(int)
8173     * @attr ref android.R.styleable#View_soundEffectsEnabled
8174     */
8175    @ViewDebug.ExportedProperty
8176    public boolean isSoundEffectsEnabled() {
8177        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8178    }
8179
8180    /**
8181     * Set whether this view should have haptic feedback for events such as
8182     * long presses.
8183     *
8184     * <p>You may wish to disable haptic feedback if your view already controls
8185     * its own haptic feedback.
8186     *
8187     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8188     * @see #isHapticFeedbackEnabled()
8189     * @see #performHapticFeedback(int)
8190     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8191     */
8192    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8193        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8194    }
8195
8196    /**
8197     * @return whether this view should have haptic feedback enabled for events
8198     * long presses.
8199     *
8200     * @see #setHapticFeedbackEnabled(boolean)
8201     * @see #performHapticFeedback(int)
8202     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8203     */
8204    @ViewDebug.ExportedProperty
8205    public boolean isHapticFeedbackEnabled() {
8206        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8207    }
8208
8209    /**
8210     * Returns the layout direction for this view.
8211     *
8212     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8213     *   {@link #LAYOUT_DIRECTION_RTL},
8214     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8215     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8216     *
8217     * @attr ref android.R.styleable#View_layoutDirection
8218     *
8219     * @hide
8220     */
8221    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8222        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8223        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8224        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8225        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8226    })
8227    @LayoutDir
8228    public int getRawLayoutDirection() {
8229        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8230    }
8231
8232    /**
8233     * Set the layout direction for this view. This will propagate a reset of layout direction
8234     * resolution to the view's children and resolve layout direction for this view.
8235     *
8236     * @param layoutDirection the layout direction to set. Should be one of:
8237     *
8238     * {@link #LAYOUT_DIRECTION_LTR},
8239     * {@link #LAYOUT_DIRECTION_RTL},
8240     * {@link #LAYOUT_DIRECTION_INHERIT},
8241     * {@link #LAYOUT_DIRECTION_LOCALE}.
8242     *
8243     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8244     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8245     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8246     *
8247     * @attr ref android.R.styleable#View_layoutDirection
8248     */
8249    @RemotableViewMethod
8250    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8251        if (getRawLayoutDirection() != layoutDirection) {
8252            // Reset the current layout direction and the resolved one
8253            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8254            resetRtlProperties();
8255            // Set the new layout direction (filtered)
8256            mPrivateFlags2 |=
8257                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8258            // We need to resolve all RTL properties as they all depend on layout direction
8259            resolveRtlPropertiesIfNeeded();
8260            requestLayout();
8261            invalidate(true);
8262        }
8263    }
8264
8265    /**
8266     * Returns the resolved layout direction for this view.
8267     *
8268     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8269     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8270     *
8271     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8272     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8273     *
8274     * @attr ref android.R.styleable#View_layoutDirection
8275     */
8276    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8277        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8278        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8279    })
8280    @ResolvedLayoutDir
8281    public int getLayoutDirection() {
8282        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8283        if (targetSdkVersion < JELLY_BEAN_MR1) {
8284            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8285            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8286        }
8287        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8288                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8289    }
8290
8291    /**
8292     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8293     * layout attribute and/or the inherited value from the parent
8294     *
8295     * @return true if the layout is right-to-left.
8296     *
8297     * @hide
8298     */
8299    @ViewDebug.ExportedProperty(category = "layout")
8300    public boolean isLayoutRtl() {
8301        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8302    }
8303
8304    /**
8305     * Indicates whether the view is currently tracking transient state that the
8306     * app should not need to concern itself with saving and restoring, but that
8307     * the framework should take special note to preserve when possible.
8308     *
8309     * <p>A view with transient state cannot be trivially rebound from an external
8310     * data source, such as an adapter binding item views in a list. This may be
8311     * because the view is performing an animation, tracking user selection
8312     * of content, or similar.</p>
8313     *
8314     * @return true if the view has transient state
8315     */
8316    @ViewDebug.ExportedProperty(category = "layout")
8317    public boolean hasTransientState() {
8318        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8319    }
8320
8321    /**
8322     * Set whether this view is currently tracking transient state that the
8323     * framework should attempt to preserve when possible. This flag is reference counted,
8324     * so every call to setHasTransientState(true) should be paired with a later call
8325     * to setHasTransientState(false).
8326     *
8327     * <p>A view with transient state cannot be trivially rebound from an external
8328     * data source, such as an adapter binding item views in a list. This may be
8329     * because the view is performing an animation, tracking user selection
8330     * of content, or similar.</p>
8331     *
8332     * @param hasTransientState true if this view has transient state
8333     */
8334    public void setHasTransientState(boolean hasTransientState) {
8335        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8336                mTransientStateCount - 1;
8337        if (mTransientStateCount < 0) {
8338            mTransientStateCount = 0;
8339            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8340                    "unmatched pair of setHasTransientState calls");
8341        } else if ((hasTransientState && mTransientStateCount == 1) ||
8342                (!hasTransientState && mTransientStateCount == 0)) {
8343            // update flag if we've just incremented up from 0 or decremented down to 0
8344            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8345                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8346            if (mParent != null) {
8347                try {
8348                    mParent.childHasTransientStateChanged(this, hasTransientState);
8349                } catch (AbstractMethodError e) {
8350                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8351                            " does not fully implement ViewParent", e);
8352                }
8353            }
8354        }
8355    }
8356
8357    /**
8358     * Returns true if this view is currently attached to a window.
8359     */
8360    public boolean isAttachedToWindow() {
8361        return mAttachInfo != null;
8362    }
8363
8364    /**
8365     * Returns true if this view has been through at least one layout since it
8366     * was last attached to or detached from a window.
8367     */
8368    public boolean isLaidOut() {
8369        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8370    }
8371
8372    /**
8373     * If this view doesn't do any drawing on its own, set this flag to
8374     * allow further optimizations. By default, this flag is not set on
8375     * View, but could be set on some View subclasses such as ViewGroup.
8376     *
8377     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8378     * you should clear this flag.
8379     *
8380     * @param willNotDraw whether or not this View draw on its own
8381     */
8382    public void setWillNotDraw(boolean willNotDraw) {
8383        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8384    }
8385
8386    /**
8387     * Returns whether or not this View draws on its own.
8388     *
8389     * @return true if this view has nothing to draw, false otherwise
8390     */
8391    @ViewDebug.ExportedProperty(category = "drawing")
8392    public boolean willNotDraw() {
8393        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8394    }
8395
8396    /**
8397     * When a View's drawing cache is enabled, drawing is redirected to an
8398     * offscreen bitmap. Some views, like an ImageView, must be able to
8399     * bypass this mechanism if they already draw a single bitmap, to avoid
8400     * unnecessary usage of the memory.
8401     *
8402     * @param willNotCacheDrawing true if this view does not cache its
8403     *        drawing, false otherwise
8404     */
8405    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8406        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8407    }
8408
8409    /**
8410     * Returns whether or not this View can cache its drawing or not.
8411     *
8412     * @return true if this view does not cache its drawing, false otherwise
8413     */
8414    @ViewDebug.ExportedProperty(category = "drawing")
8415    public boolean willNotCacheDrawing() {
8416        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8417    }
8418
8419    /**
8420     * Indicates whether this view reacts to click events or not.
8421     *
8422     * @return true if the view is clickable, false otherwise
8423     *
8424     * @see #setClickable(boolean)
8425     * @attr ref android.R.styleable#View_clickable
8426     */
8427    @ViewDebug.ExportedProperty
8428    public boolean isClickable() {
8429        return (mViewFlags & CLICKABLE) == CLICKABLE;
8430    }
8431
8432    /**
8433     * Enables or disables click events for this view. When a view
8434     * is clickable it will change its state to "pressed" on every click.
8435     * Subclasses should set the view clickable to visually react to
8436     * user's clicks.
8437     *
8438     * @param clickable true to make the view clickable, false otherwise
8439     *
8440     * @see #isClickable()
8441     * @attr ref android.R.styleable#View_clickable
8442     */
8443    public void setClickable(boolean clickable) {
8444        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8445    }
8446
8447    /**
8448     * Indicates whether this view reacts to long click events or not.
8449     *
8450     * @return true if the view is long clickable, false otherwise
8451     *
8452     * @see #setLongClickable(boolean)
8453     * @attr ref android.R.styleable#View_longClickable
8454     */
8455    public boolean isLongClickable() {
8456        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8457    }
8458
8459    /**
8460     * Enables or disables long click events for this view. When a view is long
8461     * clickable it reacts to the user holding down the button for a longer
8462     * duration than a tap. This event can either launch the listener or a
8463     * context menu.
8464     *
8465     * @param longClickable true to make the view long clickable, false otherwise
8466     * @see #isLongClickable()
8467     * @attr ref android.R.styleable#View_longClickable
8468     */
8469    public void setLongClickable(boolean longClickable) {
8470        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8471    }
8472
8473    /**
8474     * Indicates whether this view reacts to context clicks or not.
8475     *
8476     * @return true if the view is context clickable, false otherwise
8477     * @see #setContextClickable(boolean)
8478     * @attr ref android.R.styleable#View_contextClickable
8479     */
8480    public boolean isContextClickable() {
8481        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8482    }
8483
8484    /**
8485     * Enables or disables context clicking for this view. This event can launch the listener.
8486     *
8487     * @param contextClickable true to make the view react to a context click, false otherwise
8488     * @see #isContextClickable()
8489     * @attr ref android.R.styleable#View_contextClickable
8490     */
8491    public void setContextClickable(boolean contextClickable) {
8492        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8493    }
8494
8495    /**
8496     * Sets the pressed state for this view and provides a touch coordinate for
8497     * animation hinting.
8498     *
8499     * @param pressed Pass true to set the View's internal state to "pressed",
8500     *            or false to reverts the View's internal state from a
8501     *            previously set "pressed" state.
8502     * @param x The x coordinate of the touch that caused the press
8503     * @param y The y coordinate of the touch that caused the press
8504     */
8505    private void setPressed(boolean pressed, float x, float y) {
8506        if (pressed) {
8507            drawableHotspotChanged(x, y);
8508        }
8509
8510        setPressed(pressed);
8511    }
8512
8513    /**
8514     * Sets the pressed state for this view.
8515     *
8516     * @see #isClickable()
8517     * @see #setClickable(boolean)
8518     *
8519     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8520     *        the View's internal state from a previously set "pressed" state.
8521     */
8522    public void setPressed(boolean pressed) {
8523        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8524
8525        if (pressed) {
8526            mPrivateFlags |= PFLAG_PRESSED;
8527        } else {
8528            mPrivateFlags &= ~PFLAG_PRESSED;
8529        }
8530
8531        if (needsRefresh) {
8532            refreshDrawableState();
8533        }
8534        dispatchSetPressed(pressed);
8535    }
8536
8537    /**
8538     * Dispatch setPressed to all of this View's children.
8539     *
8540     * @see #setPressed(boolean)
8541     *
8542     * @param pressed The new pressed state
8543     */
8544    protected void dispatchSetPressed(boolean pressed) {
8545    }
8546
8547    /**
8548     * Indicates whether the view is currently in pressed state. Unless
8549     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8550     * the pressed state.
8551     *
8552     * @see #setPressed(boolean)
8553     * @see #isClickable()
8554     * @see #setClickable(boolean)
8555     *
8556     * @return true if the view is currently pressed, false otherwise
8557     */
8558    @ViewDebug.ExportedProperty
8559    public boolean isPressed() {
8560        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8561    }
8562
8563    /**
8564     * @hide
8565     * Indicates whether this view will participate in data collection through
8566     * {@link ViewStructure}.  If true, it will not provide any data
8567     * for itself or its children.  If false, the normal data collection will be allowed.
8568     *
8569     * @return Returns false if assist data collection is not blocked, else true.
8570     *
8571     * @see #setAssistBlocked(boolean)
8572     * @attr ref android.R.styleable#View_assistBlocked
8573     */
8574    public boolean isAssistBlocked() {
8575        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8576    }
8577
8578    /**
8579     * @hide
8580     * Controls whether assist data collection from this view and its children is enabled
8581     * (that is, whether {@link #onProvideStructure} and
8582     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8583     * allowing normal assist collection.  Setting this to false will disable assist collection.
8584     *
8585     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8586     * (the default) to allow it.
8587     *
8588     * @see #isAssistBlocked()
8589     * @see #onProvideStructure
8590     * @see #onProvideVirtualStructure
8591     * @attr ref android.R.styleable#View_assistBlocked
8592     */
8593    public void setAssistBlocked(boolean enabled) {
8594        if (enabled) {
8595            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8596        } else {
8597            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8598        }
8599    }
8600
8601    /**
8602     * Indicates whether this view will save its state (that is,
8603     * whether its {@link #onSaveInstanceState} method will be called).
8604     *
8605     * @return Returns true if the view state saving is enabled, else false.
8606     *
8607     * @see #setSaveEnabled(boolean)
8608     * @attr ref android.R.styleable#View_saveEnabled
8609     */
8610    public boolean isSaveEnabled() {
8611        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8612    }
8613
8614    /**
8615     * Controls whether the saving of this view's state is
8616     * enabled (that is, whether its {@link #onSaveInstanceState} method
8617     * will be called).  Note that even if freezing is enabled, the
8618     * view still must have an id assigned to it (via {@link #setId(int)})
8619     * for its state to be saved.  This flag can only disable the
8620     * saving of this view; any child views may still have their state saved.
8621     *
8622     * @param enabled Set to false to <em>disable</em> state saving, or true
8623     * (the default) to allow it.
8624     *
8625     * @see #isSaveEnabled()
8626     * @see #setId(int)
8627     * @see #onSaveInstanceState()
8628     * @attr ref android.R.styleable#View_saveEnabled
8629     */
8630    public void setSaveEnabled(boolean enabled) {
8631        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8632    }
8633
8634    /**
8635     * Gets whether the framework should discard touches when the view's
8636     * window is obscured by another visible window.
8637     * Refer to the {@link View} security documentation for more details.
8638     *
8639     * @return True if touch filtering is enabled.
8640     *
8641     * @see #setFilterTouchesWhenObscured(boolean)
8642     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8643     */
8644    @ViewDebug.ExportedProperty
8645    public boolean getFilterTouchesWhenObscured() {
8646        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8647    }
8648
8649    /**
8650     * Sets whether the framework should discard touches when the view's
8651     * window is obscured by another visible window.
8652     * Refer to the {@link View} security documentation for more details.
8653     *
8654     * @param enabled True if touch filtering should be enabled.
8655     *
8656     * @see #getFilterTouchesWhenObscured
8657     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8658     */
8659    public void setFilterTouchesWhenObscured(boolean enabled) {
8660        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8661                FILTER_TOUCHES_WHEN_OBSCURED);
8662    }
8663
8664    /**
8665     * Indicates whether the entire hierarchy under this view will save its
8666     * state when a state saving traversal occurs from its parent.  The default
8667     * is true; if false, these views will not be saved unless
8668     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8669     *
8670     * @return Returns true if the view state saving from parent is enabled, else false.
8671     *
8672     * @see #setSaveFromParentEnabled(boolean)
8673     */
8674    public boolean isSaveFromParentEnabled() {
8675        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8676    }
8677
8678    /**
8679     * Controls whether the entire hierarchy under this view will save its
8680     * state when a state saving traversal occurs from its parent.  The default
8681     * is true; if false, these views will not be saved unless
8682     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8683     *
8684     * @param enabled Set to false to <em>disable</em> state saving, or true
8685     * (the default) to allow it.
8686     *
8687     * @see #isSaveFromParentEnabled()
8688     * @see #setId(int)
8689     * @see #onSaveInstanceState()
8690     */
8691    public void setSaveFromParentEnabled(boolean enabled) {
8692        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8693    }
8694
8695
8696    /**
8697     * Returns whether this View is able to take focus.
8698     *
8699     * @return True if this view can take focus, or false otherwise.
8700     * @attr ref android.R.styleable#View_focusable
8701     */
8702    @ViewDebug.ExportedProperty(category = "focus")
8703    public final boolean isFocusable() {
8704        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8705    }
8706
8707    /**
8708     * When a view is focusable, it may not want to take focus when in touch mode.
8709     * For example, a button would like focus when the user is navigating via a D-pad
8710     * so that the user can click on it, but once the user starts touching the screen,
8711     * the button shouldn't take focus
8712     * @return Whether the view is focusable in touch mode.
8713     * @attr ref android.R.styleable#View_focusableInTouchMode
8714     */
8715    @ViewDebug.ExportedProperty
8716    public final boolean isFocusableInTouchMode() {
8717        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8718    }
8719
8720    /**
8721     * Find the nearest view in the specified direction that can take focus.
8722     * This does not actually give focus to that view.
8723     *
8724     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8725     *
8726     * @return The nearest focusable in the specified direction, or null if none
8727     *         can be found.
8728     */
8729    public View focusSearch(@FocusRealDirection int direction) {
8730        if (mParent != null) {
8731            return mParent.focusSearch(this, direction);
8732        } else {
8733            return null;
8734        }
8735    }
8736
8737    /**
8738     * This method is the last chance for the focused view and its ancestors to
8739     * respond to an arrow key. This is called when the focused view did not
8740     * consume the key internally, nor could the view system find a new view in
8741     * the requested direction to give focus to.
8742     *
8743     * @param focused The currently focused view.
8744     * @param direction The direction focus wants to move. One of FOCUS_UP,
8745     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8746     * @return True if the this view consumed this unhandled move.
8747     */
8748    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8749        return false;
8750    }
8751
8752    /**
8753     * If a user manually specified the next view id for a particular direction,
8754     * use the root to look up the view.
8755     * @param root The root view of the hierarchy containing this view.
8756     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8757     * or FOCUS_BACKWARD.
8758     * @return The user specified next view, or null if there is none.
8759     */
8760    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8761        switch (direction) {
8762            case FOCUS_LEFT:
8763                if (mNextFocusLeftId == View.NO_ID) return null;
8764                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8765            case FOCUS_RIGHT:
8766                if (mNextFocusRightId == View.NO_ID) return null;
8767                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8768            case FOCUS_UP:
8769                if (mNextFocusUpId == View.NO_ID) return null;
8770                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8771            case FOCUS_DOWN:
8772                if (mNextFocusDownId == View.NO_ID) return null;
8773                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8774            case FOCUS_FORWARD:
8775                if (mNextFocusForwardId == View.NO_ID) return null;
8776                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8777            case FOCUS_BACKWARD: {
8778                if (mID == View.NO_ID) return null;
8779                final int id = mID;
8780                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8781                    @Override
8782                    public boolean apply(View t) {
8783                        return t.mNextFocusForwardId == id;
8784                    }
8785                });
8786            }
8787        }
8788        return null;
8789    }
8790
8791    private View findViewInsideOutShouldExist(View root, int id) {
8792        if (mMatchIdPredicate == null) {
8793            mMatchIdPredicate = new MatchIdPredicate();
8794        }
8795        mMatchIdPredicate.mId = id;
8796        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8797        if (result == null) {
8798            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8799        }
8800        return result;
8801    }
8802
8803    /**
8804     * Find and return all focusable views that are descendants of this view,
8805     * possibly including this view if it is focusable itself.
8806     *
8807     * @param direction The direction of the focus
8808     * @return A list of focusable views
8809     */
8810    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8811        ArrayList<View> result = new ArrayList<View>(24);
8812        addFocusables(result, direction);
8813        return result;
8814    }
8815
8816    /**
8817     * Add any focusable views that are descendants of this view (possibly
8818     * including this view if it is focusable itself) to views.  If we are in touch mode,
8819     * only add views that are also focusable in touch mode.
8820     *
8821     * @param views Focusable views found so far
8822     * @param direction The direction of the focus
8823     */
8824    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8825        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
8826    }
8827
8828    /**
8829     * Adds any focusable views that are descendants of this view (possibly
8830     * including this view if it is focusable itself) to views. This method
8831     * adds all focusable views regardless if we are in touch mode or
8832     * only views focusable in touch mode if we are in touch mode or
8833     * only views that can take accessibility focus if accessibility is enabled
8834     * depending on the focusable mode parameter.
8835     *
8836     * @param views Focusable views found so far or null if all we are interested is
8837     *        the number of focusables.
8838     * @param direction The direction of the focus.
8839     * @param focusableMode The type of focusables to be added.
8840     *
8841     * @see #FOCUSABLES_ALL
8842     * @see #FOCUSABLES_TOUCH_MODE
8843     */
8844    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8845            @FocusableMode int focusableMode) {
8846        if (views == null) {
8847            return;
8848        }
8849        if (!isFocusable()) {
8850            return;
8851        }
8852        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8853                && !isFocusableInTouchMode()) {
8854            return;
8855        }
8856        views.add(this);
8857    }
8858
8859    /**
8860     * Finds the Views that contain given text. The containment is case insensitive.
8861     * The search is performed by either the text that the View renders or the content
8862     * description that describes the view for accessibility purposes and the view does
8863     * not render or both. Clients can specify how the search is to be performed via
8864     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8865     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8866     *
8867     * @param outViews The output list of matching Views.
8868     * @param searched The text to match against.
8869     *
8870     * @see #FIND_VIEWS_WITH_TEXT
8871     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8872     * @see #setContentDescription(CharSequence)
8873     */
8874    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8875            @FindViewFlags int flags) {
8876        if (getAccessibilityNodeProvider() != null) {
8877            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8878                outViews.add(this);
8879            }
8880        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8881                && (searched != null && searched.length() > 0)
8882                && (mContentDescription != null && mContentDescription.length() > 0)) {
8883            String searchedLowerCase = searched.toString().toLowerCase();
8884            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8885            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8886                outViews.add(this);
8887            }
8888        }
8889    }
8890
8891    /**
8892     * Find and return all touchable views that are descendants of this view,
8893     * possibly including this view if it is touchable itself.
8894     *
8895     * @return A list of touchable views
8896     */
8897    public ArrayList<View> getTouchables() {
8898        ArrayList<View> result = new ArrayList<View>();
8899        addTouchables(result);
8900        return result;
8901    }
8902
8903    /**
8904     * Add any touchable views that are descendants of this view (possibly
8905     * including this view if it is touchable itself) to views.
8906     *
8907     * @param views Touchable views found so far
8908     */
8909    public void addTouchables(ArrayList<View> views) {
8910        final int viewFlags = mViewFlags;
8911
8912        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8913                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8914                && (viewFlags & ENABLED_MASK) == ENABLED) {
8915            views.add(this);
8916        }
8917    }
8918
8919    /**
8920     * Returns whether this View is accessibility focused.
8921     *
8922     * @return True if this View is accessibility focused.
8923     */
8924    public boolean isAccessibilityFocused() {
8925        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8926    }
8927
8928    /**
8929     * Call this to try to give accessibility focus to this view.
8930     *
8931     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8932     * returns false or the view is no visible or the view already has accessibility
8933     * focus.
8934     *
8935     * See also {@link #focusSearch(int)}, which is what you call to say that you
8936     * have focus, and you want your parent to look for the next one.
8937     *
8938     * @return Whether this view actually took accessibility focus.
8939     *
8940     * @hide
8941     */
8942    public boolean requestAccessibilityFocus() {
8943        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8944        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8945            return false;
8946        }
8947        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8948            return false;
8949        }
8950        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8951            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8952            ViewRootImpl viewRootImpl = getViewRootImpl();
8953            if (viewRootImpl != null) {
8954                viewRootImpl.setAccessibilityFocus(this, null);
8955            }
8956            invalidate();
8957            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8958            return true;
8959        }
8960        return false;
8961    }
8962
8963    /**
8964     * Call this to try to clear accessibility focus of this view.
8965     *
8966     * See also {@link #focusSearch(int)}, which is what you call to say that you
8967     * have focus, and you want your parent to look for the next one.
8968     *
8969     * @hide
8970     */
8971    public void clearAccessibilityFocus() {
8972        clearAccessibilityFocusNoCallbacks(0);
8973
8974        // Clear the global reference of accessibility focus if this view or
8975        // any of its descendants had accessibility focus. This will NOT send
8976        // an event or update internal state if focus is cleared from a
8977        // descendant view, which may leave views in inconsistent states.
8978        final ViewRootImpl viewRootImpl = getViewRootImpl();
8979        if (viewRootImpl != null) {
8980            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8981            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8982                viewRootImpl.setAccessibilityFocus(null, null);
8983            }
8984        }
8985    }
8986
8987    private void sendAccessibilityHoverEvent(int eventType) {
8988        // Since we are not delivering to a client accessibility events from not
8989        // important views (unless the clinet request that) we need to fire the
8990        // event from the deepest view exposed to the client. As a consequence if
8991        // the user crosses a not exposed view the client will see enter and exit
8992        // of the exposed predecessor followed by and enter and exit of that same
8993        // predecessor when entering and exiting the not exposed descendant. This
8994        // is fine since the client has a clear idea which view is hovered at the
8995        // price of a couple more events being sent. This is a simple and
8996        // working solution.
8997        View source = this;
8998        while (true) {
8999            if (source.includeForAccessibility()) {
9000                source.sendAccessibilityEvent(eventType);
9001                return;
9002            }
9003            ViewParent parent = source.getParent();
9004            if (parent instanceof View) {
9005                source = (View) parent;
9006            } else {
9007                return;
9008            }
9009        }
9010    }
9011
9012    /**
9013     * Clears accessibility focus without calling any callback methods
9014     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9015     * is used separately from that one for clearing accessibility focus when
9016     * giving this focus to another view.
9017     *
9018     * @param action The action, if any, that led to focus being cleared. Set to
9019     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9020     * the window.
9021     */
9022    void clearAccessibilityFocusNoCallbacks(int action) {
9023        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9024            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9025            invalidate();
9026            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9027                AccessibilityEvent event = AccessibilityEvent.obtain(
9028                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9029                event.setAction(action);
9030                if (mAccessibilityDelegate != null) {
9031                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9032                } else {
9033                    sendAccessibilityEventUnchecked(event);
9034                }
9035            }
9036        }
9037    }
9038
9039    /**
9040     * Call this to try to give focus to a specific view or to one of its
9041     * descendants.
9042     *
9043     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9044     * false), or if it is focusable and it is not focusable in touch mode
9045     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9046     *
9047     * See also {@link #focusSearch(int)}, which is what you call to say that you
9048     * have focus, and you want your parent to look for the next one.
9049     *
9050     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9051     * {@link #FOCUS_DOWN} and <code>null</code>.
9052     *
9053     * @return Whether this view or one of its descendants actually took focus.
9054     */
9055    public final boolean requestFocus() {
9056        return requestFocus(View.FOCUS_DOWN);
9057    }
9058
9059    /**
9060     * Call this to try to give focus to a specific view or to one of its
9061     * descendants and give it a hint about what direction focus is heading.
9062     *
9063     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9064     * false), or if it is focusable and it is not focusable in touch mode
9065     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9066     *
9067     * See also {@link #focusSearch(int)}, which is what you call to say that you
9068     * have focus, and you want your parent to look for the next one.
9069     *
9070     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9071     * <code>null</code> set for the previously focused rectangle.
9072     *
9073     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9074     * @return Whether this view or one of its descendants actually took focus.
9075     */
9076    public final boolean requestFocus(int direction) {
9077        return requestFocus(direction, null);
9078    }
9079
9080    /**
9081     * Call this to try to give focus to a specific view or to one of its descendants
9082     * and give it hints about the direction and a specific rectangle that the focus
9083     * is coming from.  The rectangle can help give larger views a finer grained hint
9084     * about where focus is coming from, and therefore, where to show selection, or
9085     * forward focus change internally.
9086     *
9087     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9088     * false), or if it is focusable and it is not focusable in touch mode
9089     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9090     *
9091     * A View will not take focus if it is not visible.
9092     *
9093     * A View will not take focus if one of its parents has
9094     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9095     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9096     *
9097     * See also {@link #focusSearch(int)}, which is what you call to say that you
9098     * have focus, and you want your parent to look for the next one.
9099     *
9100     * You may wish to override this method if your custom {@link View} has an internal
9101     * {@link View} that it wishes to forward the request to.
9102     *
9103     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9104     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9105     *        to give a finer grained hint about where focus is coming from.  May be null
9106     *        if there is no hint.
9107     * @return Whether this view or one of its descendants actually took focus.
9108     */
9109    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9110        return requestFocusNoSearch(direction, previouslyFocusedRect);
9111    }
9112
9113    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9114        // need to be focusable
9115        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9116                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9117            return false;
9118        }
9119
9120        // need to be focusable in touch mode if in touch mode
9121        if (isInTouchMode() &&
9122            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9123               return false;
9124        }
9125
9126        // need to not have any parents blocking us
9127        if (hasAncestorThatBlocksDescendantFocus()) {
9128            return false;
9129        }
9130
9131        handleFocusGainInternal(direction, previouslyFocusedRect);
9132        return true;
9133    }
9134
9135    /**
9136     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9137     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9138     * touch mode to request focus when they are touched.
9139     *
9140     * @return Whether this view or one of its descendants actually took focus.
9141     *
9142     * @see #isInTouchMode()
9143     *
9144     */
9145    public final boolean requestFocusFromTouch() {
9146        // Leave touch mode if we need to
9147        if (isInTouchMode()) {
9148            ViewRootImpl viewRoot = getViewRootImpl();
9149            if (viewRoot != null) {
9150                viewRoot.ensureTouchMode(false);
9151            }
9152        }
9153        return requestFocus(View.FOCUS_DOWN);
9154    }
9155
9156    /**
9157     * @return Whether any ancestor of this view blocks descendant focus.
9158     */
9159    private boolean hasAncestorThatBlocksDescendantFocus() {
9160        final boolean focusableInTouchMode = isFocusableInTouchMode();
9161        ViewParent ancestor = mParent;
9162        while (ancestor instanceof ViewGroup) {
9163            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9164            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9165                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9166                return true;
9167            } else {
9168                ancestor = vgAncestor.getParent();
9169            }
9170        }
9171        return false;
9172    }
9173
9174    /**
9175     * Gets the mode for determining whether this View is important for accessibility
9176     * which is if it fires accessibility events and if it is reported to
9177     * accessibility services that query the screen.
9178     *
9179     * @return The mode for determining whether a View is important for accessibility.
9180     *
9181     * @attr ref android.R.styleable#View_importantForAccessibility
9182     *
9183     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9184     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9185     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9186     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9187     */
9188    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9189            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9190            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9191            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9192            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9193                    to = "noHideDescendants")
9194        })
9195    public int getImportantForAccessibility() {
9196        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9197                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9198    }
9199
9200    /**
9201     * Sets the live region mode for this view. This indicates to accessibility
9202     * services whether they should automatically notify the user about changes
9203     * to the view's content description or text, or to the content descriptions
9204     * or text of the view's children (where applicable).
9205     * <p>
9206     * For example, in a login screen with a TextView that displays an "incorrect
9207     * password" notification, that view should be marked as a live region with
9208     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9209     * <p>
9210     * To disable change notifications for this view, use
9211     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9212     * mode for most views.
9213     * <p>
9214     * To indicate that the user should be notified of changes, use
9215     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9216     * <p>
9217     * If the view's changes should interrupt ongoing speech and notify the user
9218     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9219     *
9220     * @param mode The live region mode for this view, one of:
9221     *        <ul>
9222     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9223     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9224     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9225     *        </ul>
9226     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9227     */
9228    public void setAccessibilityLiveRegion(int mode) {
9229        if (mode != getAccessibilityLiveRegion()) {
9230            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9231            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9232                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9233            notifyViewAccessibilityStateChangedIfNeeded(
9234                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9235        }
9236    }
9237
9238    /**
9239     * Gets the live region mode for this View.
9240     *
9241     * @return The live region mode for the view.
9242     *
9243     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9244     *
9245     * @see #setAccessibilityLiveRegion(int)
9246     */
9247    public int getAccessibilityLiveRegion() {
9248        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9249                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9250    }
9251
9252    /**
9253     * Sets how to determine whether this view is important for accessibility
9254     * which is if it fires accessibility events and if it is reported to
9255     * accessibility services that query the screen.
9256     *
9257     * @param mode How to determine whether this view is important for accessibility.
9258     *
9259     * @attr ref android.R.styleable#View_importantForAccessibility
9260     *
9261     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9262     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9263     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9264     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9265     */
9266    public void setImportantForAccessibility(int mode) {
9267        final int oldMode = getImportantForAccessibility();
9268        if (mode != oldMode) {
9269            final boolean hideDescendants =
9270                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9271
9272            // If this node or its descendants are no longer important, try to
9273            // clear accessibility focus.
9274            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9275                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9276                if (focusHost != null) {
9277                    focusHost.clearAccessibilityFocus();
9278                }
9279            }
9280
9281            // If we're moving between AUTO and another state, we might not need
9282            // to send a subtree changed notification. We'll store the computed
9283            // importance, since we'll need to check it later to make sure.
9284            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9285                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9286            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9287            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9288            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9289                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9290            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9291                notifySubtreeAccessibilityStateChangedIfNeeded();
9292            } else {
9293                notifyViewAccessibilityStateChangedIfNeeded(
9294                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9295            }
9296        }
9297    }
9298
9299    /**
9300     * Returns the view within this view's hierarchy that is hosting
9301     * accessibility focus.
9302     *
9303     * @param searchDescendants whether to search for focus in descendant views
9304     * @return the view hosting accessibility focus, or {@code null}
9305     */
9306    private View findAccessibilityFocusHost(boolean searchDescendants) {
9307        if (isAccessibilityFocusedViewOrHost()) {
9308            return this;
9309        }
9310
9311        if (searchDescendants) {
9312            final ViewRootImpl viewRoot = getViewRootImpl();
9313            if (viewRoot != null) {
9314                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9315                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9316                    return focusHost;
9317                }
9318            }
9319        }
9320
9321        return null;
9322    }
9323
9324    /**
9325     * Computes whether this view should be exposed for accessibility. In
9326     * general, views that are interactive or provide information are exposed
9327     * while views that serve only as containers are hidden.
9328     * <p>
9329     * If an ancestor of this view has importance
9330     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9331     * returns <code>false</code>.
9332     * <p>
9333     * Otherwise, the value is computed according to the view's
9334     * {@link #getImportantForAccessibility()} value:
9335     * <ol>
9336     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9337     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9338     * </code>
9339     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9340     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9341     * view satisfies any of the following:
9342     * <ul>
9343     * <li>Is actionable, e.g. {@link #isClickable()},
9344     * {@link #isLongClickable()}, or {@link #isFocusable()}
9345     * <li>Has an {@link AccessibilityDelegate}
9346     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9347     * {@link OnKeyListener}, etc.
9348     * <li>Is an accessibility live region, e.g.
9349     * {@link #getAccessibilityLiveRegion()} is not
9350     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9351     * </ul>
9352     * </ol>
9353     *
9354     * @return Whether the view is exposed for accessibility.
9355     * @see #setImportantForAccessibility(int)
9356     * @see #getImportantForAccessibility()
9357     */
9358    public boolean isImportantForAccessibility() {
9359        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9360                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9361        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9362                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9363            return false;
9364        }
9365
9366        // Check parent mode to ensure we're not hidden.
9367        ViewParent parent = mParent;
9368        while (parent instanceof View) {
9369            if (((View) parent).getImportantForAccessibility()
9370                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9371                return false;
9372            }
9373            parent = parent.getParent();
9374        }
9375
9376        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9377                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9378                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9379    }
9380
9381    /**
9382     * Gets the parent for accessibility purposes. Note that the parent for
9383     * accessibility is not necessary the immediate parent. It is the first
9384     * predecessor that is important for accessibility.
9385     *
9386     * @return The parent for accessibility purposes.
9387     */
9388    public ViewParent getParentForAccessibility() {
9389        if (mParent instanceof View) {
9390            View parentView = (View) mParent;
9391            if (parentView.includeForAccessibility()) {
9392                return mParent;
9393            } else {
9394                return mParent.getParentForAccessibility();
9395            }
9396        }
9397        return null;
9398    }
9399
9400    /**
9401     * Adds the children of this View relevant for accessibility to the given list
9402     * as output. Since some Views are not important for accessibility the added
9403     * child views are not necessarily direct children of this view, rather they are
9404     * the first level of descendants important for accessibility.
9405     *
9406     * @param outChildren The output list that will receive children for accessibility.
9407     */
9408    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9409
9410    }
9411
9412    /**
9413     * Whether to regard this view for accessibility. A view is regarded for
9414     * accessibility if it is important for accessibility or the querying
9415     * accessibility service has explicitly requested that view not
9416     * important for accessibility are regarded.
9417     *
9418     * @return Whether to regard the view for accessibility.
9419     *
9420     * @hide
9421     */
9422    public boolean includeForAccessibility() {
9423        if (mAttachInfo != null) {
9424            return (mAttachInfo.mAccessibilityFetchFlags
9425                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9426                    || isImportantForAccessibility();
9427        }
9428        return false;
9429    }
9430
9431    /**
9432     * Returns whether the View is considered actionable from
9433     * accessibility perspective. Such view are important for
9434     * accessibility.
9435     *
9436     * @return True if the view is actionable for accessibility.
9437     *
9438     * @hide
9439     */
9440    public boolean isActionableForAccessibility() {
9441        return (isClickable() || isLongClickable() || isFocusable());
9442    }
9443
9444    /**
9445     * Returns whether the View has registered callbacks which makes it
9446     * important for accessibility.
9447     *
9448     * @return True if the view is actionable for accessibility.
9449     */
9450    private boolean hasListenersForAccessibility() {
9451        ListenerInfo info = getListenerInfo();
9452        return mTouchDelegate != null || info.mOnKeyListener != null
9453                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9454                || info.mOnHoverListener != null || info.mOnDragListener != null;
9455    }
9456
9457    /**
9458     * Notifies that the accessibility state of this view changed. The change
9459     * is local to this view and does not represent structural changes such
9460     * as children and parent. For example, the view became focusable. The
9461     * notification is at at most once every
9462     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9463     * to avoid unnecessary load to the system. Also once a view has a pending
9464     * notification this method is a NOP until the notification has been sent.
9465     *
9466     * @hide
9467     */
9468    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9469        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9470            return;
9471        }
9472        if (mSendViewStateChangedAccessibilityEvent == null) {
9473            mSendViewStateChangedAccessibilityEvent =
9474                    new SendViewStateChangedAccessibilityEvent();
9475        }
9476        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9477    }
9478
9479    /**
9480     * Notifies that the accessibility state of this view changed. The change
9481     * is *not* local to this view and does represent structural changes such
9482     * as children and parent. For example, the view size changed. The
9483     * notification is at at most once every
9484     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9485     * to avoid unnecessary load to the system. Also once a view has a pending
9486     * notification this method is a NOP until the notification has been sent.
9487     *
9488     * @hide
9489     */
9490    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9491        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9492            return;
9493        }
9494        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9495            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9496            if (mParent != null) {
9497                try {
9498                    mParent.notifySubtreeAccessibilityStateChanged(
9499                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9500                } catch (AbstractMethodError e) {
9501                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9502                            " does not fully implement ViewParent", e);
9503                }
9504            }
9505        }
9506    }
9507
9508    /**
9509     * Change the visibility of the View without triggering any other changes. This is
9510     * important for transitions, where visibility changes should not adjust focus or
9511     * trigger a new layout. This is only used when the visibility has already been changed
9512     * and we need a transient value during an animation. When the animation completes,
9513     * the original visibility value is always restored.
9514     *
9515     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9516     * @hide
9517     */
9518    public void setTransitionVisibility(@Visibility int visibility) {
9519        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9520    }
9521
9522    /**
9523     * Reset the flag indicating the accessibility state of the subtree rooted
9524     * at this view changed.
9525     */
9526    void resetSubtreeAccessibilityStateChanged() {
9527        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9528    }
9529
9530    /**
9531     * Report an accessibility action to this view's parents for delegated processing.
9532     *
9533     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9534     * call this method to delegate an accessibility action to a supporting parent. If the parent
9535     * returns true from its
9536     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9537     * method this method will return true to signify that the action was consumed.</p>
9538     *
9539     * <p>This method is useful for implementing nested scrolling child views. If
9540     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9541     * a custom view implementation may invoke this method to allow a parent to consume the
9542     * scroll first. If this method returns true the custom view should skip its own scrolling
9543     * behavior.</p>
9544     *
9545     * @param action Accessibility action to delegate
9546     * @param arguments Optional action arguments
9547     * @return true if the action was consumed by a parent
9548     */
9549    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9550        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9551            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9552                return true;
9553            }
9554        }
9555        return false;
9556    }
9557
9558    /**
9559     * Performs the specified accessibility action on the view. For
9560     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9561     * <p>
9562     * If an {@link AccessibilityDelegate} has been specified via calling
9563     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9564     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9565     * is responsible for handling this call.
9566     * </p>
9567     *
9568     * <p>The default implementation will delegate
9569     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9570     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9571     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9572     *
9573     * @param action The action to perform.
9574     * @param arguments Optional action arguments.
9575     * @return Whether the action was performed.
9576     */
9577    public boolean performAccessibilityAction(int action, Bundle arguments) {
9578      if (mAccessibilityDelegate != null) {
9579          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9580      } else {
9581          return performAccessibilityActionInternal(action, arguments);
9582      }
9583    }
9584
9585   /**
9586    * @see #performAccessibilityAction(int, Bundle)
9587    *
9588    * Note: Called from the default {@link AccessibilityDelegate}.
9589    *
9590    * @hide
9591    */
9592    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9593        if (isNestedScrollingEnabled()
9594                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9595                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9596                || action == R.id.accessibilityActionScrollUp
9597                || action == R.id.accessibilityActionScrollLeft
9598                || action == R.id.accessibilityActionScrollDown
9599                || action == R.id.accessibilityActionScrollRight)) {
9600            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9601                return true;
9602            }
9603        }
9604
9605        switch (action) {
9606            case AccessibilityNodeInfo.ACTION_CLICK: {
9607                if (isClickable()) {
9608                    performClick();
9609                    return true;
9610                }
9611            } break;
9612            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9613                if (isLongClickable()) {
9614                    performLongClick();
9615                    return true;
9616                }
9617            } break;
9618            case AccessibilityNodeInfo.ACTION_FOCUS: {
9619                if (!hasFocus()) {
9620                    // Get out of touch mode since accessibility
9621                    // wants to move focus around.
9622                    getViewRootImpl().ensureTouchMode(false);
9623                    return requestFocus();
9624                }
9625            } break;
9626            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9627                if (hasFocus()) {
9628                    clearFocus();
9629                    return !isFocused();
9630                }
9631            } break;
9632            case AccessibilityNodeInfo.ACTION_SELECT: {
9633                if (!isSelected()) {
9634                    setSelected(true);
9635                    return isSelected();
9636                }
9637            } break;
9638            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9639                if (isSelected()) {
9640                    setSelected(false);
9641                    return !isSelected();
9642                }
9643            } break;
9644            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9645                if (!isAccessibilityFocused()) {
9646                    return requestAccessibilityFocus();
9647                }
9648            } break;
9649            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
9650                if (isAccessibilityFocused()) {
9651                    clearAccessibilityFocus();
9652                    return true;
9653                }
9654            } break;
9655            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
9656                if (arguments != null) {
9657                    final int granularity = arguments.getInt(
9658                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9659                    final boolean extendSelection = arguments.getBoolean(
9660                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9661                    return traverseAtGranularity(granularity, true, extendSelection);
9662                }
9663            } break;
9664            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9665                if (arguments != null) {
9666                    final int granularity = arguments.getInt(
9667                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9668                    final boolean extendSelection = arguments.getBoolean(
9669                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9670                    return traverseAtGranularity(granularity, false, extendSelection);
9671                }
9672            } break;
9673            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9674                CharSequence text = getIterableTextForAccessibility();
9675                if (text == null) {
9676                    return false;
9677                }
9678                final int start = (arguments != null) ? arguments.getInt(
9679                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9680                final int end = (arguments != null) ? arguments.getInt(
9681                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9682                // Only cursor position can be specified (selection length == 0)
9683                if ((getAccessibilitySelectionStart() != start
9684                        || getAccessibilitySelectionEnd() != end)
9685                        && (start == end)) {
9686                    setAccessibilitySelection(start, end);
9687                    notifyViewAccessibilityStateChangedIfNeeded(
9688                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9689                    return true;
9690                }
9691            } break;
9692            case R.id.accessibilityActionShowOnScreen: {
9693                if (mAttachInfo != null) {
9694                    final Rect r = mAttachInfo.mTmpInvalRect;
9695                    getDrawingRect(r);
9696                    return requestRectangleOnScreen(r, true);
9697                }
9698            } break;
9699            case R.id.accessibilityActionContextClick: {
9700                if (isContextClickable()) {
9701                    performContextClick();
9702                    return true;
9703                }
9704            } break;
9705        }
9706        return false;
9707    }
9708
9709    private boolean traverseAtGranularity(int granularity, boolean forward,
9710            boolean extendSelection) {
9711        CharSequence text = getIterableTextForAccessibility();
9712        if (text == null || text.length() == 0) {
9713            return false;
9714        }
9715        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9716        if (iterator == null) {
9717            return false;
9718        }
9719        int current = getAccessibilitySelectionEnd();
9720        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9721            current = forward ? 0 : text.length();
9722        }
9723        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9724        if (range == null) {
9725            return false;
9726        }
9727        final int segmentStart = range[0];
9728        final int segmentEnd = range[1];
9729        int selectionStart;
9730        int selectionEnd;
9731        if (extendSelection && isAccessibilitySelectionExtendable()) {
9732            selectionStart = getAccessibilitySelectionStart();
9733            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9734                selectionStart = forward ? segmentStart : segmentEnd;
9735            }
9736            selectionEnd = forward ? segmentEnd : segmentStart;
9737        } else {
9738            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9739        }
9740        setAccessibilitySelection(selectionStart, selectionEnd);
9741        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9742                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9743        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9744        return true;
9745    }
9746
9747    /**
9748     * Gets the text reported for accessibility purposes.
9749     *
9750     * @return The accessibility text.
9751     *
9752     * @hide
9753     */
9754    public CharSequence getIterableTextForAccessibility() {
9755        return getContentDescription();
9756    }
9757
9758    /**
9759     * Gets whether accessibility selection can be extended.
9760     *
9761     * @return If selection is extensible.
9762     *
9763     * @hide
9764     */
9765    public boolean isAccessibilitySelectionExtendable() {
9766        return false;
9767    }
9768
9769    /**
9770     * @hide
9771     */
9772    public int getAccessibilitySelectionStart() {
9773        return mAccessibilityCursorPosition;
9774    }
9775
9776    /**
9777     * @hide
9778     */
9779    public int getAccessibilitySelectionEnd() {
9780        return getAccessibilitySelectionStart();
9781    }
9782
9783    /**
9784     * @hide
9785     */
9786    public void setAccessibilitySelection(int start, int end) {
9787        if (start ==  end && end == mAccessibilityCursorPosition) {
9788            return;
9789        }
9790        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9791            mAccessibilityCursorPosition = start;
9792        } else {
9793            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9794        }
9795        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9796    }
9797
9798    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9799            int fromIndex, int toIndex) {
9800        if (mParent == null) {
9801            return;
9802        }
9803        AccessibilityEvent event = AccessibilityEvent.obtain(
9804                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9805        onInitializeAccessibilityEvent(event);
9806        onPopulateAccessibilityEvent(event);
9807        event.setFromIndex(fromIndex);
9808        event.setToIndex(toIndex);
9809        event.setAction(action);
9810        event.setMovementGranularity(granularity);
9811        mParent.requestSendAccessibilityEvent(this, event);
9812    }
9813
9814    /**
9815     * @hide
9816     */
9817    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9818        switch (granularity) {
9819            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9820                CharSequence text = getIterableTextForAccessibility();
9821                if (text != null && text.length() > 0) {
9822                    CharacterTextSegmentIterator iterator =
9823                        CharacterTextSegmentIterator.getInstance(
9824                                mContext.getResources().getConfiguration().locale);
9825                    iterator.initialize(text.toString());
9826                    return iterator;
9827                }
9828            } break;
9829            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9830                CharSequence text = getIterableTextForAccessibility();
9831                if (text != null && text.length() > 0) {
9832                    WordTextSegmentIterator iterator =
9833                        WordTextSegmentIterator.getInstance(
9834                                mContext.getResources().getConfiguration().locale);
9835                    iterator.initialize(text.toString());
9836                    return iterator;
9837                }
9838            } break;
9839            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9840                CharSequence text = getIterableTextForAccessibility();
9841                if (text != null && text.length() > 0) {
9842                    ParagraphTextSegmentIterator iterator =
9843                        ParagraphTextSegmentIterator.getInstance();
9844                    iterator.initialize(text.toString());
9845                    return iterator;
9846                }
9847            } break;
9848        }
9849        return null;
9850    }
9851
9852    /**
9853     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
9854     * and {@link #onFinishTemporaryDetach()}.
9855     *
9856     * <p>This method always returns {@code true} when called directly or indirectly from
9857     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
9858     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
9859     * <ul>
9860     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
9861     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
9862     * </ul>
9863     * </p>
9864     *
9865     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
9866     * and {@link #onFinishTemporaryDetach()}.
9867     */
9868    public final boolean isTemporarilyDetached() {
9869        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
9870    }
9871
9872    /**
9873     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
9874     * a container View.
9875     */
9876    @CallSuper
9877    public void dispatchStartTemporaryDetach() {
9878        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
9879        onStartTemporaryDetach();
9880    }
9881
9882    /**
9883     * This is called when a container is going to temporarily detach a child, with
9884     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9885     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9886     * {@link #onDetachedFromWindow()} when the container is done.
9887     */
9888    public void onStartTemporaryDetach() {
9889        removeUnsetPressCallback();
9890        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9891    }
9892
9893    /**
9894     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
9895     * a container View.
9896     */
9897    @CallSuper
9898    public void dispatchFinishTemporaryDetach() {
9899        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
9900        onFinishTemporaryDetach();
9901        if (hasWindowFocus() && hasFocus()) {
9902            InputMethodManager.getInstance().focusIn(this);
9903        }
9904    }
9905
9906    /**
9907     * Called after {@link #onStartTemporaryDetach} when the container is done
9908     * changing the view.
9909     */
9910    public void onFinishTemporaryDetach() {
9911    }
9912
9913    /**
9914     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9915     * for this view's window.  Returns null if the view is not currently attached
9916     * to the window.  Normally you will not need to use this directly, but
9917     * just use the standard high-level event callbacks like
9918     * {@link #onKeyDown(int, KeyEvent)}.
9919     */
9920    public KeyEvent.DispatcherState getKeyDispatcherState() {
9921        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9922    }
9923
9924    /**
9925     * Dispatch a key event before it is processed by any input method
9926     * associated with the view hierarchy.  This can be used to intercept
9927     * key events in special situations before the IME consumes them; a
9928     * typical example would be handling the BACK key to update the application's
9929     * UI instead of allowing the IME to see it and close itself.
9930     *
9931     * @param event The key event to be dispatched.
9932     * @return True if the event was handled, false otherwise.
9933     */
9934    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9935        return onKeyPreIme(event.getKeyCode(), event);
9936    }
9937
9938    /**
9939     * Dispatch a key event to the next view on the focus path. This path runs
9940     * from the top of the view tree down to the currently focused view. If this
9941     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9942     * the next node down the focus path. This method also fires any key
9943     * listeners.
9944     *
9945     * @param event The key event to be dispatched.
9946     * @return True if the event was handled, false otherwise.
9947     */
9948    public boolean dispatchKeyEvent(KeyEvent event) {
9949        if (mInputEventConsistencyVerifier != null) {
9950            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9951        }
9952
9953        // Give any attached key listener a first crack at the event.
9954        //noinspection SimplifiableIfStatement
9955        ListenerInfo li = mListenerInfo;
9956        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9957                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9958            return true;
9959        }
9960
9961        if (event.dispatch(this, mAttachInfo != null
9962                ? mAttachInfo.mKeyDispatchState : null, this)) {
9963            return true;
9964        }
9965
9966        if (mInputEventConsistencyVerifier != null) {
9967            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9968        }
9969        return false;
9970    }
9971
9972    /**
9973     * Dispatches a key shortcut event.
9974     *
9975     * @param event The key event to be dispatched.
9976     * @return True if the event was handled by the view, false otherwise.
9977     */
9978    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9979        return onKeyShortcut(event.getKeyCode(), event);
9980    }
9981
9982    /**
9983     * Pass the touch screen motion event down to the target view, or this
9984     * view if it is the target.
9985     *
9986     * @param event The motion event to be dispatched.
9987     * @return True if the event was handled by the view, false otherwise.
9988     */
9989    public boolean dispatchTouchEvent(MotionEvent event) {
9990        // If the event should be handled by accessibility focus first.
9991        if (event.isTargetAccessibilityFocus()) {
9992            // We don't have focus or no virtual descendant has it, do not handle the event.
9993            if (!isAccessibilityFocusedViewOrHost()) {
9994                return false;
9995            }
9996            // We have focus and got the event, then use normal event dispatch.
9997            event.setTargetAccessibilityFocus(false);
9998        }
9999
10000        boolean result = false;
10001
10002        if (mInputEventConsistencyVerifier != null) {
10003            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
10004        }
10005
10006        final int actionMasked = event.getActionMasked();
10007        if (actionMasked == MotionEvent.ACTION_DOWN) {
10008            // Defensive cleanup for new gesture
10009            stopNestedScroll();
10010        }
10011
10012        if (onFilterTouchEventForSecurity(event)) {
10013            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10014                result = true;
10015            }
10016            //noinspection SimplifiableIfStatement
10017            ListenerInfo li = mListenerInfo;
10018            if (li != null && li.mOnTouchListener != null
10019                    && (mViewFlags & ENABLED_MASK) == ENABLED
10020                    && li.mOnTouchListener.onTouch(this, event)) {
10021                result = true;
10022            }
10023
10024            if (!result && onTouchEvent(event)) {
10025                result = true;
10026            }
10027        }
10028
10029        if (!result && mInputEventConsistencyVerifier != null) {
10030            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10031        }
10032
10033        // Clean up after nested scrolls if this is the end of a gesture;
10034        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10035        // of the gesture.
10036        if (actionMasked == MotionEvent.ACTION_UP ||
10037                actionMasked == MotionEvent.ACTION_CANCEL ||
10038                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10039            stopNestedScroll();
10040        }
10041
10042        return result;
10043    }
10044
10045    boolean isAccessibilityFocusedViewOrHost() {
10046        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10047                .getAccessibilityFocusedHost() == this);
10048    }
10049
10050    /**
10051     * Filter the touch event to apply security policies.
10052     *
10053     * @param event The motion event to be filtered.
10054     * @return True if the event should be dispatched, false if the event should be dropped.
10055     *
10056     * @see #getFilterTouchesWhenObscured
10057     */
10058    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10059        //noinspection RedundantIfStatement
10060        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10061                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10062            // Window is obscured, drop this touch.
10063            return false;
10064        }
10065        return true;
10066    }
10067
10068    /**
10069     * Pass a trackball motion event down to the focused view.
10070     *
10071     * @param event The motion event to be dispatched.
10072     * @return True if the event was handled by the view, false otherwise.
10073     */
10074    public boolean dispatchTrackballEvent(MotionEvent event) {
10075        if (mInputEventConsistencyVerifier != null) {
10076            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10077        }
10078
10079        return onTrackballEvent(event);
10080    }
10081
10082    /**
10083     * Dispatch a generic motion event.
10084     * <p>
10085     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10086     * are delivered to the view under the pointer.  All other generic motion events are
10087     * delivered to the focused view.  Hover events are handled specially and are delivered
10088     * to {@link #onHoverEvent(MotionEvent)}.
10089     * </p>
10090     *
10091     * @param event The motion event to be dispatched.
10092     * @return True if the event was handled by the view, false otherwise.
10093     */
10094    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10095        if (mInputEventConsistencyVerifier != null) {
10096            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10097        }
10098
10099        final int source = event.getSource();
10100        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10101            final int action = event.getAction();
10102            if (action == MotionEvent.ACTION_HOVER_ENTER
10103                    || action == MotionEvent.ACTION_HOVER_MOVE
10104                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10105                if (dispatchHoverEvent(event)) {
10106                    return true;
10107                }
10108            } else if (dispatchGenericPointerEvent(event)) {
10109                return true;
10110            }
10111        } else if (dispatchGenericFocusedEvent(event)) {
10112            return true;
10113        }
10114
10115        if (dispatchGenericMotionEventInternal(event)) {
10116            return true;
10117        }
10118
10119        if (mInputEventConsistencyVerifier != null) {
10120            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10121        }
10122        return false;
10123    }
10124
10125    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10126        //noinspection SimplifiableIfStatement
10127        ListenerInfo li = mListenerInfo;
10128        if (li != null && li.mOnGenericMotionListener != null
10129                && (mViewFlags & ENABLED_MASK) == ENABLED
10130                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10131            return true;
10132        }
10133
10134        if (onGenericMotionEvent(event)) {
10135            return true;
10136        }
10137
10138        final int actionButton = event.getActionButton();
10139        switch (event.getActionMasked()) {
10140            case MotionEvent.ACTION_BUTTON_PRESS:
10141                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10142                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10143                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10144                    if (performContextClick(event.getX(), event.getY())) {
10145                        mInContextButtonPress = true;
10146                        setPressed(true, event.getX(), event.getY());
10147                        removeTapCallback();
10148                        removeLongPressCallback();
10149                        return true;
10150                    }
10151                }
10152                break;
10153
10154            case MotionEvent.ACTION_BUTTON_RELEASE:
10155                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10156                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10157                    mInContextButtonPress = false;
10158                    mIgnoreNextUpEvent = true;
10159                }
10160                break;
10161        }
10162
10163        if (mInputEventConsistencyVerifier != null) {
10164            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10165        }
10166        return false;
10167    }
10168
10169    /**
10170     * Dispatch a hover event.
10171     * <p>
10172     * Do not call this method directly.
10173     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10174     * </p>
10175     *
10176     * @param event The motion event to be dispatched.
10177     * @return True if the event was handled by the view, false otherwise.
10178     */
10179    protected boolean dispatchHoverEvent(MotionEvent event) {
10180        ListenerInfo li = mListenerInfo;
10181        //noinspection SimplifiableIfStatement
10182        if (li != null && li.mOnHoverListener != null
10183                && (mViewFlags & ENABLED_MASK) == ENABLED
10184                && li.mOnHoverListener.onHover(this, event)) {
10185            return true;
10186        }
10187
10188        return onHoverEvent(event);
10189    }
10190
10191    /**
10192     * Returns true if the view has a child to which it has recently sent
10193     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10194     * it does not have a hovered child, then it must be the innermost hovered view.
10195     * @hide
10196     */
10197    protected boolean hasHoveredChild() {
10198        return false;
10199    }
10200
10201    /**
10202     * Dispatch a generic motion event to the view under the first pointer.
10203     * <p>
10204     * Do not call this method directly.
10205     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10206     * </p>
10207     *
10208     * @param event The motion event to be dispatched.
10209     * @return True if the event was handled by the view, false otherwise.
10210     */
10211    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10212        return false;
10213    }
10214
10215    /**
10216     * Dispatch a generic motion event to the currently focused view.
10217     * <p>
10218     * Do not call this method directly.
10219     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10220     * </p>
10221     *
10222     * @param event The motion event to be dispatched.
10223     * @return True if the event was handled by the view, false otherwise.
10224     */
10225    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10226        return false;
10227    }
10228
10229    /**
10230     * Dispatch a pointer event.
10231     * <p>
10232     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10233     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10234     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10235     * and should not be expected to handle other pointing device features.
10236     * </p>
10237     *
10238     * @param event The motion event to be dispatched.
10239     * @return True if the event was handled by the view, false otherwise.
10240     * @hide
10241     */
10242    public final boolean dispatchPointerEvent(MotionEvent event) {
10243        if (event.isTouchEvent()) {
10244            return dispatchTouchEvent(event);
10245        } else {
10246            return dispatchGenericMotionEvent(event);
10247        }
10248    }
10249
10250    /**
10251     * Called when the window containing this view gains or loses window focus.
10252     * ViewGroups should override to route to their children.
10253     *
10254     * @param hasFocus True if the window containing this view now has focus,
10255     *        false otherwise.
10256     */
10257    public void dispatchWindowFocusChanged(boolean hasFocus) {
10258        onWindowFocusChanged(hasFocus);
10259    }
10260
10261    /**
10262     * Called when the window containing this view gains or loses focus.  Note
10263     * that this is separate from view focus: to receive key events, both
10264     * your view and its window must have focus.  If a window is displayed
10265     * on top of yours that takes input focus, then your own window will lose
10266     * focus but the view focus will remain unchanged.
10267     *
10268     * @param hasWindowFocus True if the window containing this view now has
10269     *        focus, false otherwise.
10270     */
10271    public void onWindowFocusChanged(boolean hasWindowFocus) {
10272        InputMethodManager imm = InputMethodManager.peekInstance();
10273        if (!hasWindowFocus) {
10274            if (isPressed()) {
10275                setPressed(false);
10276            }
10277            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10278                imm.focusOut(this);
10279            }
10280            removeLongPressCallback();
10281            removeTapCallback();
10282            onFocusLost();
10283        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10284            imm.focusIn(this);
10285        }
10286        refreshDrawableState();
10287    }
10288
10289    /**
10290     * Returns true if this view is in a window that currently has window focus.
10291     * Note that this is not the same as the view itself having focus.
10292     *
10293     * @return True if this view is in a window that currently has window focus.
10294     */
10295    public boolean hasWindowFocus() {
10296        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10297    }
10298
10299    /**
10300     * Dispatch a view visibility change down the view hierarchy.
10301     * ViewGroups should override to route to their children.
10302     * @param changedView The view whose visibility changed. Could be 'this' or
10303     * an ancestor view.
10304     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10305     * {@link #INVISIBLE} or {@link #GONE}.
10306     */
10307    protected void dispatchVisibilityChanged(@NonNull View changedView,
10308            @Visibility int visibility) {
10309        onVisibilityChanged(changedView, visibility);
10310    }
10311
10312    /**
10313     * Called when the visibility of the view or an ancestor of the view has
10314     * changed.
10315     *
10316     * @param changedView The view whose visibility changed. May be
10317     *                    {@code this} or an ancestor view.
10318     * @param visibility The new visibility, one of {@link #VISIBLE},
10319     *                   {@link #INVISIBLE} or {@link #GONE}.
10320     */
10321    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10322    }
10323
10324    /**
10325     * Dispatch a hint about whether this view is displayed. For instance, when
10326     * a View moves out of the screen, it might receives a display hint indicating
10327     * the view is not displayed. Applications should not <em>rely</em> on this hint
10328     * as there is no guarantee that they will receive one.
10329     *
10330     * @param hint A hint about whether or not this view is displayed:
10331     * {@link #VISIBLE} or {@link #INVISIBLE}.
10332     */
10333    public void dispatchDisplayHint(@Visibility int hint) {
10334        onDisplayHint(hint);
10335    }
10336
10337    /**
10338     * Gives this view a hint about whether is displayed or not. For instance, when
10339     * a View moves out of the screen, it might receives a display hint indicating
10340     * the view is not displayed. Applications should not <em>rely</em> on this hint
10341     * as there is no guarantee that they will receive one.
10342     *
10343     * @param hint A hint about whether or not this view is displayed:
10344     * {@link #VISIBLE} or {@link #INVISIBLE}.
10345     */
10346    protected void onDisplayHint(@Visibility int hint) {
10347    }
10348
10349    /**
10350     * Dispatch a window visibility change down the view hierarchy.
10351     * ViewGroups should override to route to their children.
10352     *
10353     * @param visibility The new visibility of the window.
10354     *
10355     * @see #onWindowVisibilityChanged(int)
10356     */
10357    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10358        onWindowVisibilityChanged(visibility);
10359    }
10360
10361    /**
10362     * Called when the window containing has change its visibility
10363     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10364     * that this tells you whether or not your window is being made visible
10365     * to the window manager; this does <em>not</em> tell you whether or not
10366     * your window is obscured by other windows on the screen, even if it
10367     * is itself visible.
10368     *
10369     * @param visibility The new visibility of the window.
10370     */
10371    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10372        if (visibility == VISIBLE) {
10373            initialAwakenScrollBars();
10374        }
10375    }
10376
10377    /**
10378     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10379     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10380     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10381     *
10382     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10383     *                  ancestors or by window visibility
10384     * @return true if this view is visible to the user, not counting clipping or overlapping
10385     */
10386    boolean dispatchVisibilityAggregated(boolean isVisible) {
10387        final boolean thisVisible = getVisibility() == VISIBLE;
10388        // If we're not visible but something is telling us we are, ignore it.
10389        if (thisVisible || !isVisible) {
10390            onVisibilityAggregated(isVisible);
10391        }
10392        return thisVisible && isVisible;
10393    }
10394
10395    /**
10396     * Called when the user-visibility of this View is potentially affected by a change
10397     * to this view itself, an ancestor view or the window this view is attached to.
10398     *
10399     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10400     *                  and this view's window is also visible
10401     */
10402    @CallSuper
10403    public void onVisibilityAggregated(boolean isVisible) {
10404        if (isVisible && mAttachInfo != null) {
10405            initialAwakenScrollBars();
10406        }
10407
10408        final Drawable dr = mBackground;
10409        if (dr != null && isVisible != dr.isVisible()) {
10410            dr.setVisible(isVisible, false);
10411        }
10412        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10413        if (fg != null && isVisible != fg.isVisible()) {
10414            fg.setVisible(isVisible, false);
10415        }
10416    }
10417
10418    /**
10419     * Returns the current visibility of the window this view is attached to
10420     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10421     *
10422     * @return Returns the current visibility of the view's window.
10423     */
10424    @Visibility
10425    public int getWindowVisibility() {
10426        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10427    }
10428
10429    /**
10430     * Retrieve the overall visible display size in which the window this view is
10431     * attached to has been positioned in.  This takes into account screen
10432     * decorations above the window, for both cases where the window itself
10433     * is being position inside of them or the window is being placed under
10434     * then and covered insets are used for the window to position its content
10435     * inside.  In effect, this tells you the available area where content can
10436     * be placed and remain visible to users.
10437     *
10438     * <p>This function requires an IPC back to the window manager to retrieve
10439     * the requested information, so should not be used in performance critical
10440     * code like drawing.
10441     *
10442     * @param outRect Filled in with the visible display frame.  If the view
10443     * is not attached to a window, this is simply the raw display size.
10444     */
10445    public void getWindowVisibleDisplayFrame(Rect outRect) {
10446        if (mAttachInfo != null) {
10447            try {
10448                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10449            } catch (RemoteException e) {
10450                return;
10451            }
10452            // XXX This is really broken, and probably all needs to be done
10453            // in the window manager, and we need to know more about whether
10454            // we want the area behind or in front of the IME.
10455            final Rect insets = mAttachInfo.mVisibleInsets;
10456            outRect.left += insets.left;
10457            outRect.top += insets.top;
10458            outRect.right -= insets.right;
10459            outRect.bottom -= insets.bottom;
10460            return;
10461        }
10462        // The view is not attached to a display so we don't have a context.
10463        // Make a best guess about the display size.
10464        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10465        d.getRectSize(outRect);
10466    }
10467
10468    /**
10469     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10470     * is currently in without any insets.
10471     *
10472     * @hide
10473     */
10474    public void getWindowDisplayFrame(Rect outRect) {
10475        if (mAttachInfo != null) {
10476            try {
10477                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10478            } catch (RemoteException e) {
10479                return;
10480            }
10481            return;
10482        }
10483        // The view is not attached to a display so we don't have a context.
10484        // Make a best guess about the display size.
10485        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10486        d.getRectSize(outRect);
10487    }
10488
10489    /**
10490     * Dispatch a notification about a resource configuration change down
10491     * the view hierarchy.
10492     * ViewGroups should override to route to their children.
10493     *
10494     * @param newConfig The new resource configuration.
10495     *
10496     * @see #onConfigurationChanged(android.content.res.Configuration)
10497     */
10498    public void dispatchConfigurationChanged(Configuration newConfig) {
10499        onConfigurationChanged(newConfig);
10500    }
10501
10502    /**
10503     * Called when the current configuration of the resources being used
10504     * by the application have changed.  You can use this to decide when
10505     * to reload resources that can changed based on orientation and other
10506     * configuration characteristics.  You only need to use this if you are
10507     * not relying on the normal {@link android.app.Activity} mechanism of
10508     * recreating the activity instance upon a configuration change.
10509     *
10510     * @param newConfig The new resource configuration.
10511     */
10512    protected void onConfigurationChanged(Configuration newConfig) {
10513    }
10514
10515    /**
10516     * Private function to aggregate all per-view attributes in to the view
10517     * root.
10518     */
10519    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10520        performCollectViewAttributes(attachInfo, visibility);
10521    }
10522
10523    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10524        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10525            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10526                attachInfo.mKeepScreenOn = true;
10527            }
10528            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10529            ListenerInfo li = mListenerInfo;
10530            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10531                attachInfo.mHasSystemUiListeners = true;
10532            }
10533        }
10534    }
10535
10536    void needGlobalAttributesUpdate(boolean force) {
10537        final AttachInfo ai = mAttachInfo;
10538        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10539            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10540                    || ai.mHasSystemUiListeners) {
10541                ai.mRecomputeGlobalAttributes = true;
10542            }
10543        }
10544    }
10545
10546    /**
10547     * Returns whether the device is currently in touch mode.  Touch mode is entered
10548     * once the user begins interacting with the device by touch, and affects various
10549     * things like whether focus is always visible to the user.
10550     *
10551     * @return Whether the device is in touch mode.
10552     */
10553    @ViewDebug.ExportedProperty
10554    public boolean isInTouchMode() {
10555        if (mAttachInfo != null) {
10556            return mAttachInfo.mInTouchMode;
10557        } else {
10558            return ViewRootImpl.isInTouchMode();
10559        }
10560    }
10561
10562    /**
10563     * Returns the context the view is running in, through which it can
10564     * access the current theme, resources, etc.
10565     *
10566     * @return The view's Context.
10567     */
10568    @ViewDebug.CapturedViewProperty
10569    public final Context getContext() {
10570        return mContext;
10571    }
10572
10573    /**
10574     * Handle a key event before it is processed by any input method
10575     * associated with the view hierarchy.  This can be used to intercept
10576     * key events in special situations before the IME consumes them; a
10577     * typical example would be handling the BACK key to update the application's
10578     * UI instead of allowing the IME to see it and close itself.
10579     *
10580     * @param keyCode The value in event.getKeyCode().
10581     * @param event Description of the key event.
10582     * @return If you handled the event, return true. If you want to allow the
10583     *         event to be handled by the next receiver, return false.
10584     */
10585    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10586        return false;
10587    }
10588
10589    /**
10590     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10591     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10592     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10593     * is released, if the view is enabled and clickable.
10594     * <p>
10595     * Key presses in software keyboards will generally NOT trigger this
10596     * listener, although some may elect to do so in some situations. Do not
10597     * rely on this to catch software key presses.
10598     *
10599     * @param keyCode a key code that represents the button pressed, from
10600     *                {@link android.view.KeyEvent}
10601     * @param event the KeyEvent object that defines the button action
10602     */
10603    public boolean onKeyDown(int keyCode, KeyEvent event) {
10604        if (KeyEvent.isConfirmKey(keyCode)) {
10605            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10606                return true;
10607            }
10608
10609            // Long clickable items don't necessarily have to be clickable.
10610            if (((mViewFlags & CLICKABLE) == CLICKABLE
10611                    || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10612                    && (event.getRepeatCount() == 0)) {
10613                // For the purposes of menu anchoring and drawable hotspots,
10614                // key events are considered to be at the center of the view.
10615                final float x = getWidth() / 2f;
10616                final float y = getHeight() / 2f;
10617                setPressed(true, x, y);
10618                checkForLongClick(0, x, y);
10619                return true;
10620            }
10621        }
10622
10623        return false;
10624    }
10625
10626    /**
10627     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10628     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10629     * the event).
10630     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10631     * although some may elect to do so in some situations. Do not rely on this to
10632     * catch software key presses.
10633     */
10634    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10635        return false;
10636    }
10637
10638    /**
10639     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10640     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10641     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
10642     * or {@link KeyEvent#KEYCODE_SPACE} is released.
10643     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10644     * although some may elect to do so in some situations. Do not rely on this to
10645     * catch software key presses.
10646     *
10647     * @param keyCode A key code that represents the button pressed, from
10648     *                {@link android.view.KeyEvent}.
10649     * @param event   The KeyEvent object that defines the button action.
10650     */
10651    public boolean onKeyUp(int keyCode, KeyEvent event) {
10652        if (KeyEvent.isConfirmKey(keyCode)) {
10653            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10654                return true;
10655            }
10656            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
10657                setPressed(false);
10658
10659                if (!mHasPerformedLongPress) {
10660                    // This is a tap, so remove the longpress check
10661                    removeLongPressCallback();
10662                    return performClick();
10663                }
10664            }
10665        }
10666        return false;
10667    }
10668
10669    /**
10670     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
10671     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
10672     * the event).
10673     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10674     * although some may elect to do so in some situations. Do not rely on this to
10675     * catch software key presses.
10676     *
10677     * @param keyCode     A key code that represents the button pressed, from
10678     *                    {@link android.view.KeyEvent}.
10679     * @param repeatCount The number of times the action was made.
10680     * @param event       The KeyEvent object that defines the button action.
10681     */
10682    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
10683        return false;
10684    }
10685
10686    /**
10687     * Called on the focused view when a key shortcut event is not handled.
10688     * Override this method to implement local key shortcuts for the View.
10689     * Key shortcuts can also be implemented by setting the
10690     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
10691     *
10692     * @param keyCode The value in event.getKeyCode().
10693     * @param event Description of the key event.
10694     * @return If you handled the event, return true. If you want to allow the
10695     *         event to be handled by the next receiver, return false.
10696     */
10697    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
10698        return false;
10699    }
10700
10701    /**
10702     * Check whether the called view is a text editor, in which case it
10703     * would make sense to automatically display a soft input window for
10704     * it.  Subclasses should override this if they implement
10705     * {@link #onCreateInputConnection(EditorInfo)} to return true if
10706     * a call on that method would return a non-null InputConnection, and
10707     * they are really a first-class editor that the user would normally
10708     * start typing on when the go into a window containing your view.
10709     *
10710     * <p>The default implementation always returns false.  This does
10711     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
10712     * will not be called or the user can not otherwise perform edits on your
10713     * view; it is just a hint to the system that this is not the primary
10714     * purpose of this view.
10715     *
10716     * @return Returns true if this view is a text editor, else false.
10717     */
10718    public boolean onCheckIsTextEditor() {
10719        return false;
10720    }
10721
10722    /**
10723     * Create a new InputConnection for an InputMethod to interact
10724     * with the view.  The default implementation returns null, since it doesn't
10725     * support input methods.  You can override this to implement such support.
10726     * This is only needed for views that take focus and text input.
10727     *
10728     * <p>When implementing this, you probably also want to implement
10729     * {@link #onCheckIsTextEditor()} to indicate you will return a
10730     * non-null InputConnection.</p>
10731     *
10732     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
10733     * object correctly and in its entirety, so that the connected IME can rely
10734     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
10735     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
10736     * must be filled in with the correct cursor position for IMEs to work correctly
10737     * with your application.</p>
10738     *
10739     * @param outAttrs Fill in with attribute information about the connection.
10740     */
10741    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
10742        return null;
10743    }
10744
10745    /**
10746     * Called by the {@link android.view.inputmethod.InputMethodManager}
10747     * when a view who is not the current
10748     * input connection target is trying to make a call on the manager.  The
10749     * default implementation returns false; you can override this to return
10750     * true for certain views if you are performing InputConnection proxying
10751     * to them.
10752     * @param view The View that is making the InputMethodManager call.
10753     * @return Return true to allow the call, false to reject.
10754     */
10755    public boolean checkInputConnectionProxy(View view) {
10756        return false;
10757    }
10758
10759    /**
10760     * Show the context menu for this view. It is not safe to hold on to the
10761     * menu after returning from this method.
10762     *
10763     * You should normally not overload this method. Overload
10764     * {@link #onCreateContextMenu(ContextMenu)} or define an
10765     * {@link OnCreateContextMenuListener} to add items to the context menu.
10766     *
10767     * @param menu The context menu to populate
10768     */
10769    public void createContextMenu(ContextMenu menu) {
10770        ContextMenuInfo menuInfo = getContextMenuInfo();
10771
10772        // Sets the current menu info so all items added to menu will have
10773        // my extra info set.
10774        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10775
10776        onCreateContextMenu(menu);
10777        ListenerInfo li = mListenerInfo;
10778        if (li != null && li.mOnCreateContextMenuListener != null) {
10779            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10780        }
10781
10782        // Clear the extra information so subsequent items that aren't mine don't
10783        // have my extra info.
10784        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10785
10786        if (mParent != null) {
10787            mParent.createContextMenu(menu);
10788        }
10789    }
10790
10791    /**
10792     * Views should implement this if they have extra information to associate
10793     * with the context menu. The return result is supplied as a parameter to
10794     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10795     * callback.
10796     *
10797     * @return Extra information about the item for which the context menu
10798     *         should be shown. This information will vary across different
10799     *         subclasses of View.
10800     */
10801    protected ContextMenuInfo getContextMenuInfo() {
10802        return null;
10803    }
10804
10805    /**
10806     * Views should implement this if the view itself is going to add items to
10807     * the context menu.
10808     *
10809     * @param menu the context menu to populate
10810     */
10811    protected void onCreateContextMenu(ContextMenu menu) {
10812    }
10813
10814    /**
10815     * Implement this method to handle trackball motion events.  The
10816     * <em>relative</em> movement of the trackball since the last event
10817     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10818     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10819     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10820     * they will often be fractional values, representing the more fine-grained
10821     * movement information available from a trackball).
10822     *
10823     * @param event The motion event.
10824     * @return True if the event was handled, false otherwise.
10825     */
10826    public boolean onTrackballEvent(MotionEvent event) {
10827        return false;
10828    }
10829
10830    /**
10831     * Implement this method to handle generic motion events.
10832     * <p>
10833     * Generic motion events describe joystick movements, mouse hovers, track pad
10834     * touches, scroll wheel movements and other input events.  The
10835     * {@link MotionEvent#getSource() source} of the motion event specifies
10836     * the class of input that was received.  Implementations of this method
10837     * must examine the bits in the source before processing the event.
10838     * The following code example shows how this is done.
10839     * </p><p>
10840     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10841     * are delivered to the view under the pointer.  All other generic motion events are
10842     * delivered to the focused view.
10843     * </p>
10844     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10845     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10846     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10847     *             // process the joystick movement...
10848     *             return true;
10849     *         }
10850     *     }
10851     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10852     *         switch (event.getAction()) {
10853     *             case MotionEvent.ACTION_HOVER_MOVE:
10854     *                 // process the mouse hover movement...
10855     *                 return true;
10856     *             case MotionEvent.ACTION_SCROLL:
10857     *                 // process the scroll wheel movement...
10858     *                 return true;
10859     *         }
10860     *     }
10861     *     return super.onGenericMotionEvent(event);
10862     * }</pre>
10863     *
10864     * @param event The generic motion event being processed.
10865     * @return True if the event was handled, false otherwise.
10866     */
10867    public boolean onGenericMotionEvent(MotionEvent event) {
10868        return false;
10869    }
10870
10871    /**
10872     * Implement this method to handle hover events.
10873     * <p>
10874     * This method is called whenever a pointer is hovering into, over, or out of the
10875     * bounds of a view and the view is not currently being touched.
10876     * Hover events are represented as pointer events with action
10877     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10878     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10879     * </p>
10880     * <ul>
10881     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10882     * when the pointer enters the bounds of the view.</li>
10883     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10884     * when the pointer has already entered the bounds of the view and has moved.</li>
10885     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10886     * when the pointer has exited the bounds of the view or when the pointer is
10887     * about to go down due to a button click, tap, or similar user action that
10888     * causes the view to be touched.</li>
10889     * </ul>
10890     * <p>
10891     * The view should implement this method to return true to indicate that it is
10892     * handling the hover event, such as by changing its drawable state.
10893     * </p><p>
10894     * The default implementation calls {@link #setHovered} to update the hovered state
10895     * of the view when a hover enter or hover exit event is received, if the view
10896     * is enabled and is clickable.  The default implementation also sends hover
10897     * accessibility events.
10898     * </p>
10899     *
10900     * @param event The motion event that describes the hover.
10901     * @return True if the view handled the hover event.
10902     *
10903     * @see #isHovered
10904     * @see #setHovered
10905     * @see #onHoverChanged
10906     */
10907    public boolean onHoverEvent(MotionEvent event) {
10908        // The root view may receive hover (or touch) events that are outside the bounds of
10909        // the window.  This code ensures that we only send accessibility events for
10910        // hovers that are actually within the bounds of the root view.
10911        final int action = event.getActionMasked();
10912        if (!mSendingHoverAccessibilityEvents) {
10913            if ((action == MotionEvent.ACTION_HOVER_ENTER
10914                    || action == MotionEvent.ACTION_HOVER_MOVE)
10915                    && !hasHoveredChild()
10916                    && pointInView(event.getX(), event.getY())) {
10917                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10918                mSendingHoverAccessibilityEvents = true;
10919            }
10920        } else {
10921            if (action == MotionEvent.ACTION_HOVER_EXIT
10922                    || (action == MotionEvent.ACTION_MOVE
10923                            && !pointInView(event.getX(), event.getY()))) {
10924                mSendingHoverAccessibilityEvents = false;
10925                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10926            }
10927        }
10928
10929        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
10930                && event.isFromSource(InputDevice.SOURCE_MOUSE)
10931                && isOnScrollbar(event.getX(), event.getY())) {
10932            awakenScrollBars();
10933        }
10934        if (isHoverable()) {
10935            switch (action) {
10936                case MotionEvent.ACTION_HOVER_ENTER:
10937                    setHovered(true);
10938                    break;
10939                case MotionEvent.ACTION_HOVER_EXIT:
10940                    setHovered(false);
10941                    break;
10942            }
10943
10944            // Dispatch the event to onGenericMotionEvent before returning true.
10945            // This is to provide compatibility with existing applications that
10946            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10947            // break because of the new default handling for hoverable views
10948            // in onHoverEvent.
10949            // Note that onGenericMotionEvent will be called by default when
10950            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10951            dispatchGenericMotionEventInternal(event);
10952            // The event was already handled by calling setHovered(), so always
10953            // return true.
10954            return true;
10955        }
10956
10957        return false;
10958    }
10959
10960    /**
10961     * Returns true if the view should handle {@link #onHoverEvent}
10962     * by calling {@link #setHovered} to change its hovered state.
10963     *
10964     * @return True if the view is hoverable.
10965     */
10966    private boolean isHoverable() {
10967        final int viewFlags = mViewFlags;
10968        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10969            return false;
10970        }
10971
10972        return (viewFlags & CLICKABLE) == CLICKABLE
10973                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10974                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10975    }
10976
10977    /**
10978     * Returns true if the view is currently hovered.
10979     *
10980     * @return True if the view is currently hovered.
10981     *
10982     * @see #setHovered
10983     * @see #onHoverChanged
10984     */
10985    @ViewDebug.ExportedProperty
10986    public boolean isHovered() {
10987        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10988    }
10989
10990    /**
10991     * Sets whether the view is currently hovered.
10992     * <p>
10993     * Calling this method also changes the drawable state of the view.  This
10994     * enables the view to react to hover by using different drawable resources
10995     * to change its appearance.
10996     * </p><p>
10997     * The {@link #onHoverChanged} method is called when the hovered state changes.
10998     * </p>
10999     *
11000     * @param hovered True if the view is hovered.
11001     *
11002     * @see #isHovered
11003     * @see #onHoverChanged
11004     */
11005    public void setHovered(boolean hovered) {
11006        if (hovered) {
11007            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11008                mPrivateFlags |= PFLAG_HOVERED;
11009                refreshDrawableState();
11010                onHoverChanged(true);
11011            }
11012        } else {
11013            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11014                mPrivateFlags &= ~PFLAG_HOVERED;
11015                refreshDrawableState();
11016                onHoverChanged(false);
11017            }
11018        }
11019    }
11020
11021    /**
11022     * Implement this method to handle hover state changes.
11023     * <p>
11024     * This method is called whenever the hover state changes as a result of a
11025     * call to {@link #setHovered}.
11026     * </p>
11027     *
11028     * @param hovered The current hover state, as returned by {@link #isHovered}.
11029     *
11030     * @see #isHovered
11031     * @see #setHovered
11032     */
11033    public void onHoverChanged(boolean hovered) {
11034    }
11035
11036    /**
11037     * Handles scroll bar dragging by mouse input.
11038     *
11039     * @hide
11040     * @param event The motion event.
11041     *
11042     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11043     */
11044    protected boolean handleScrollBarDragging(MotionEvent event) {
11045        if (mScrollCache == null) {
11046            return false;
11047        }
11048        final float x = event.getX();
11049        final float y = event.getY();
11050        final int action = event.getAction();
11051        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11052                && action != MotionEvent.ACTION_DOWN)
11053                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11054                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11055            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11056            return false;
11057        }
11058
11059        switch (action) {
11060            case MotionEvent.ACTION_MOVE:
11061                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11062                    return false;
11063                }
11064                if (mScrollCache.mScrollBarDraggingState
11065                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11066                    final Rect bounds = mScrollCache.mScrollBarBounds;
11067                    getVerticalScrollBarBounds(bounds);
11068                    final int range = computeVerticalScrollRange();
11069                    final int offset = computeVerticalScrollOffset();
11070                    final int extent = computeVerticalScrollExtent();
11071
11072                    final int thumbLength = ScrollBarUtils.getThumbLength(
11073                            bounds.height(), bounds.width(), extent, range);
11074                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11075                            bounds.height(), thumbLength, extent, range, offset);
11076
11077                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11078                    final float maxThumbOffset = bounds.height() - thumbLength;
11079                    final float newThumbOffset =
11080                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11081                    final int height = getHeight();
11082                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11083                            && height > 0 && extent > 0) {
11084                        final int newY = Math.round((range - extent)
11085                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11086                        if (newY != getScrollY()) {
11087                            mScrollCache.mScrollBarDraggingPos = y;
11088                            setScrollY(newY);
11089                        }
11090                    }
11091                    return true;
11092                }
11093                if (mScrollCache.mScrollBarDraggingState
11094                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11095                    final Rect bounds = mScrollCache.mScrollBarBounds;
11096                    getHorizontalScrollBarBounds(bounds);
11097                    final int range = computeHorizontalScrollRange();
11098                    final int offset = computeHorizontalScrollOffset();
11099                    final int extent = computeHorizontalScrollExtent();
11100
11101                    final int thumbLength = ScrollBarUtils.getThumbLength(
11102                            bounds.width(), bounds.height(), extent, range);
11103                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11104                            bounds.width(), thumbLength, extent, range, offset);
11105
11106                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11107                    final float maxThumbOffset = bounds.width() - thumbLength;
11108                    final float newThumbOffset =
11109                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11110                    final int width = getWidth();
11111                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11112                            && width > 0 && extent > 0) {
11113                        final int newX = Math.round((range - extent)
11114                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11115                        if (newX != getScrollX()) {
11116                            mScrollCache.mScrollBarDraggingPos = x;
11117                            setScrollX(newX);
11118                        }
11119                    }
11120                    return true;
11121                }
11122            case MotionEvent.ACTION_DOWN:
11123                if (mScrollCache.state == ScrollabilityCache.OFF) {
11124                    return false;
11125                }
11126                if (isOnVerticalScrollbarThumb(x, y)) {
11127                    mScrollCache.mScrollBarDraggingState =
11128                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11129                    mScrollCache.mScrollBarDraggingPos = y;
11130                    return true;
11131                }
11132                if (isOnHorizontalScrollbarThumb(x, y)) {
11133                    mScrollCache.mScrollBarDraggingState =
11134                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11135                    mScrollCache.mScrollBarDraggingPos = x;
11136                    return true;
11137                }
11138        }
11139        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11140        return false;
11141    }
11142
11143    /**
11144     * Implement this method to handle touch screen motion events.
11145     * <p>
11146     * If this method is used to detect click actions, it is recommended that
11147     * the actions be performed by implementing and calling
11148     * {@link #performClick()}. This will ensure consistent system behavior,
11149     * including:
11150     * <ul>
11151     * <li>obeying click sound preferences
11152     * <li>dispatching OnClickListener calls
11153     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11154     * accessibility features are enabled
11155     * </ul>
11156     *
11157     * @param event The motion event.
11158     * @return True if the event was handled, false otherwise.
11159     */
11160    public boolean onTouchEvent(MotionEvent event) {
11161        final float x = event.getX();
11162        final float y = event.getY();
11163        final int viewFlags = mViewFlags;
11164        final int action = event.getAction();
11165
11166        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11167            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11168                setPressed(false);
11169            }
11170            // A disabled view that is clickable still consumes the touch
11171            // events, it just doesn't respond to them.
11172            return (((viewFlags & CLICKABLE) == CLICKABLE
11173                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11174                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
11175        }
11176        if (mTouchDelegate != null) {
11177            if (mTouchDelegate.onTouchEvent(event)) {
11178                return true;
11179            }
11180        }
11181
11182        if (((viewFlags & CLICKABLE) == CLICKABLE ||
11183                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
11184                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
11185            switch (action) {
11186                case MotionEvent.ACTION_UP:
11187                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11188                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11189                        // take focus if we don't have it already and we should in
11190                        // touch mode.
11191                        boolean focusTaken = false;
11192                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11193                            focusTaken = requestFocus();
11194                        }
11195
11196                        if (prepressed) {
11197                            // The button is being released before we actually
11198                            // showed it as pressed.  Make it show the pressed
11199                            // state now (before scheduling the click) to ensure
11200                            // the user sees it.
11201                            setPressed(true, x, y);
11202                       }
11203
11204                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11205                            // This is a tap, so remove the longpress check
11206                            removeLongPressCallback();
11207
11208                            // Only perform take click actions if we were in the pressed state
11209                            if (!focusTaken) {
11210                                // Use a Runnable and post this rather than calling
11211                                // performClick directly. This lets other visual state
11212                                // of the view update before click actions start.
11213                                if (mPerformClick == null) {
11214                                    mPerformClick = new PerformClick();
11215                                }
11216                                if (!post(mPerformClick)) {
11217                                    performClick();
11218                                }
11219                            }
11220                        }
11221
11222                        if (mUnsetPressedState == null) {
11223                            mUnsetPressedState = new UnsetPressedState();
11224                        }
11225
11226                        if (prepressed) {
11227                            postDelayed(mUnsetPressedState,
11228                                    ViewConfiguration.getPressedStateDuration());
11229                        } else if (!post(mUnsetPressedState)) {
11230                            // If the post failed, unpress right now
11231                            mUnsetPressedState.run();
11232                        }
11233
11234                        removeTapCallback();
11235                    }
11236                    mIgnoreNextUpEvent = false;
11237                    break;
11238
11239                case MotionEvent.ACTION_DOWN:
11240                    mHasPerformedLongPress = false;
11241
11242                    if (performButtonActionOnTouchDown(event)) {
11243                        break;
11244                    }
11245
11246                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11247                    boolean isInScrollingContainer = isInScrollingContainer();
11248
11249                    // For views inside a scrolling container, delay the pressed feedback for
11250                    // a short period in case this is a scroll.
11251                    if (isInScrollingContainer) {
11252                        mPrivateFlags |= PFLAG_PREPRESSED;
11253                        if (mPendingCheckForTap == null) {
11254                            mPendingCheckForTap = new CheckForTap();
11255                        }
11256                        mPendingCheckForTap.x = event.getX();
11257                        mPendingCheckForTap.y = event.getY();
11258                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11259                    } else {
11260                        // Not inside a scrolling container, so show the feedback right away
11261                        setPressed(true, x, y);
11262                        checkForLongClick(0, x, y);
11263                    }
11264                    break;
11265
11266                case MotionEvent.ACTION_CANCEL:
11267                    setPressed(false);
11268                    removeTapCallback();
11269                    removeLongPressCallback();
11270                    mInContextButtonPress = false;
11271                    mHasPerformedLongPress = false;
11272                    mIgnoreNextUpEvent = false;
11273                    break;
11274
11275                case MotionEvent.ACTION_MOVE:
11276                    drawableHotspotChanged(x, y);
11277
11278                    // Be lenient about moving outside of buttons
11279                    if (!pointInView(x, y, mTouchSlop)) {
11280                        // Outside button
11281                        removeTapCallback();
11282                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11283                            // Remove any future long press/tap checks
11284                            removeLongPressCallback();
11285
11286                            setPressed(false);
11287                        }
11288                    }
11289                    break;
11290            }
11291
11292            return true;
11293        }
11294
11295        return false;
11296    }
11297
11298    /**
11299     * @hide
11300     */
11301    public boolean isInScrollingContainer() {
11302        ViewParent p = getParent();
11303        while (p != null && p instanceof ViewGroup) {
11304            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11305                return true;
11306            }
11307            p = p.getParent();
11308        }
11309        return false;
11310    }
11311
11312    /**
11313     * Remove the longpress detection timer.
11314     */
11315    private void removeLongPressCallback() {
11316        if (mPendingCheckForLongPress != null) {
11317          removeCallbacks(mPendingCheckForLongPress);
11318        }
11319    }
11320
11321    /**
11322     * Remove the pending click action
11323     */
11324    private void removePerformClickCallback() {
11325        if (mPerformClick != null) {
11326            removeCallbacks(mPerformClick);
11327        }
11328    }
11329
11330    /**
11331     * Remove the prepress detection timer.
11332     */
11333    private void removeUnsetPressCallback() {
11334        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11335            setPressed(false);
11336            removeCallbacks(mUnsetPressedState);
11337        }
11338    }
11339
11340    /**
11341     * Remove the tap detection timer.
11342     */
11343    private void removeTapCallback() {
11344        if (mPendingCheckForTap != null) {
11345            mPrivateFlags &= ~PFLAG_PREPRESSED;
11346            removeCallbacks(mPendingCheckForTap);
11347        }
11348    }
11349
11350    /**
11351     * Cancels a pending long press.  Your subclass can use this if you
11352     * want the context menu to come up if the user presses and holds
11353     * at the same place, but you don't want it to come up if they press
11354     * and then move around enough to cause scrolling.
11355     */
11356    public void cancelLongPress() {
11357        removeLongPressCallback();
11358
11359        /*
11360         * The prepressed state handled by the tap callback is a display
11361         * construct, but the tap callback will post a long press callback
11362         * less its own timeout. Remove it here.
11363         */
11364        removeTapCallback();
11365    }
11366
11367    /**
11368     * Remove the pending callback for sending a
11369     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11370     */
11371    private void removeSendViewScrolledAccessibilityEventCallback() {
11372        if (mSendViewScrolledAccessibilityEvent != null) {
11373            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11374            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11375        }
11376    }
11377
11378    /**
11379     * Sets the TouchDelegate for this View.
11380     */
11381    public void setTouchDelegate(TouchDelegate delegate) {
11382        mTouchDelegate = delegate;
11383    }
11384
11385    /**
11386     * Gets the TouchDelegate for this View.
11387     */
11388    public TouchDelegate getTouchDelegate() {
11389        return mTouchDelegate;
11390    }
11391
11392    /**
11393     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11394     *
11395     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11396     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11397     * available. This method should only be called for touch events.
11398     *
11399     * <p class="note">This api is not intended for most applications. Buffered dispatch
11400     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11401     * streams will not improve your input latency. Side effects include: increased latency,
11402     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11403     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11404     * you.</p>
11405     */
11406    public final void requestUnbufferedDispatch(MotionEvent event) {
11407        final int action = event.getAction();
11408        if (mAttachInfo == null
11409                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11410                || !event.isTouchEvent()) {
11411            return;
11412        }
11413        mAttachInfo.mUnbufferedDispatchRequested = true;
11414    }
11415
11416    /**
11417     * Set flags controlling behavior of this view.
11418     *
11419     * @param flags Constant indicating the value which should be set
11420     * @param mask Constant indicating the bit range that should be changed
11421     */
11422    void setFlags(int flags, int mask) {
11423        final boolean accessibilityEnabled =
11424                AccessibilityManager.getInstance(mContext).isEnabled();
11425        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11426
11427        int old = mViewFlags;
11428        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11429
11430        int changed = mViewFlags ^ old;
11431        if (changed == 0) {
11432            return;
11433        }
11434        int privateFlags = mPrivateFlags;
11435
11436        /* Check if the FOCUSABLE bit has changed */
11437        if (((changed & FOCUSABLE_MASK) != 0) &&
11438                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11439            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11440                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11441                /* Give up focus if we are no longer focusable */
11442                clearFocus();
11443            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11444                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11445                /*
11446                 * Tell the view system that we are now available to take focus
11447                 * if no one else already has it.
11448                 */
11449                if (mParent != null) mParent.focusableViewAvailable(this);
11450            }
11451        }
11452
11453        final int newVisibility = flags & VISIBILITY_MASK;
11454        if (newVisibility == VISIBLE) {
11455            if ((changed & VISIBILITY_MASK) != 0) {
11456                /*
11457                 * If this view is becoming visible, invalidate it in case it changed while
11458                 * it was not visible. Marking it drawn ensures that the invalidation will
11459                 * go through.
11460                 */
11461                mPrivateFlags |= PFLAG_DRAWN;
11462                invalidate(true);
11463
11464                needGlobalAttributesUpdate(true);
11465
11466                // a view becoming visible is worth notifying the parent
11467                // about in case nothing has focus.  even if this specific view
11468                // isn't focusable, it may contain something that is, so let
11469                // the root view try to give this focus if nothing else does.
11470                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11471                    mParent.focusableViewAvailable(this);
11472                }
11473            }
11474        }
11475
11476        /* Check if the GONE bit has changed */
11477        if ((changed & GONE) != 0) {
11478            needGlobalAttributesUpdate(false);
11479            requestLayout();
11480
11481            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11482                if (hasFocus()) clearFocus();
11483                clearAccessibilityFocus();
11484                destroyDrawingCache();
11485                if (mParent instanceof View) {
11486                    // GONE views noop invalidation, so invalidate the parent
11487                    ((View) mParent).invalidate(true);
11488                }
11489                // Mark the view drawn to ensure that it gets invalidated properly the next
11490                // time it is visible and gets invalidated
11491                mPrivateFlags |= PFLAG_DRAWN;
11492            }
11493            if (mAttachInfo != null) {
11494                mAttachInfo.mViewVisibilityChanged = true;
11495            }
11496        }
11497
11498        /* Check if the VISIBLE bit has changed */
11499        if ((changed & INVISIBLE) != 0) {
11500            needGlobalAttributesUpdate(false);
11501            /*
11502             * If this view is becoming invisible, set the DRAWN flag so that
11503             * the next invalidate() will not be skipped.
11504             */
11505            mPrivateFlags |= PFLAG_DRAWN;
11506
11507            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11508                // root view becoming invisible shouldn't clear focus and accessibility focus
11509                if (getRootView() != this) {
11510                    if (hasFocus()) clearFocus();
11511                    clearAccessibilityFocus();
11512                }
11513            }
11514            if (mAttachInfo != null) {
11515                mAttachInfo.mViewVisibilityChanged = true;
11516            }
11517        }
11518
11519        if ((changed & VISIBILITY_MASK) != 0) {
11520            // If the view is invisible, cleanup its display list to free up resources
11521            if (newVisibility != VISIBLE && mAttachInfo != null) {
11522                cleanupDraw();
11523            }
11524
11525            if (mParent instanceof ViewGroup) {
11526                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11527                        (changed & VISIBILITY_MASK), newVisibility);
11528                ((View) mParent).invalidate(true);
11529            } else if (mParent != null) {
11530                mParent.invalidateChild(this, null);
11531            }
11532
11533            if (mAttachInfo != null) {
11534                dispatchVisibilityChanged(this, newVisibility);
11535
11536                // Aggregated visibility changes are dispatched to attached views
11537                // in visible windows where the parent is currently shown/drawn
11538                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11539                // discounting clipping or overlapping. This makes it a good place
11540                // to change animation states.
11541                if (mParent != null && getWindowVisibility() == VISIBLE &&
11542                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11543                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11544                }
11545                notifySubtreeAccessibilityStateChangedIfNeeded();
11546            }
11547        }
11548
11549        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11550            destroyDrawingCache();
11551        }
11552
11553        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11554            destroyDrawingCache();
11555            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11556            invalidateParentCaches();
11557        }
11558
11559        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11560            destroyDrawingCache();
11561            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11562        }
11563
11564        if ((changed & DRAW_MASK) != 0) {
11565            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11566                if (mBackground != null
11567                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11568                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11569                } else {
11570                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11571                }
11572            } else {
11573                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11574            }
11575            requestLayout();
11576            invalidate(true);
11577        }
11578
11579        if ((changed & KEEP_SCREEN_ON) != 0) {
11580            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11581                mParent.recomputeViewAttributes(this);
11582            }
11583        }
11584
11585        if (accessibilityEnabled) {
11586            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11587                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11588                    || (changed & CONTEXT_CLICKABLE) != 0) {
11589                if (oldIncludeForAccessibility != includeForAccessibility()) {
11590                    notifySubtreeAccessibilityStateChangedIfNeeded();
11591                } else {
11592                    notifyViewAccessibilityStateChangedIfNeeded(
11593                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11594                }
11595            } else if ((changed & ENABLED_MASK) != 0) {
11596                notifyViewAccessibilityStateChangedIfNeeded(
11597                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11598            }
11599        }
11600    }
11601
11602    /**
11603     * Change the view's z order in the tree, so it's on top of other sibling
11604     * views. This ordering change may affect layout, if the parent container
11605     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11606     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11607     * method should be followed by calls to {@link #requestLayout()} and
11608     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11609     * with the new child ordering.
11610     *
11611     * @see ViewGroup#bringChildToFront(View)
11612     */
11613    public void bringToFront() {
11614        if (mParent != null) {
11615            mParent.bringChildToFront(this);
11616        }
11617    }
11618
11619    /**
11620     * This is called in response to an internal scroll in this view (i.e., the
11621     * view scrolled its own contents). This is typically as a result of
11622     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
11623     * called.
11624     *
11625     * @param l Current horizontal scroll origin.
11626     * @param t Current vertical scroll origin.
11627     * @param oldl Previous horizontal scroll origin.
11628     * @param oldt Previous vertical scroll origin.
11629     */
11630    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
11631        notifySubtreeAccessibilityStateChangedIfNeeded();
11632
11633        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11634            postSendViewScrolledAccessibilityEventCallback();
11635        }
11636
11637        mBackgroundSizeChanged = true;
11638        if (mForegroundInfo != null) {
11639            mForegroundInfo.mBoundsChanged = true;
11640        }
11641
11642        final AttachInfo ai = mAttachInfo;
11643        if (ai != null) {
11644            ai.mViewScrollChanged = true;
11645        }
11646
11647        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
11648            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
11649        }
11650    }
11651
11652    /**
11653     * Interface definition for a callback to be invoked when the scroll
11654     * X or Y positions of a view change.
11655     * <p>
11656     * <b>Note:</b> Some views handle scrolling independently from View and may
11657     * have their own separate listeners for scroll-type events. For example,
11658     * {@link android.widget.ListView ListView} allows clients to register an
11659     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
11660     * to listen for changes in list scroll position.
11661     *
11662     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
11663     */
11664    public interface OnScrollChangeListener {
11665        /**
11666         * Called when the scroll position of a view changes.
11667         *
11668         * @param v The view whose scroll position has changed.
11669         * @param scrollX Current horizontal scroll origin.
11670         * @param scrollY Current vertical scroll origin.
11671         * @param oldScrollX Previous horizontal scroll origin.
11672         * @param oldScrollY Previous vertical scroll origin.
11673         */
11674        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
11675    }
11676
11677    /**
11678     * Interface definition for a callback to be invoked when the layout bounds of a view
11679     * changes due to layout processing.
11680     */
11681    public interface OnLayoutChangeListener {
11682        /**
11683         * Called when the layout bounds of a view changes due to layout processing.
11684         *
11685         * @param v The view whose bounds have changed.
11686         * @param left The new value of the view's left property.
11687         * @param top The new value of the view's top property.
11688         * @param right The new value of the view's right property.
11689         * @param bottom The new value of the view's bottom property.
11690         * @param oldLeft The previous value of the view's left property.
11691         * @param oldTop The previous value of the view's top property.
11692         * @param oldRight The previous value of the view's right property.
11693         * @param oldBottom The previous value of the view's bottom property.
11694         */
11695        void onLayoutChange(View v, int left, int top, int right, int bottom,
11696            int oldLeft, int oldTop, int oldRight, int oldBottom);
11697    }
11698
11699    /**
11700     * This is called during layout when the size of this view has changed. If
11701     * you were just added to the view hierarchy, you're called with the old
11702     * values of 0.
11703     *
11704     * @param w Current width of this view.
11705     * @param h Current height of this view.
11706     * @param oldw Old width of this view.
11707     * @param oldh Old height of this view.
11708     */
11709    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
11710    }
11711
11712    /**
11713     * Called by draw to draw the child views. This may be overridden
11714     * by derived classes to gain control just before its children are drawn
11715     * (but after its own view has been drawn).
11716     * @param canvas the canvas on which to draw the view
11717     */
11718    protected void dispatchDraw(Canvas canvas) {
11719
11720    }
11721
11722    /**
11723     * Gets the parent of this view. Note that the parent is a
11724     * ViewParent and not necessarily a View.
11725     *
11726     * @return Parent of this view.
11727     */
11728    public final ViewParent getParent() {
11729        return mParent;
11730    }
11731
11732    /**
11733     * Set the horizontal scrolled position of your view. This will cause a call to
11734     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11735     * invalidated.
11736     * @param value the x position to scroll to
11737     */
11738    public void setScrollX(int value) {
11739        scrollTo(value, mScrollY);
11740    }
11741
11742    /**
11743     * Set the vertical scrolled position of your view. This will cause a call to
11744     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11745     * invalidated.
11746     * @param value the y position to scroll to
11747     */
11748    public void setScrollY(int value) {
11749        scrollTo(mScrollX, value);
11750    }
11751
11752    /**
11753     * Return the scrolled left position of this view. This is the left edge of
11754     * the displayed part of your view. You do not need to draw any pixels
11755     * farther left, since those are outside of the frame of your view on
11756     * screen.
11757     *
11758     * @return The left edge of the displayed part of your view, in pixels.
11759     */
11760    public final int getScrollX() {
11761        return mScrollX;
11762    }
11763
11764    /**
11765     * Return the scrolled top position of this view. This is the top edge of
11766     * the displayed part of your view. You do not need to draw any pixels above
11767     * it, since those are outside of the frame of your view on screen.
11768     *
11769     * @return The top edge of the displayed part of your view, in pixels.
11770     */
11771    public final int getScrollY() {
11772        return mScrollY;
11773    }
11774
11775    /**
11776     * Return the width of the your view.
11777     *
11778     * @return The width of your view, in pixels.
11779     */
11780    @ViewDebug.ExportedProperty(category = "layout")
11781    public final int getWidth() {
11782        return mRight - mLeft;
11783    }
11784
11785    /**
11786     * Return the height of your view.
11787     *
11788     * @return The height of your view, in pixels.
11789     */
11790    @ViewDebug.ExportedProperty(category = "layout")
11791    public final int getHeight() {
11792        return mBottom - mTop;
11793    }
11794
11795    /**
11796     * Return the visible drawing bounds of your view. Fills in the output
11797     * rectangle with the values from getScrollX(), getScrollY(),
11798     * getWidth(), and getHeight(). These bounds do not account for any
11799     * transformation properties currently set on the view, such as
11800     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
11801     *
11802     * @param outRect The (scrolled) drawing bounds of the view.
11803     */
11804    public void getDrawingRect(Rect outRect) {
11805        outRect.left = mScrollX;
11806        outRect.top = mScrollY;
11807        outRect.right = mScrollX + (mRight - mLeft);
11808        outRect.bottom = mScrollY + (mBottom - mTop);
11809    }
11810
11811    /**
11812     * Like {@link #getMeasuredWidthAndState()}, but only returns the
11813     * raw width component (that is the result is masked by
11814     * {@link #MEASURED_SIZE_MASK}).
11815     *
11816     * @return The raw measured width of this view.
11817     */
11818    public final int getMeasuredWidth() {
11819        return mMeasuredWidth & MEASURED_SIZE_MASK;
11820    }
11821
11822    /**
11823     * Return the full width measurement information for this view as computed
11824     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11825     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11826     * This should be used during measurement and layout calculations only. Use
11827     * {@link #getWidth()} to see how wide a view is after layout.
11828     *
11829     * @return The measured width of this view as a bit mask.
11830     */
11831    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11832            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11833                    name = "MEASURED_STATE_TOO_SMALL"),
11834    })
11835    public final int getMeasuredWidthAndState() {
11836        return mMeasuredWidth;
11837    }
11838
11839    /**
11840     * Like {@link #getMeasuredHeightAndState()}, but only returns the
11841     * raw width component (that is the result is masked by
11842     * {@link #MEASURED_SIZE_MASK}).
11843     *
11844     * @return The raw measured height of this view.
11845     */
11846    public final int getMeasuredHeight() {
11847        return mMeasuredHeight & MEASURED_SIZE_MASK;
11848    }
11849
11850    /**
11851     * Return the full height measurement information for this view as computed
11852     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11853     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11854     * This should be used during measurement and layout calculations only. Use
11855     * {@link #getHeight()} to see how wide a view is after layout.
11856     *
11857     * @return The measured width of this view as a bit mask.
11858     */
11859    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11860            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11861                    name = "MEASURED_STATE_TOO_SMALL"),
11862    })
11863    public final int getMeasuredHeightAndState() {
11864        return mMeasuredHeight;
11865    }
11866
11867    /**
11868     * Return only the state bits of {@link #getMeasuredWidthAndState()}
11869     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
11870     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
11871     * and the height component is at the shifted bits
11872     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
11873     */
11874    public final int getMeasuredState() {
11875        return (mMeasuredWidth&MEASURED_STATE_MASK)
11876                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
11877                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
11878    }
11879
11880    /**
11881     * The transform matrix of this view, which is calculated based on the current
11882     * rotation, scale, and pivot properties.
11883     *
11884     * @see #getRotation()
11885     * @see #getScaleX()
11886     * @see #getScaleY()
11887     * @see #getPivotX()
11888     * @see #getPivotY()
11889     * @return The current transform matrix for the view
11890     */
11891    public Matrix getMatrix() {
11892        ensureTransformationInfo();
11893        final Matrix matrix = mTransformationInfo.mMatrix;
11894        mRenderNode.getMatrix(matrix);
11895        return matrix;
11896    }
11897
11898    /**
11899     * Returns true if the transform matrix is the identity matrix.
11900     * Recomputes the matrix if necessary.
11901     *
11902     * @return True if the transform matrix is the identity matrix, false otherwise.
11903     */
11904    final boolean hasIdentityMatrix() {
11905        return mRenderNode.hasIdentityMatrix();
11906    }
11907
11908    void ensureTransformationInfo() {
11909        if (mTransformationInfo == null) {
11910            mTransformationInfo = new TransformationInfo();
11911        }
11912    }
11913
11914    /**
11915     * Utility method to retrieve the inverse of the current mMatrix property.
11916     * We cache the matrix to avoid recalculating it when transform properties
11917     * have not changed.
11918     *
11919     * @return The inverse of the current matrix of this view.
11920     * @hide
11921     */
11922    public final Matrix getInverseMatrix() {
11923        ensureTransformationInfo();
11924        if (mTransformationInfo.mInverseMatrix == null) {
11925            mTransformationInfo.mInverseMatrix = new Matrix();
11926        }
11927        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11928        mRenderNode.getInverseMatrix(matrix);
11929        return matrix;
11930    }
11931
11932    /**
11933     * Gets the distance along the Z axis from the camera to this view.
11934     *
11935     * @see #setCameraDistance(float)
11936     *
11937     * @return The distance along the Z axis.
11938     */
11939    public float getCameraDistance() {
11940        final float dpi = mResources.getDisplayMetrics().densityDpi;
11941        return -(mRenderNode.getCameraDistance() * dpi);
11942    }
11943
11944    /**
11945     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11946     * views are drawn) from the camera to this view. The camera's distance
11947     * affects 3D transformations, for instance rotations around the X and Y
11948     * axis. If the rotationX or rotationY properties are changed and this view is
11949     * large (more than half the size of the screen), it is recommended to always
11950     * use a camera distance that's greater than the height (X axis rotation) or
11951     * the width (Y axis rotation) of this view.</p>
11952     *
11953     * <p>The distance of the camera from the view plane can have an affect on the
11954     * perspective distortion of the view when it is rotated around the x or y axis.
11955     * For example, a large distance will result in a large viewing angle, and there
11956     * will not be much perspective distortion of the view as it rotates. A short
11957     * distance may cause much more perspective distortion upon rotation, and can
11958     * also result in some drawing artifacts if the rotated view ends up partially
11959     * behind the camera (which is why the recommendation is to use a distance at
11960     * least as far as the size of the view, if the view is to be rotated.)</p>
11961     *
11962     * <p>The distance is expressed in "depth pixels." The default distance depends
11963     * on the screen density. For instance, on a medium density display, the
11964     * default distance is 1280. On a high density display, the default distance
11965     * is 1920.</p>
11966     *
11967     * <p>If you want to specify a distance that leads to visually consistent
11968     * results across various densities, use the following formula:</p>
11969     * <pre>
11970     * float scale = context.getResources().getDisplayMetrics().density;
11971     * view.setCameraDistance(distance * scale);
11972     * </pre>
11973     *
11974     * <p>The density scale factor of a high density display is 1.5,
11975     * and 1920 = 1280 * 1.5.</p>
11976     *
11977     * @param distance The distance in "depth pixels", if negative the opposite
11978     *        value is used
11979     *
11980     * @see #setRotationX(float)
11981     * @see #setRotationY(float)
11982     */
11983    public void setCameraDistance(float distance) {
11984        final float dpi = mResources.getDisplayMetrics().densityDpi;
11985
11986        invalidateViewProperty(true, false);
11987        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11988        invalidateViewProperty(false, false);
11989
11990        invalidateParentIfNeededAndWasQuickRejected();
11991    }
11992
11993    /**
11994     * The degrees that the view is rotated around the pivot point.
11995     *
11996     * @see #setRotation(float)
11997     * @see #getPivotX()
11998     * @see #getPivotY()
11999     *
12000     * @return The degrees of rotation.
12001     */
12002    @ViewDebug.ExportedProperty(category = "drawing")
12003    public float getRotation() {
12004        return mRenderNode.getRotation();
12005    }
12006
12007    /**
12008     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12009     * result in clockwise rotation.
12010     *
12011     * @param rotation The degrees of rotation.
12012     *
12013     * @see #getRotation()
12014     * @see #getPivotX()
12015     * @see #getPivotY()
12016     * @see #setRotationX(float)
12017     * @see #setRotationY(float)
12018     *
12019     * @attr ref android.R.styleable#View_rotation
12020     */
12021    public void setRotation(float rotation) {
12022        if (rotation != getRotation()) {
12023            // Double-invalidation is necessary to capture view's old and new areas
12024            invalidateViewProperty(true, false);
12025            mRenderNode.setRotation(rotation);
12026            invalidateViewProperty(false, true);
12027
12028            invalidateParentIfNeededAndWasQuickRejected();
12029            notifySubtreeAccessibilityStateChangedIfNeeded();
12030        }
12031    }
12032
12033    /**
12034     * The degrees that the view is rotated around the vertical axis through the pivot point.
12035     *
12036     * @see #getPivotX()
12037     * @see #getPivotY()
12038     * @see #setRotationY(float)
12039     *
12040     * @return The degrees of Y rotation.
12041     */
12042    @ViewDebug.ExportedProperty(category = "drawing")
12043    public float getRotationY() {
12044        return mRenderNode.getRotationY();
12045    }
12046
12047    /**
12048     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12049     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12050     * down the y axis.
12051     *
12052     * When rotating large views, it is recommended to adjust the camera distance
12053     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12054     *
12055     * @param rotationY The degrees of Y rotation.
12056     *
12057     * @see #getRotationY()
12058     * @see #getPivotX()
12059     * @see #getPivotY()
12060     * @see #setRotation(float)
12061     * @see #setRotationX(float)
12062     * @see #setCameraDistance(float)
12063     *
12064     * @attr ref android.R.styleable#View_rotationY
12065     */
12066    public void setRotationY(float rotationY) {
12067        if (rotationY != getRotationY()) {
12068            invalidateViewProperty(true, false);
12069            mRenderNode.setRotationY(rotationY);
12070            invalidateViewProperty(false, true);
12071
12072            invalidateParentIfNeededAndWasQuickRejected();
12073            notifySubtreeAccessibilityStateChangedIfNeeded();
12074        }
12075    }
12076
12077    /**
12078     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12079     *
12080     * @see #getPivotX()
12081     * @see #getPivotY()
12082     * @see #setRotationX(float)
12083     *
12084     * @return The degrees of X rotation.
12085     */
12086    @ViewDebug.ExportedProperty(category = "drawing")
12087    public float getRotationX() {
12088        return mRenderNode.getRotationX();
12089    }
12090
12091    /**
12092     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12093     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12094     * x axis.
12095     *
12096     * When rotating large views, it is recommended to adjust the camera distance
12097     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12098     *
12099     * @param rotationX The degrees of X rotation.
12100     *
12101     * @see #getRotationX()
12102     * @see #getPivotX()
12103     * @see #getPivotY()
12104     * @see #setRotation(float)
12105     * @see #setRotationY(float)
12106     * @see #setCameraDistance(float)
12107     *
12108     * @attr ref android.R.styleable#View_rotationX
12109     */
12110    public void setRotationX(float rotationX) {
12111        if (rotationX != getRotationX()) {
12112            invalidateViewProperty(true, false);
12113            mRenderNode.setRotationX(rotationX);
12114            invalidateViewProperty(false, true);
12115
12116            invalidateParentIfNeededAndWasQuickRejected();
12117            notifySubtreeAccessibilityStateChangedIfNeeded();
12118        }
12119    }
12120
12121    /**
12122     * The amount that the view is scaled in x around the pivot point, as a proportion of
12123     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12124     *
12125     * <p>By default, this is 1.0f.
12126     *
12127     * @see #getPivotX()
12128     * @see #getPivotY()
12129     * @return The scaling factor.
12130     */
12131    @ViewDebug.ExportedProperty(category = "drawing")
12132    public float getScaleX() {
12133        return mRenderNode.getScaleX();
12134    }
12135
12136    /**
12137     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12138     * the view's unscaled width. A value of 1 means that no scaling is applied.
12139     *
12140     * @param scaleX The scaling factor.
12141     * @see #getPivotX()
12142     * @see #getPivotY()
12143     *
12144     * @attr ref android.R.styleable#View_scaleX
12145     */
12146    public void setScaleX(float scaleX) {
12147        if (scaleX != getScaleX()) {
12148            invalidateViewProperty(true, false);
12149            mRenderNode.setScaleX(scaleX);
12150            invalidateViewProperty(false, true);
12151
12152            invalidateParentIfNeededAndWasQuickRejected();
12153            notifySubtreeAccessibilityStateChangedIfNeeded();
12154        }
12155    }
12156
12157    /**
12158     * The amount that the view is scaled in y around the pivot point, as a proportion of
12159     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12160     *
12161     * <p>By default, this is 1.0f.
12162     *
12163     * @see #getPivotX()
12164     * @see #getPivotY()
12165     * @return The scaling factor.
12166     */
12167    @ViewDebug.ExportedProperty(category = "drawing")
12168    public float getScaleY() {
12169        return mRenderNode.getScaleY();
12170    }
12171
12172    /**
12173     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12174     * the view's unscaled width. A value of 1 means that no scaling is applied.
12175     *
12176     * @param scaleY The scaling factor.
12177     * @see #getPivotX()
12178     * @see #getPivotY()
12179     *
12180     * @attr ref android.R.styleable#View_scaleY
12181     */
12182    public void setScaleY(float scaleY) {
12183        if (scaleY != getScaleY()) {
12184            invalidateViewProperty(true, false);
12185            mRenderNode.setScaleY(scaleY);
12186            invalidateViewProperty(false, true);
12187
12188            invalidateParentIfNeededAndWasQuickRejected();
12189            notifySubtreeAccessibilityStateChangedIfNeeded();
12190        }
12191    }
12192
12193    /**
12194     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12195     * and {@link #setScaleX(float) scaled}.
12196     *
12197     * @see #getRotation()
12198     * @see #getScaleX()
12199     * @see #getScaleY()
12200     * @see #getPivotY()
12201     * @return The x location of the pivot point.
12202     *
12203     * @attr ref android.R.styleable#View_transformPivotX
12204     */
12205    @ViewDebug.ExportedProperty(category = "drawing")
12206    public float getPivotX() {
12207        return mRenderNode.getPivotX();
12208    }
12209
12210    /**
12211     * Sets the x location of the point around which the view is
12212     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12213     * By default, the pivot point is centered on the object.
12214     * Setting this property disables this behavior and causes the view to use only the
12215     * explicitly set pivotX and pivotY values.
12216     *
12217     * @param pivotX The x location of the pivot point.
12218     * @see #getRotation()
12219     * @see #getScaleX()
12220     * @see #getScaleY()
12221     * @see #getPivotY()
12222     *
12223     * @attr ref android.R.styleable#View_transformPivotX
12224     */
12225    public void setPivotX(float pivotX) {
12226        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12227            invalidateViewProperty(true, false);
12228            mRenderNode.setPivotX(pivotX);
12229            invalidateViewProperty(false, true);
12230
12231            invalidateParentIfNeededAndWasQuickRejected();
12232        }
12233    }
12234
12235    /**
12236     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12237     * and {@link #setScaleY(float) scaled}.
12238     *
12239     * @see #getRotation()
12240     * @see #getScaleX()
12241     * @see #getScaleY()
12242     * @see #getPivotY()
12243     * @return The y location of the pivot point.
12244     *
12245     * @attr ref android.R.styleable#View_transformPivotY
12246     */
12247    @ViewDebug.ExportedProperty(category = "drawing")
12248    public float getPivotY() {
12249        return mRenderNode.getPivotY();
12250    }
12251
12252    /**
12253     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12254     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12255     * Setting this property disables this behavior and causes the view to use only the
12256     * explicitly set pivotX and pivotY values.
12257     *
12258     * @param pivotY The y location of the pivot point.
12259     * @see #getRotation()
12260     * @see #getScaleX()
12261     * @see #getScaleY()
12262     * @see #getPivotY()
12263     *
12264     * @attr ref android.R.styleable#View_transformPivotY
12265     */
12266    public void setPivotY(float pivotY) {
12267        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12268            invalidateViewProperty(true, false);
12269            mRenderNode.setPivotY(pivotY);
12270            invalidateViewProperty(false, true);
12271
12272            invalidateParentIfNeededAndWasQuickRejected();
12273        }
12274    }
12275
12276    /**
12277     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12278     * completely transparent and 1 means the view is completely opaque.
12279     *
12280     * <p>By default this is 1.0f.
12281     * @return The opacity of the view.
12282     */
12283    @ViewDebug.ExportedProperty(category = "drawing")
12284    public float getAlpha() {
12285        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12286    }
12287
12288    /**
12289     * Sets the behavior for overlapping rendering for this view (see {@link
12290     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12291     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12292     * providing the value which is then used internally. That is, when {@link
12293     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12294     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12295     * instead.
12296     *
12297     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12298     * instead of that returned by {@link #hasOverlappingRendering()}.
12299     *
12300     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12301     */
12302    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12303        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12304        if (hasOverlappingRendering) {
12305            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12306        } else {
12307            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12308        }
12309    }
12310
12311    /**
12312     * Returns the value for overlapping rendering that is used internally. This is either
12313     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12314     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12315     *
12316     * @return The value for overlapping rendering being used internally.
12317     */
12318    public final boolean getHasOverlappingRendering() {
12319        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12320                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12321                hasOverlappingRendering();
12322    }
12323
12324    /**
12325     * Returns whether this View has content which overlaps.
12326     *
12327     * <p>This function, intended to be overridden by specific View types, is an optimization when
12328     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12329     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12330     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12331     * directly. An example of overlapping rendering is a TextView with a background image, such as
12332     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12333     * ImageView with only the foreground image. The default implementation returns true; subclasses
12334     * should override if they have cases which can be optimized.</p>
12335     *
12336     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12337     * necessitates that a View return true if it uses the methods internally without passing the
12338     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12339     *
12340     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12341     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12342     *
12343     * @return true if the content in this view might overlap, false otherwise.
12344     */
12345    @ViewDebug.ExportedProperty(category = "drawing")
12346    public boolean hasOverlappingRendering() {
12347        return true;
12348    }
12349
12350    /**
12351     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12352     * completely transparent and 1 means the view is completely opaque.
12353     *
12354     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12355     * can have significant performance implications, especially for large views. It is best to use
12356     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12357     *
12358     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12359     * strongly recommended for performance reasons to either override
12360     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12361     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12362     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12363     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12364     * of rendering cost, even for simple or small views. Starting with
12365     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12366     * applied to the view at the rendering level.</p>
12367     *
12368     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12369     * responsible for applying the opacity itself.</p>
12370     *
12371     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12372     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12373     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12374     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12375     *
12376     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12377     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12378     * {@link #hasOverlappingRendering}.</p>
12379     *
12380     * @param alpha The opacity of the view.
12381     *
12382     * @see #hasOverlappingRendering()
12383     * @see #setLayerType(int, android.graphics.Paint)
12384     *
12385     * @attr ref android.R.styleable#View_alpha
12386     */
12387    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12388        ensureTransformationInfo();
12389        if (mTransformationInfo.mAlpha != alpha) {
12390            // Report visibility changes, which can affect children, to accessibility
12391            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
12392                notifySubtreeAccessibilityStateChangedIfNeeded();
12393            }
12394            mTransformationInfo.mAlpha = alpha;
12395            if (onSetAlpha((int) (alpha * 255))) {
12396                mPrivateFlags |= PFLAG_ALPHA_SET;
12397                // subclass is handling alpha - don't optimize rendering cache invalidation
12398                invalidateParentCaches();
12399                invalidate(true);
12400            } else {
12401                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12402                invalidateViewProperty(true, false);
12403                mRenderNode.setAlpha(getFinalAlpha());
12404            }
12405        }
12406    }
12407
12408    /**
12409     * Faster version of setAlpha() which performs the same steps except there are
12410     * no calls to invalidate(). The caller of this function should perform proper invalidation
12411     * on the parent and this object. The return value indicates whether the subclass handles
12412     * alpha (the return value for onSetAlpha()).
12413     *
12414     * @param alpha The new value for the alpha property
12415     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12416     *         the new value for the alpha property is different from the old value
12417     */
12418    boolean setAlphaNoInvalidation(float alpha) {
12419        ensureTransformationInfo();
12420        if (mTransformationInfo.mAlpha != alpha) {
12421            mTransformationInfo.mAlpha = alpha;
12422            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12423            if (subclassHandlesAlpha) {
12424                mPrivateFlags |= PFLAG_ALPHA_SET;
12425                return true;
12426            } else {
12427                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12428                mRenderNode.setAlpha(getFinalAlpha());
12429            }
12430        }
12431        return false;
12432    }
12433
12434    /**
12435     * This property is hidden and intended only for use by the Fade transition, which
12436     * animates it to produce a visual translucency that does not side-effect (or get
12437     * affected by) the real alpha property. This value is composited with the other
12438     * alpha value (and the AlphaAnimation value, when that is present) to produce
12439     * a final visual translucency result, which is what is passed into the DisplayList.
12440     *
12441     * @hide
12442     */
12443    public void setTransitionAlpha(float alpha) {
12444        ensureTransformationInfo();
12445        if (mTransformationInfo.mTransitionAlpha != alpha) {
12446            mTransformationInfo.mTransitionAlpha = alpha;
12447            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12448            invalidateViewProperty(true, false);
12449            mRenderNode.setAlpha(getFinalAlpha());
12450        }
12451    }
12452
12453    /**
12454     * Calculates the visual alpha of this view, which is a combination of the actual
12455     * alpha value and the transitionAlpha value (if set).
12456     */
12457    private float getFinalAlpha() {
12458        if (mTransformationInfo != null) {
12459            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12460        }
12461        return 1;
12462    }
12463
12464    /**
12465     * This property is hidden and intended only for use by the Fade transition, which
12466     * animates it to produce a visual translucency that does not side-effect (or get
12467     * affected by) the real alpha property. This value is composited with the other
12468     * alpha value (and the AlphaAnimation value, when that is present) to produce
12469     * a final visual translucency result, which is what is passed into the DisplayList.
12470     *
12471     * @hide
12472     */
12473    @ViewDebug.ExportedProperty(category = "drawing")
12474    public float getTransitionAlpha() {
12475        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12476    }
12477
12478    /**
12479     * Top position of this view relative to its parent.
12480     *
12481     * @return The top of this view, in pixels.
12482     */
12483    @ViewDebug.CapturedViewProperty
12484    public final int getTop() {
12485        return mTop;
12486    }
12487
12488    /**
12489     * Sets the top position of this view relative to its parent. This method is meant to be called
12490     * by the layout system and should not generally be called otherwise, because the property
12491     * may be changed at any time by the layout.
12492     *
12493     * @param top The top of this view, in pixels.
12494     */
12495    public final void setTop(int top) {
12496        if (top != mTop) {
12497            final boolean matrixIsIdentity = hasIdentityMatrix();
12498            if (matrixIsIdentity) {
12499                if (mAttachInfo != null) {
12500                    int minTop;
12501                    int yLoc;
12502                    if (top < mTop) {
12503                        minTop = top;
12504                        yLoc = top - mTop;
12505                    } else {
12506                        minTop = mTop;
12507                        yLoc = 0;
12508                    }
12509                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12510                }
12511            } else {
12512                // Double-invalidation is necessary to capture view's old and new areas
12513                invalidate(true);
12514            }
12515
12516            int width = mRight - mLeft;
12517            int oldHeight = mBottom - mTop;
12518
12519            mTop = top;
12520            mRenderNode.setTop(mTop);
12521
12522            sizeChange(width, mBottom - mTop, width, oldHeight);
12523
12524            if (!matrixIsIdentity) {
12525                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12526                invalidate(true);
12527            }
12528            mBackgroundSizeChanged = true;
12529            if (mForegroundInfo != null) {
12530                mForegroundInfo.mBoundsChanged = true;
12531            }
12532            invalidateParentIfNeeded();
12533            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12534                // View was rejected last time it was drawn by its parent; this may have changed
12535                invalidateParentIfNeeded();
12536            }
12537        }
12538    }
12539
12540    /**
12541     * Bottom position of this view relative to its parent.
12542     *
12543     * @return The bottom of this view, in pixels.
12544     */
12545    @ViewDebug.CapturedViewProperty
12546    public final int getBottom() {
12547        return mBottom;
12548    }
12549
12550    /**
12551     * True if this view has changed since the last time being drawn.
12552     *
12553     * @return The dirty state of this view.
12554     */
12555    public boolean isDirty() {
12556        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12557    }
12558
12559    /**
12560     * Sets the bottom position of this view relative to its parent. This method is meant to be
12561     * called by the layout system and should not generally be called otherwise, because the
12562     * property may be changed at any time by the layout.
12563     *
12564     * @param bottom The bottom of this view, in pixels.
12565     */
12566    public final void setBottom(int bottom) {
12567        if (bottom != mBottom) {
12568            final boolean matrixIsIdentity = hasIdentityMatrix();
12569            if (matrixIsIdentity) {
12570                if (mAttachInfo != null) {
12571                    int maxBottom;
12572                    if (bottom < mBottom) {
12573                        maxBottom = mBottom;
12574                    } else {
12575                        maxBottom = bottom;
12576                    }
12577                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12578                }
12579            } else {
12580                // Double-invalidation is necessary to capture view's old and new areas
12581                invalidate(true);
12582            }
12583
12584            int width = mRight - mLeft;
12585            int oldHeight = mBottom - mTop;
12586
12587            mBottom = bottom;
12588            mRenderNode.setBottom(mBottom);
12589
12590            sizeChange(width, mBottom - mTop, width, oldHeight);
12591
12592            if (!matrixIsIdentity) {
12593                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12594                invalidate(true);
12595            }
12596            mBackgroundSizeChanged = true;
12597            if (mForegroundInfo != null) {
12598                mForegroundInfo.mBoundsChanged = true;
12599            }
12600            invalidateParentIfNeeded();
12601            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12602                // View was rejected last time it was drawn by its parent; this may have changed
12603                invalidateParentIfNeeded();
12604            }
12605        }
12606    }
12607
12608    /**
12609     * Left position of this view relative to its parent.
12610     *
12611     * @return The left edge of this view, in pixels.
12612     */
12613    @ViewDebug.CapturedViewProperty
12614    public final int getLeft() {
12615        return mLeft;
12616    }
12617
12618    /**
12619     * Sets the left position of this view relative to its parent. This method is meant to be called
12620     * by the layout system and should not generally be called otherwise, because the property
12621     * may be changed at any time by the layout.
12622     *
12623     * @param left The left of this view, in pixels.
12624     */
12625    public final void setLeft(int left) {
12626        if (left != mLeft) {
12627            final boolean matrixIsIdentity = hasIdentityMatrix();
12628            if (matrixIsIdentity) {
12629                if (mAttachInfo != null) {
12630                    int minLeft;
12631                    int xLoc;
12632                    if (left < mLeft) {
12633                        minLeft = left;
12634                        xLoc = left - mLeft;
12635                    } else {
12636                        minLeft = mLeft;
12637                        xLoc = 0;
12638                    }
12639                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
12640                }
12641            } else {
12642                // Double-invalidation is necessary to capture view's old and new areas
12643                invalidate(true);
12644            }
12645
12646            int oldWidth = mRight - mLeft;
12647            int height = mBottom - mTop;
12648
12649            mLeft = left;
12650            mRenderNode.setLeft(left);
12651
12652            sizeChange(mRight - mLeft, height, oldWidth, height);
12653
12654            if (!matrixIsIdentity) {
12655                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12656                invalidate(true);
12657            }
12658            mBackgroundSizeChanged = true;
12659            if (mForegroundInfo != null) {
12660                mForegroundInfo.mBoundsChanged = true;
12661            }
12662            invalidateParentIfNeeded();
12663            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12664                // View was rejected last time it was drawn by its parent; this may have changed
12665                invalidateParentIfNeeded();
12666            }
12667        }
12668    }
12669
12670    /**
12671     * Right position of this view relative to its parent.
12672     *
12673     * @return The right edge of this view, in pixels.
12674     */
12675    @ViewDebug.CapturedViewProperty
12676    public final int getRight() {
12677        return mRight;
12678    }
12679
12680    /**
12681     * Sets the right position of this view relative to its parent. This method is meant to be called
12682     * by the layout system and should not generally be called otherwise, because the property
12683     * may be changed at any time by the layout.
12684     *
12685     * @param right The right of this view, in pixels.
12686     */
12687    public final void setRight(int right) {
12688        if (right != mRight) {
12689            final boolean matrixIsIdentity = hasIdentityMatrix();
12690            if (matrixIsIdentity) {
12691                if (mAttachInfo != null) {
12692                    int maxRight;
12693                    if (right < mRight) {
12694                        maxRight = mRight;
12695                    } else {
12696                        maxRight = right;
12697                    }
12698                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
12699                }
12700            } else {
12701                // Double-invalidation is necessary to capture view's old and new areas
12702                invalidate(true);
12703            }
12704
12705            int oldWidth = mRight - mLeft;
12706            int height = mBottom - mTop;
12707
12708            mRight = right;
12709            mRenderNode.setRight(mRight);
12710
12711            sizeChange(mRight - mLeft, height, oldWidth, height);
12712
12713            if (!matrixIsIdentity) {
12714                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12715                invalidate(true);
12716            }
12717            mBackgroundSizeChanged = true;
12718            if (mForegroundInfo != null) {
12719                mForegroundInfo.mBoundsChanged = true;
12720            }
12721            invalidateParentIfNeeded();
12722            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12723                // View was rejected last time it was drawn by its parent; this may have changed
12724                invalidateParentIfNeeded();
12725            }
12726        }
12727    }
12728
12729    /**
12730     * The visual x position of this view, in pixels. This is equivalent to the
12731     * {@link #setTranslationX(float) translationX} property plus the current
12732     * {@link #getLeft() left} property.
12733     *
12734     * @return The visual x position of this view, in pixels.
12735     */
12736    @ViewDebug.ExportedProperty(category = "drawing")
12737    public float getX() {
12738        return mLeft + getTranslationX();
12739    }
12740
12741    /**
12742     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
12743     * {@link #setTranslationX(float) translationX} property to be the difference between
12744     * the x value passed in and the current {@link #getLeft() left} property.
12745     *
12746     * @param x The visual x position of this view, in pixels.
12747     */
12748    public void setX(float x) {
12749        setTranslationX(x - mLeft);
12750    }
12751
12752    /**
12753     * The visual y position of this view, in pixels. This is equivalent to the
12754     * {@link #setTranslationY(float) translationY} property plus the current
12755     * {@link #getTop() top} property.
12756     *
12757     * @return The visual y position of this view, in pixels.
12758     */
12759    @ViewDebug.ExportedProperty(category = "drawing")
12760    public float getY() {
12761        return mTop + getTranslationY();
12762    }
12763
12764    /**
12765     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
12766     * {@link #setTranslationY(float) translationY} property to be the difference between
12767     * the y value passed in and the current {@link #getTop() top} property.
12768     *
12769     * @param y The visual y position of this view, in pixels.
12770     */
12771    public void setY(float y) {
12772        setTranslationY(y - mTop);
12773    }
12774
12775    /**
12776     * The visual z position of this view, in pixels. This is equivalent to the
12777     * {@link #setTranslationZ(float) translationZ} property plus the current
12778     * {@link #getElevation() elevation} property.
12779     *
12780     * @return The visual z position of this view, in pixels.
12781     */
12782    @ViewDebug.ExportedProperty(category = "drawing")
12783    public float getZ() {
12784        return getElevation() + getTranslationZ();
12785    }
12786
12787    /**
12788     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
12789     * {@link #setTranslationZ(float) translationZ} property to be the difference between
12790     * the x value passed in and the current {@link #getElevation() elevation} property.
12791     *
12792     * @param z The visual z position of this view, in pixels.
12793     */
12794    public void setZ(float z) {
12795        setTranslationZ(z - getElevation());
12796    }
12797
12798    /**
12799     * The base elevation of this view relative to its parent, in pixels.
12800     *
12801     * @return The base depth position of the view, in pixels.
12802     */
12803    @ViewDebug.ExportedProperty(category = "drawing")
12804    public float getElevation() {
12805        return mRenderNode.getElevation();
12806    }
12807
12808    /**
12809     * Sets the base elevation of this view, in pixels.
12810     *
12811     * @attr ref android.R.styleable#View_elevation
12812     */
12813    public void setElevation(float elevation) {
12814        if (elevation != getElevation()) {
12815            invalidateViewProperty(true, false);
12816            mRenderNode.setElevation(elevation);
12817            invalidateViewProperty(false, true);
12818
12819            invalidateParentIfNeededAndWasQuickRejected();
12820        }
12821    }
12822
12823    /**
12824     * The horizontal location of this view relative to its {@link #getLeft() left} position.
12825     * This position is post-layout, in addition to wherever the object's
12826     * layout placed it.
12827     *
12828     * @return The horizontal position of this view relative to its left position, in pixels.
12829     */
12830    @ViewDebug.ExportedProperty(category = "drawing")
12831    public float getTranslationX() {
12832        return mRenderNode.getTranslationX();
12833    }
12834
12835    /**
12836     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
12837     * This effectively positions the object post-layout, in addition to wherever the object's
12838     * layout placed it.
12839     *
12840     * @param translationX The horizontal position of this view relative to its left position,
12841     * in pixels.
12842     *
12843     * @attr ref android.R.styleable#View_translationX
12844     */
12845    public void setTranslationX(float translationX) {
12846        if (translationX != getTranslationX()) {
12847            invalidateViewProperty(true, false);
12848            mRenderNode.setTranslationX(translationX);
12849            invalidateViewProperty(false, true);
12850
12851            invalidateParentIfNeededAndWasQuickRejected();
12852            notifySubtreeAccessibilityStateChangedIfNeeded();
12853        }
12854    }
12855
12856    /**
12857     * The vertical location of this view relative to its {@link #getTop() top} position.
12858     * This position is post-layout, in addition to wherever the object's
12859     * layout placed it.
12860     *
12861     * @return The vertical position of this view relative to its top position,
12862     * in pixels.
12863     */
12864    @ViewDebug.ExportedProperty(category = "drawing")
12865    public float getTranslationY() {
12866        return mRenderNode.getTranslationY();
12867    }
12868
12869    /**
12870     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
12871     * This effectively positions the object post-layout, in addition to wherever the object's
12872     * layout placed it.
12873     *
12874     * @param translationY The vertical position of this view relative to its top position,
12875     * in pixels.
12876     *
12877     * @attr ref android.R.styleable#View_translationY
12878     */
12879    public void setTranslationY(float translationY) {
12880        if (translationY != getTranslationY()) {
12881            invalidateViewProperty(true, false);
12882            mRenderNode.setTranslationY(translationY);
12883            invalidateViewProperty(false, true);
12884
12885            invalidateParentIfNeededAndWasQuickRejected();
12886            notifySubtreeAccessibilityStateChangedIfNeeded();
12887        }
12888    }
12889
12890    /**
12891     * The depth location of this view relative to its {@link #getElevation() elevation}.
12892     *
12893     * @return The depth of this view relative to its elevation.
12894     */
12895    @ViewDebug.ExportedProperty(category = "drawing")
12896    public float getTranslationZ() {
12897        return mRenderNode.getTranslationZ();
12898    }
12899
12900    /**
12901     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
12902     *
12903     * @attr ref android.R.styleable#View_translationZ
12904     */
12905    public void setTranslationZ(float translationZ) {
12906        if (translationZ != getTranslationZ()) {
12907            invalidateViewProperty(true, false);
12908            mRenderNode.setTranslationZ(translationZ);
12909            invalidateViewProperty(false, true);
12910
12911            invalidateParentIfNeededAndWasQuickRejected();
12912        }
12913    }
12914
12915    /** @hide */
12916    public void setAnimationMatrix(Matrix matrix) {
12917        invalidateViewProperty(true, false);
12918        mRenderNode.setAnimationMatrix(matrix);
12919        invalidateViewProperty(false, true);
12920
12921        invalidateParentIfNeededAndWasQuickRejected();
12922    }
12923
12924    /**
12925     * Returns the current StateListAnimator if exists.
12926     *
12927     * @return StateListAnimator or null if it does not exists
12928     * @see    #setStateListAnimator(android.animation.StateListAnimator)
12929     */
12930    public StateListAnimator getStateListAnimator() {
12931        return mStateListAnimator;
12932    }
12933
12934    /**
12935     * Attaches the provided StateListAnimator to this View.
12936     * <p>
12937     * Any previously attached StateListAnimator will be detached.
12938     *
12939     * @param stateListAnimator The StateListAnimator to update the view
12940     * @see {@link android.animation.StateListAnimator}
12941     */
12942    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12943        if (mStateListAnimator == stateListAnimator) {
12944            return;
12945        }
12946        if (mStateListAnimator != null) {
12947            mStateListAnimator.setTarget(null);
12948        }
12949        mStateListAnimator = stateListAnimator;
12950        if (stateListAnimator != null) {
12951            stateListAnimator.setTarget(this);
12952            if (isAttachedToWindow()) {
12953                stateListAnimator.setState(getDrawableState());
12954            }
12955        }
12956    }
12957
12958    /**
12959     * Returns whether the Outline should be used to clip the contents of the View.
12960     * <p>
12961     * Note that this flag will only be respected if the View's Outline returns true from
12962     * {@link Outline#canClip()}.
12963     *
12964     * @see #setOutlineProvider(ViewOutlineProvider)
12965     * @see #setClipToOutline(boolean)
12966     */
12967    public final boolean getClipToOutline() {
12968        return mRenderNode.getClipToOutline();
12969    }
12970
12971    /**
12972     * Sets whether the View's Outline should be used to clip the contents of the View.
12973     * <p>
12974     * Only a single non-rectangular clip can be applied on a View at any time.
12975     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12976     * circular reveal} animation take priority over Outline clipping, and
12977     * child Outline clipping takes priority over Outline clipping done by a
12978     * parent.
12979     * <p>
12980     * Note that this flag will only be respected if the View's Outline returns true from
12981     * {@link Outline#canClip()}.
12982     *
12983     * @see #setOutlineProvider(ViewOutlineProvider)
12984     * @see #getClipToOutline()
12985     */
12986    public void setClipToOutline(boolean clipToOutline) {
12987        damageInParent();
12988        if (getClipToOutline() != clipToOutline) {
12989            mRenderNode.setClipToOutline(clipToOutline);
12990        }
12991    }
12992
12993    // correspond to the enum values of View_outlineProvider
12994    private static final int PROVIDER_BACKGROUND = 0;
12995    private static final int PROVIDER_NONE = 1;
12996    private static final int PROVIDER_BOUNDS = 2;
12997    private static final int PROVIDER_PADDED_BOUNDS = 3;
12998    private void setOutlineProviderFromAttribute(int providerInt) {
12999        switch (providerInt) {
13000            case PROVIDER_BACKGROUND:
13001                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
13002                break;
13003            case PROVIDER_NONE:
13004                setOutlineProvider(null);
13005                break;
13006            case PROVIDER_BOUNDS:
13007                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13008                break;
13009            case PROVIDER_PADDED_BOUNDS:
13010                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13011                break;
13012        }
13013    }
13014
13015    /**
13016     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13017     * the shape of the shadow it casts, and enables outline clipping.
13018     * <p>
13019     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13020     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13021     * outline provider with this method allows this behavior to be overridden.
13022     * <p>
13023     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13024     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13025     * <p>
13026     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13027     *
13028     * @see #setClipToOutline(boolean)
13029     * @see #getClipToOutline()
13030     * @see #getOutlineProvider()
13031     */
13032    public void setOutlineProvider(ViewOutlineProvider provider) {
13033        mOutlineProvider = provider;
13034        invalidateOutline();
13035    }
13036
13037    /**
13038     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13039     * that defines the shape of the shadow it casts, and enables outline clipping.
13040     *
13041     * @see #setOutlineProvider(ViewOutlineProvider)
13042     */
13043    public ViewOutlineProvider getOutlineProvider() {
13044        return mOutlineProvider;
13045    }
13046
13047    /**
13048     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13049     *
13050     * @see #setOutlineProvider(ViewOutlineProvider)
13051     */
13052    public void invalidateOutline() {
13053        rebuildOutline();
13054
13055        notifySubtreeAccessibilityStateChangedIfNeeded();
13056        invalidateViewProperty(false, false);
13057    }
13058
13059    /**
13060     * Internal version of {@link #invalidateOutline()} which invalidates the
13061     * outline without invalidating the view itself. This is intended to be called from
13062     * within methods in the View class itself which are the result of the view being
13063     * invalidated already. For example, when we are drawing the background of a View,
13064     * we invalidate the outline in case it changed in the meantime, but we do not
13065     * need to invalidate the view because we're already drawing the background as part
13066     * of drawing the view in response to an earlier invalidation of the view.
13067     */
13068    private void rebuildOutline() {
13069        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13070        if (mAttachInfo == null) return;
13071
13072        if (mOutlineProvider == null) {
13073            // no provider, remove outline
13074            mRenderNode.setOutline(null);
13075        } else {
13076            final Outline outline = mAttachInfo.mTmpOutline;
13077            outline.setEmpty();
13078            outline.setAlpha(1.0f);
13079
13080            mOutlineProvider.getOutline(this, outline);
13081            mRenderNode.setOutline(outline);
13082        }
13083    }
13084
13085    /**
13086     * HierarchyViewer only
13087     *
13088     * @hide
13089     */
13090    @ViewDebug.ExportedProperty(category = "drawing")
13091    public boolean hasShadow() {
13092        return mRenderNode.hasShadow();
13093    }
13094
13095
13096    /** @hide */
13097    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13098        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13099        invalidateViewProperty(false, false);
13100    }
13101
13102    /**
13103     * Hit rectangle in parent's coordinates
13104     *
13105     * @param outRect The hit rectangle of the view.
13106     */
13107    public void getHitRect(Rect outRect) {
13108        if (hasIdentityMatrix() || mAttachInfo == null) {
13109            outRect.set(mLeft, mTop, mRight, mBottom);
13110        } else {
13111            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13112            tmpRect.set(0, 0, getWidth(), getHeight());
13113            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13114            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13115                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13116        }
13117    }
13118
13119    /**
13120     * Determines whether the given point, in local coordinates is inside the view.
13121     */
13122    /*package*/ final boolean pointInView(float localX, float localY) {
13123        return pointInView(localX, localY, 0);
13124    }
13125
13126    /**
13127     * Utility method to determine whether the given point, in local coordinates,
13128     * is inside the view, where the area of the view is expanded by the slop factor.
13129     * This method is called while processing touch-move events to determine if the event
13130     * is still within the view.
13131     *
13132     * @hide
13133     */
13134    public boolean pointInView(float localX, float localY, float slop) {
13135        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13136                localY < ((mBottom - mTop) + slop);
13137    }
13138
13139    /**
13140     * When a view has focus and the user navigates away from it, the next view is searched for
13141     * starting from the rectangle filled in by this method.
13142     *
13143     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13144     * of the view.  However, if your view maintains some idea of internal selection,
13145     * such as a cursor, or a selected row or column, you should override this method and
13146     * fill in a more specific rectangle.
13147     *
13148     * @param r The rectangle to fill in, in this view's coordinates.
13149     */
13150    public void getFocusedRect(Rect r) {
13151        getDrawingRect(r);
13152    }
13153
13154    /**
13155     * If some part of this view is not clipped by any of its parents, then
13156     * return that area in r in global (root) coordinates. To convert r to local
13157     * coordinates (without taking possible View rotations into account), offset
13158     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13159     * If the view is completely clipped or translated out, return false.
13160     *
13161     * @param r If true is returned, r holds the global coordinates of the
13162     *        visible portion of this view.
13163     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13164     *        between this view and its root. globalOffet may be null.
13165     * @return true if r is non-empty (i.e. part of the view is visible at the
13166     *         root level.
13167     */
13168    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13169        int width = mRight - mLeft;
13170        int height = mBottom - mTop;
13171        if (width > 0 && height > 0) {
13172            r.set(0, 0, width, height);
13173            if (globalOffset != null) {
13174                globalOffset.set(-mScrollX, -mScrollY);
13175            }
13176            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13177        }
13178        return false;
13179    }
13180
13181    public final boolean getGlobalVisibleRect(Rect r) {
13182        return getGlobalVisibleRect(r, null);
13183    }
13184
13185    public final boolean getLocalVisibleRect(Rect r) {
13186        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13187        if (getGlobalVisibleRect(r, offset)) {
13188            r.offset(-offset.x, -offset.y); // make r local
13189            return true;
13190        }
13191        return false;
13192    }
13193
13194    /**
13195     * Offset this view's vertical location by the specified number of pixels.
13196     *
13197     * @param offset the number of pixels to offset the view by
13198     */
13199    public void offsetTopAndBottom(int offset) {
13200        if (offset != 0) {
13201            final boolean matrixIsIdentity = hasIdentityMatrix();
13202            if (matrixIsIdentity) {
13203                if (isHardwareAccelerated()) {
13204                    invalidateViewProperty(false, false);
13205                } else {
13206                    final ViewParent p = mParent;
13207                    if (p != null && mAttachInfo != null) {
13208                        final Rect r = mAttachInfo.mTmpInvalRect;
13209                        int minTop;
13210                        int maxBottom;
13211                        int yLoc;
13212                        if (offset < 0) {
13213                            minTop = mTop + offset;
13214                            maxBottom = mBottom;
13215                            yLoc = offset;
13216                        } else {
13217                            minTop = mTop;
13218                            maxBottom = mBottom + offset;
13219                            yLoc = 0;
13220                        }
13221                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13222                        p.invalidateChild(this, r);
13223                    }
13224                }
13225            } else {
13226                invalidateViewProperty(false, false);
13227            }
13228
13229            mTop += offset;
13230            mBottom += offset;
13231            mRenderNode.offsetTopAndBottom(offset);
13232            if (isHardwareAccelerated()) {
13233                invalidateViewProperty(false, false);
13234                invalidateParentIfNeededAndWasQuickRejected();
13235            } else {
13236                if (!matrixIsIdentity) {
13237                    invalidateViewProperty(false, true);
13238                }
13239                invalidateParentIfNeeded();
13240            }
13241            notifySubtreeAccessibilityStateChangedIfNeeded();
13242        }
13243    }
13244
13245    /**
13246     * Offset this view's horizontal location by the specified amount of pixels.
13247     *
13248     * @param offset the number of pixels to offset the view by
13249     */
13250    public void offsetLeftAndRight(int offset) {
13251        if (offset != 0) {
13252            final boolean matrixIsIdentity = hasIdentityMatrix();
13253            if (matrixIsIdentity) {
13254                if (isHardwareAccelerated()) {
13255                    invalidateViewProperty(false, false);
13256                } else {
13257                    final ViewParent p = mParent;
13258                    if (p != null && mAttachInfo != null) {
13259                        final Rect r = mAttachInfo.mTmpInvalRect;
13260                        int minLeft;
13261                        int maxRight;
13262                        if (offset < 0) {
13263                            minLeft = mLeft + offset;
13264                            maxRight = mRight;
13265                        } else {
13266                            minLeft = mLeft;
13267                            maxRight = mRight + offset;
13268                        }
13269                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13270                        p.invalidateChild(this, r);
13271                    }
13272                }
13273            } else {
13274                invalidateViewProperty(false, false);
13275            }
13276
13277            mLeft += offset;
13278            mRight += offset;
13279            mRenderNode.offsetLeftAndRight(offset);
13280            if (isHardwareAccelerated()) {
13281                invalidateViewProperty(false, false);
13282                invalidateParentIfNeededAndWasQuickRejected();
13283            } else {
13284                if (!matrixIsIdentity) {
13285                    invalidateViewProperty(false, true);
13286                }
13287                invalidateParentIfNeeded();
13288            }
13289            notifySubtreeAccessibilityStateChangedIfNeeded();
13290        }
13291    }
13292
13293    /**
13294     * Get the LayoutParams associated with this view. All views should have
13295     * layout parameters. These supply parameters to the <i>parent</i> of this
13296     * view specifying how it should be arranged. There are many subclasses of
13297     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13298     * of ViewGroup that are responsible for arranging their children.
13299     *
13300     * This method may return null if this View is not attached to a parent
13301     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13302     * was not invoked successfully. When a View is attached to a parent
13303     * ViewGroup, this method must not return null.
13304     *
13305     * @return The LayoutParams associated with this view, or null if no
13306     *         parameters have been set yet
13307     */
13308    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13309    public ViewGroup.LayoutParams getLayoutParams() {
13310        return mLayoutParams;
13311    }
13312
13313    /**
13314     * Set the layout parameters associated with this view. These supply
13315     * parameters to the <i>parent</i> of this view specifying how it should be
13316     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13317     * correspond to the different subclasses of ViewGroup that are responsible
13318     * for arranging their children.
13319     *
13320     * @param params The layout parameters for this view, cannot be null
13321     */
13322    public void setLayoutParams(ViewGroup.LayoutParams params) {
13323        if (params == null) {
13324            throw new NullPointerException("Layout parameters cannot be null");
13325        }
13326        mLayoutParams = params;
13327        resolveLayoutParams();
13328        if (mParent instanceof ViewGroup) {
13329            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13330        }
13331        requestLayout();
13332    }
13333
13334    /**
13335     * Resolve the layout parameters depending on the resolved layout direction
13336     *
13337     * @hide
13338     */
13339    public void resolveLayoutParams() {
13340        if (mLayoutParams != null) {
13341            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13342        }
13343    }
13344
13345    /**
13346     * Set the scrolled position of your view. This will cause a call to
13347     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13348     * invalidated.
13349     * @param x the x position to scroll to
13350     * @param y the y position to scroll to
13351     */
13352    public void scrollTo(int x, int y) {
13353        if (mScrollX != x || mScrollY != y) {
13354            int oldX = mScrollX;
13355            int oldY = mScrollY;
13356            mScrollX = x;
13357            mScrollY = y;
13358            invalidateParentCaches();
13359            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13360            if (!awakenScrollBars()) {
13361                postInvalidateOnAnimation();
13362            }
13363        }
13364    }
13365
13366    /**
13367     * Move the scrolled position of your view. This will cause a call to
13368     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13369     * invalidated.
13370     * @param x the amount of pixels to scroll by horizontally
13371     * @param y the amount of pixels to scroll by vertically
13372     */
13373    public void scrollBy(int x, int y) {
13374        scrollTo(mScrollX + x, mScrollY + y);
13375    }
13376
13377    /**
13378     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13379     * animation to fade the scrollbars out after a default delay. If a subclass
13380     * provides animated scrolling, the start delay should equal the duration
13381     * of the scrolling animation.</p>
13382     *
13383     * <p>The animation starts only if at least one of the scrollbars is
13384     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13385     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13386     * this method returns true, and false otherwise. If the animation is
13387     * started, this method calls {@link #invalidate()}; in that case the
13388     * caller should not call {@link #invalidate()}.</p>
13389     *
13390     * <p>This method should be invoked every time a subclass directly updates
13391     * the scroll parameters.</p>
13392     *
13393     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13394     * and {@link #scrollTo(int, int)}.</p>
13395     *
13396     * @return true if the animation is played, false otherwise
13397     *
13398     * @see #awakenScrollBars(int)
13399     * @see #scrollBy(int, int)
13400     * @see #scrollTo(int, int)
13401     * @see #isHorizontalScrollBarEnabled()
13402     * @see #isVerticalScrollBarEnabled()
13403     * @see #setHorizontalScrollBarEnabled(boolean)
13404     * @see #setVerticalScrollBarEnabled(boolean)
13405     */
13406    protected boolean awakenScrollBars() {
13407        return mScrollCache != null &&
13408                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13409    }
13410
13411    /**
13412     * Trigger the scrollbars to draw.
13413     * This method differs from awakenScrollBars() only in its default duration.
13414     * initialAwakenScrollBars() will show the scroll bars for longer than
13415     * usual to give the user more of a chance to notice them.
13416     *
13417     * @return true if the animation is played, false otherwise.
13418     */
13419    private boolean initialAwakenScrollBars() {
13420        return mScrollCache != null &&
13421                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13422    }
13423
13424    /**
13425     * <p>
13426     * Trigger the scrollbars to draw. When invoked this method starts an
13427     * animation to fade the scrollbars out after a fixed delay. If a subclass
13428     * provides animated scrolling, the start delay should equal the duration of
13429     * the scrolling animation.
13430     * </p>
13431     *
13432     * <p>
13433     * The animation starts only if at least one of the scrollbars is enabled,
13434     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13435     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13436     * this method returns true, and false otherwise. If the animation is
13437     * started, this method calls {@link #invalidate()}; in that case the caller
13438     * should not call {@link #invalidate()}.
13439     * </p>
13440     *
13441     * <p>
13442     * This method should be invoked every time a subclass directly updates the
13443     * scroll parameters.
13444     * </p>
13445     *
13446     * @param startDelay the delay, in milliseconds, after which the animation
13447     *        should start; when the delay is 0, the animation starts
13448     *        immediately
13449     * @return true if the animation is played, false otherwise
13450     *
13451     * @see #scrollBy(int, int)
13452     * @see #scrollTo(int, int)
13453     * @see #isHorizontalScrollBarEnabled()
13454     * @see #isVerticalScrollBarEnabled()
13455     * @see #setHorizontalScrollBarEnabled(boolean)
13456     * @see #setVerticalScrollBarEnabled(boolean)
13457     */
13458    protected boolean awakenScrollBars(int startDelay) {
13459        return awakenScrollBars(startDelay, true);
13460    }
13461
13462    /**
13463     * <p>
13464     * Trigger the scrollbars to draw. When invoked this method starts an
13465     * animation to fade the scrollbars out after a fixed delay. If a subclass
13466     * provides animated scrolling, the start delay should equal the duration of
13467     * the scrolling animation.
13468     * </p>
13469     *
13470     * <p>
13471     * The animation starts only if at least one of the scrollbars is enabled,
13472     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13473     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13474     * this method returns true, and false otherwise. If the animation is
13475     * started, this method calls {@link #invalidate()} if the invalidate parameter
13476     * is set to true; in that case the caller
13477     * should not call {@link #invalidate()}.
13478     * </p>
13479     *
13480     * <p>
13481     * This method should be invoked every time a subclass directly updates the
13482     * scroll parameters.
13483     * </p>
13484     *
13485     * @param startDelay the delay, in milliseconds, after which the animation
13486     *        should start; when the delay is 0, the animation starts
13487     *        immediately
13488     *
13489     * @param invalidate Whether this method should call invalidate
13490     *
13491     * @return true if the animation is played, false otherwise
13492     *
13493     * @see #scrollBy(int, int)
13494     * @see #scrollTo(int, int)
13495     * @see #isHorizontalScrollBarEnabled()
13496     * @see #isVerticalScrollBarEnabled()
13497     * @see #setHorizontalScrollBarEnabled(boolean)
13498     * @see #setVerticalScrollBarEnabled(boolean)
13499     */
13500    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13501        final ScrollabilityCache scrollCache = mScrollCache;
13502
13503        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13504            return false;
13505        }
13506
13507        if (scrollCache.scrollBar == null) {
13508            scrollCache.scrollBar = new ScrollBarDrawable();
13509            scrollCache.scrollBar.setState(getDrawableState());
13510            scrollCache.scrollBar.setCallback(this);
13511        }
13512
13513        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13514
13515            if (invalidate) {
13516                // Invalidate to show the scrollbars
13517                postInvalidateOnAnimation();
13518            }
13519
13520            if (scrollCache.state == ScrollabilityCache.OFF) {
13521                // FIXME: this is copied from WindowManagerService.
13522                // We should get this value from the system when it
13523                // is possible to do so.
13524                final int KEY_REPEAT_FIRST_DELAY = 750;
13525                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13526            }
13527
13528            // Tell mScrollCache when we should start fading. This may
13529            // extend the fade start time if one was already scheduled
13530            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13531            scrollCache.fadeStartTime = fadeStartTime;
13532            scrollCache.state = ScrollabilityCache.ON;
13533
13534            // Schedule our fader to run, unscheduling any old ones first
13535            if (mAttachInfo != null) {
13536                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13537                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13538            }
13539
13540            return true;
13541        }
13542
13543        return false;
13544    }
13545
13546    /**
13547     * Do not invalidate views which are not visible and which are not running an animation. They
13548     * will not get drawn and they should not set dirty flags as if they will be drawn
13549     */
13550    private boolean skipInvalidate() {
13551        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13552                (!(mParent instanceof ViewGroup) ||
13553                        !((ViewGroup) mParent).isViewTransitioning(this));
13554    }
13555
13556    /**
13557     * Mark the area defined by dirty as needing to be drawn. If the view is
13558     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13559     * point in the future.
13560     * <p>
13561     * This must be called from a UI thread. To call from a non-UI thread, call
13562     * {@link #postInvalidate()}.
13563     * <p>
13564     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13565     * {@code dirty}.
13566     *
13567     * @param dirty the rectangle representing the bounds of the dirty region
13568     */
13569    public void invalidate(Rect dirty) {
13570        final int scrollX = mScrollX;
13571        final int scrollY = mScrollY;
13572        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13573                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13574    }
13575
13576    /**
13577     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13578     * coordinates of the dirty rect are relative to the view. If the view is
13579     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13580     * point in the future.
13581     * <p>
13582     * This must be called from a UI thread. To call from a non-UI thread, call
13583     * {@link #postInvalidate()}.
13584     *
13585     * @param l the left position of the dirty region
13586     * @param t the top position of the dirty region
13587     * @param r the right position of the dirty region
13588     * @param b the bottom position of the dirty region
13589     */
13590    public void invalidate(int l, int t, int r, int b) {
13591        final int scrollX = mScrollX;
13592        final int scrollY = mScrollY;
13593        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13594    }
13595
13596    /**
13597     * Invalidate the whole view. If the view is visible,
13598     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13599     * the future.
13600     * <p>
13601     * This must be called from a UI thread. To call from a non-UI thread, call
13602     * {@link #postInvalidate()}.
13603     */
13604    public void invalidate() {
13605        invalidate(true);
13606    }
13607
13608    /**
13609     * This is where the invalidate() work actually happens. A full invalidate()
13610     * causes the drawing cache to be invalidated, but this function can be
13611     * called with invalidateCache set to false to skip that invalidation step
13612     * for cases that do not need it (for example, a component that remains at
13613     * the same dimensions with the same content).
13614     *
13615     * @param invalidateCache Whether the drawing cache for this view should be
13616     *            invalidated as well. This is usually true for a full
13617     *            invalidate, but may be set to false if the View's contents or
13618     *            dimensions have not changed.
13619     */
13620    void invalidate(boolean invalidateCache) {
13621        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13622    }
13623
13624    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
13625            boolean fullInvalidate) {
13626        if (mGhostView != null) {
13627            mGhostView.invalidate(true);
13628            return;
13629        }
13630
13631        if (skipInvalidate()) {
13632            return;
13633        }
13634
13635        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
13636                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
13637                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
13638                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
13639            if (fullInvalidate) {
13640                mLastIsOpaque = isOpaque();
13641                mPrivateFlags &= ~PFLAG_DRAWN;
13642            }
13643
13644            mPrivateFlags |= PFLAG_DIRTY;
13645
13646            if (invalidateCache) {
13647                mPrivateFlags |= PFLAG_INVALIDATED;
13648                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13649            }
13650
13651            // Propagate the damage rectangle to the parent view.
13652            final AttachInfo ai = mAttachInfo;
13653            final ViewParent p = mParent;
13654            if (p != null && ai != null && l < r && t < b) {
13655                final Rect damage = ai.mTmpInvalRect;
13656                damage.set(l, t, r, b);
13657                p.invalidateChild(this, damage);
13658            }
13659
13660            // Damage the entire projection receiver, if necessary.
13661            if (mBackground != null && mBackground.isProjected()) {
13662                final View receiver = getProjectionReceiver();
13663                if (receiver != null) {
13664                    receiver.damageInParent();
13665                }
13666            }
13667
13668            // Damage the entire IsolatedZVolume receiving this view's shadow.
13669            if (isHardwareAccelerated() && getZ() != 0) {
13670                damageShadowReceiver();
13671            }
13672        }
13673    }
13674
13675    /**
13676     * @return this view's projection receiver, or {@code null} if none exists
13677     */
13678    private View getProjectionReceiver() {
13679        ViewParent p = getParent();
13680        while (p != null && p instanceof View) {
13681            final View v = (View) p;
13682            if (v.isProjectionReceiver()) {
13683                return v;
13684            }
13685            p = p.getParent();
13686        }
13687
13688        return null;
13689    }
13690
13691    /**
13692     * @return whether the view is a projection receiver
13693     */
13694    private boolean isProjectionReceiver() {
13695        return mBackground != null;
13696    }
13697
13698    /**
13699     * Damage area of the screen that can be covered by this View's shadow.
13700     *
13701     * This method will guarantee that any changes to shadows cast by a View
13702     * are damaged on the screen for future redraw.
13703     */
13704    private void damageShadowReceiver() {
13705        final AttachInfo ai = mAttachInfo;
13706        if (ai != null) {
13707            ViewParent p = getParent();
13708            if (p != null && p instanceof ViewGroup) {
13709                final ViewGroup vg = (ViewGroup) p;
13710                vg.damageInParent();
13711            }
13712        }
13713    }
13714
13715    /**
13716     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
13717     * set any flags or handle all of the cases handled by the default invalidation methods.
13718     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
13719     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
13720     * walk up the hierarchy, transforming the dirty rect as necessary.
13721     *
13722     * The method also handles normal invalidation logic if display list properties are not
13723     * being used in this view. The invalidateParent and forceRedraw flags are used by that
13724     * backup approach, to handle these cases used in the various property-setting methods.
13725     *
13726     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
13727     * are not being used in this view
13728     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
13729     * list properties are not being used in this view
13730     */
13731    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
13732        if (!isHardwareAccelerated()
13733                || !mRenderNode.isValid()
13734                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
13735            if (invalidateParent) {
13736                invalidateParentCaches();
13737            }
13738            if (forceRedraw) {
13739                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13740            }
13741            invalidate(false);
13742        } else {
13743            damageInParent();
13744        }
13745        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
13746            damageShadowReceiver();
13747        }
13748    }
13749
13750    /**
13751     * Tells the parent view to damage this view's bounds.
13752     *
13753     * @hide
13754     */
13755    protected void damageInParent() {
13756        final AttachInfo ai = mAttachInfo;
13757        final ViewParent p = mParent;
13758        if (p != null && ai != null) {
13759            final Rect r = ai.mTmpInvalRect;
13760            r.set(0, 0, mRight - mLeft, mBottom - mTop);
13761            if (mParent instanceof ViewGroup) {
13762                ((ViewGroup) mParent).damageChild(this, r);
13763            } else {
13764                mParent.invalidateChild(this, r);
13765            }
13766        }
13767    }
13768
13769    /**
13770     * Utility method to transform a given Rect by the current matrix of this view.
13771     */
13772    void transformRect(final Rect rect) {
13773        if (!getMatrix().isIdentity()) {
13774            RectF boundingRect = mAttachInfo.mTmpTransformRect;
13775            boundingRect.set(rect);
13776            getMatrix().mapRect(boundingRect);
13777            rect.set((int) Math.floor(boundingRect.left),
13778                    (int) Math.floor(boundingRect.top),
13779                    (int) Math.ceil(boundingRect.right),
13780                    (int) Math.ceil(boundingRect.bottom));
13781        }
13782    }
13783
13784    /**
13785     * Used to indicate that the parent of this view should clear its caches. This functionality
13786     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13787     * which is necessary when various parent-managed properties of the view change, such as
13788     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
13789     * clears the parent caches and does not causes an invalidate event.
13790     *
13791     * @hide
13792     */
13793    protected void invalidateParentCaches() {
13794        if (mParent instanceof View) {
13795            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
13796        }
13797    }
13798
13799    /**
13800     * Used to indicate that the parent of this view should be invalidated. This functionality
13801     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13802     * which is necessary when various parent-managed properties of the view change, such as
13803     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
13804     * an invalidation event to the parent.
13805     *
13806     * @hide
13807     */
13808    protected void invalidateParentIfNeeded() {
13809        if (isHardwareAccelerated() && mParent instanceof View) {
13810            ((View) mParent).invalidate(true);
13811        }
13812    }
13813
13814    /**
13815     * @hide
13816     */
13817    protected void invalidateParentIfNeededAndWasQuickRejected() {
13818        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
13819            // View was rejected last time it was drawn by its parent; this may have changed
13820            invalidateParentIfNeeded();
13821        }
13822    }
13823
13824    /**
13825     * Indicates whether this View is opaque. An opaque View guarantees that it will
13826     * draw all the pixels overlapping its bounds using a fully opaque color.
13827     *
13828     * Subclasses of View should override this method whenever possible to indicate
13829     * whether an instance is opaque. Opaque Views are treated in a special way by
13830     * the View hierarchy, possibly allowing it to perform optimizations during
13831     * invalidate/draw passes.
13832     *
13833     * @return True if this View is guaranteed to be fully opaque, false otherwise.
13834     */
13835    @ViewDebug.ExportedProperty(category = "drawing")
13836    public boolean isOpaque() {
13837        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
13838                getFinalAlpha() >= 1.0f;
13839    }
13840
13841    /**
13842     * @hide
13843     */
13844    protected void computeOpaqueFlags() {
13845        // Opaque if:
13846        //   - Has a background
13847        //   - Background is opaque
13848        //   - Doesn't have scrollbars or scrollbars overlay
13849
13850        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
13851            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
13852        } else {
13853            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
13854        }
13855
13856        final int flags = mViewFlags;
13857        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
13858                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
13859                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
13860            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
13861        } else {
13862            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
13863        }
13864    }
13865
13866    /**
13867     * @hide
13868     */
13869    protected boolean hasOpaqueScrollbars() {
13870        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
13871    }
13872
13873    /**
13874     * @return A handler associated with the thread running the View. This
13875     * handler can be used to pump events in the UI events queue.
13876     */
13877    public Handler getHandler() {
13878        final AttachInfo attachInfo = mAttachInfo;
13879        if (attachInfo != null) {
13880            return attachInfo.mHandler;
13881        }
13882        return null;
13883    }
13884
13885    /**
13886     * Returns the queue of runnable for this view.
13887     *
13888     * @return the queue of runnables for this view
13889     */
13890    private HandlerActionQueue getRunQueue() {
13891        if (mRunQueue == null) {
13892            mRunQueue = new HandlerActionQueue();
13893        }
13894        return mRunQueue;
13895    }
13896
13897    /**
13898     * Gets the view root associated with the View.
13899     * @return The view root, or null if none.
13900     * @hide
13901     */
13902    public ViewRootImpl getViewRootImpl() {
13903        if (mAttachInfo != null) {
13904            return mAttachInfo.mViewRootImpl;
13905        }
13906        return null;
13907    }
13908
13909    /**
13910     * @hide
13911     */
13912    public ThreadedRenderer getHardwareRenderer() {
13913        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
13914    }
13915
13916    /**
13917     * <p>Causes the Runnable to be added to the message queue.
13918     * The runnable will be run on the user interface thread.</p>
13919     *
13920     * @param action The Runnable that will be executed.
13921     *
13922     * @return Returns true if the Runnable was successfully placed in to the
13923     *         message queue.  Returns false on failure, usually because the
13924     *         looper processing the message queue is exiting.
13925     *
13926     * @see #postDelayed
13927     * @see #removeCallbacks
13928     */
13929    public boolean post(Runnable action) {
13930        final AttachInfo attachInfo = mAttachInfo;
13931        if (attachInfo != null) {
13932            return attachInfo.mHandler.post(action);
13933        }
13934
13935        // Postpone the runnable until we know on which thread it needs to run.
13936        // Assume that the runnable will be successfully placed after attach.
13937        getRunQueue().post(action);
13938        return true;
13939    }
13940
13941    /**
13942     * <p>Causes the Runnable to be added to the message queue, to be run
13943     * after the specified amount of time elapses.
13944     * The runnable will be run on the user interface thread.</p>
13945     *
13946     * @param action The Runnable that will be executed.
13947     * @param delayMillis The delay (in milliseconds) until the Runnable
13948     *        will be executed.
13949     *
13950     * @return true if the Runnable was successfully placed in to the
13951     *         message queue.  Returns false on failure, usually because the
13952     *         looper processing the message queue is exiting.  Note that a
13953     *         result of true does not mean the Runnable will be processed --
13954     *         if the looper is quit before the delivery time of the message
13955     *         occurs then the message will be dropped.
13956     *
13957     * @see #post
13958     * @see #removeCallbacks
13959     */
13960    public boolean postDelayed(Runnable action, long delayMillis) {
13961        final AttachInfo attachInfo = mAttachInfo;
13962        if (attachInfo != null) {
13963            return attachInfo.mHandler.postDelayed(action, delayMillis);
13964        }
13965
13966        // Postpone the runnable until we know on which thread it needs to run.
13967        // Assume that the runnable will be successfully placed after attach.
13968        getRunQueue().postDelayed(action, delayMillis);
13969        return true;
13970    }
13971
13972    /**
13973     * <p>Causes the Runnable to execute on the next animation time step.
13974     * The runnable will be run on the user interface thread.</p>
13975     *
13976     * @param action The Runnable that will be executed.
13977     *
13978     * @see #postOnAnimationDelayed
13979     * @see #removeCallbacks
13980     */
13981    public void postOnAnimation(Runnable action) {
13982        final AttachInfo attachInfo = mAttachInfo;
13983        if (attachInfo != null) {
13984            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13985                    Choreographer.CALLBACK_ANIMATION, action, null);
13986        } else {
13987            // Postpone the runnable until we know
13988            // on which thread it needs to run.
13989            getRunQueue().post(action);
13990        }
13991    }
13992
13993    /**
13994     * <p>Causes the Runnable to execute on the next animation time step,
13995     * after the specified amount of time elapses.
13996     * The runnable will be run on the user interface thread.</p>
13997     *
13998     * @param action The Runnable that will be executed.
13999     * @param delayMillis The delay (in milliseconds) until the Runnable
14000     *        will be executed.
14001     *
14002     * @see #postOnAnimation
14003     * @see #removeCallbacks
14004     */
14005    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14006        final AttachInfo attachInfo = mAttachInfo;
14007        if (attachInfo != null) {
14008            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14009                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14010        } else {
14011            // Postpone the runnable until we know
14012            // on which thread it needs to run.
14013            getRunQueue().postDelayed(action, delayMillis);
14014        }
14015    }
14016
14017    /**
14018     * <p>Removes the specified Runnable from the message queue.</p>
14019     *
14020     * @param action The Runnable to remove from the message handling queue
14021     *
14022     * @return true if this view could ask the Handler to remove the Runnable,
14023     *         false otherwise. When the returned value is true, the Runnable
14024     *         may or may not have been actually removed from the message queue
14025     *         (for instance, if the Runnable was not in the queue already.)
14026     *
14027     * @see #post
14028     * @see #postDelayed
14029     * @see #postOnAnimation
14030     * @see #postOnAnimationDelayed
14031     */
14032    public boolean removeCallbacks(Runnable action) {
14033        if (action != null) {
14034            final AttachInfo attachInfo = mAttachInfo;
14035            if (attachInfo != null) {
14036                attachInfo.mHandler.removeCallbacks(action);
14037                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14038                        Choreographer.CALLBACK_ANIMATION, action, null);
14039            }
14040            getRunQueue().removeCallbacks(action);
14041        }
14042        return true;
14043    }
14044
14045    /**
14046     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14047     * Use this to invalidate the View from a non-UI thread.</p>
14048     *
14049     * <p>This method can be invoked from outside of the UI thread
14050     * only when this View is attached to a window.</p>
14051     *
14052     * @see #invalidate()
14053     * @see #postInvalidateDelayed(long)
14054     */
14055    public void postInvalidate() {
14056        postInvalidateDelayed(0);
14057    }
14058
14059    /**
14060     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14061     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14062     *
14063     * <p>This method can be invoked from outside of the UI thread
14064     * only when this View is attached to a window.</p>
14065     *
14066     * @param left The left coordinate of the rectangle to invalidate.
14067     * @param top The top coordinate of the rectangle to invalidate.
14068     * @param right The right coordinate of the rectangle to invalidate.
14069     * @param bottom The bottom coordinate of the rectangle to invalidate.
14070     *
14071     * @see #invalidate(int, int, int, int)
14072     * @see #invalidate(Rect)
14073     * @see #postInvalidateDelayed(long, int, int, int, int)
14074     */
14075    public void postInvalidate(int left, int top, int right, int bottom) {
14076        postInvalidateDelayed(0, left, top, right, bottom);
14077    }
14078
14079    /**
14080     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14081     * loop. Waits for the specified amount of time.</p>
14082     *
14083     * <p>This method can be invoked from outside of the UI thread
14084     * only when this View is attached to a window.</p>
14085     *
14086     * @param delayMilliseconds the duration in milliseconds to delay the
14087     *         invalidation by
14088     *
14089     * @see #invalidate()
14090     * @see #postInvalidate()
14091     */
14092    public void postInvalidateDelayed(long delayMilliseconds) {
14093        // We try only with the AttachInfo because there's no point in invalidating
14094        // if we are not attached to our window
14095        final AttachInfo attachInfo = mAttachInfo;
14096        if (attachInfo != null) {
14097            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14098        }
14099    }
14100
14101    /**
14102     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14103     * through the event loop. Waits for the specified amount of time.</p>
14104     *
14105     * <p>This method can be invoked from outside of the UI thread
14106     * only when this View is attached to a window.</p>
14107     *
14108     * @param delayMilliseconds the duration in milliseconds to delay the
14109     *         invalidation by
14110     * @param left The left coordinate of the rectangle to invalidate.
14111     * @param top The top coordinate of the rectangle to invalidate.
14112     * @param right The right coordinate of the rectangle to invalidate.
14113     * @param bottom The bottom coordinate of the rectangle to invalidate.
14114     *
14115     * @see #invalidate(int, int, int, int)
14116     * @see #invalidate(Rect)
14117     * @see #postInvalidate(int, int, int, int)
14118     */
14119    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14120            int right, int bottom) {
14121
14122        // We try only with the AttachInfo because there's no point in invalidating
14123        // if we are not attached to our window
14124        final AttachInfo attachInfo = mAttachInfo;
14125        if (attachInfo != null) {
14126            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14127            info.target = this;
14128            info.left = left;
14129            info.top = top;
14130            info.right = right;
14131            info.bottom = bottom;
14132
14133            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14134        }
14135    }
14136
14137    /**
14138     * <p>Cause an invalidate to happen on the next animation time step, typically the
14139     * next display frame.</p>
14140     *
14141     * <p>This method can be invoked from outside of the UI thread
14142     * only when this View is attached to a window.</p>
14143     *
14144     * @see #invalidate()
14145     */
14146    public void postInvalidateOnAnimation() {
14147        // We try only with the AttachInfo because there's no point in invalidating
14148        // if we are not attached to our window
14149        final AttachInfo attachInfo = mAttachInfo;
14150        if (attachInfo != null) {
14151            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14152        }
14153    }
14154
14155    /**
14156     * <p>Cause an invalidate of the specified area to happen on the next animation
14157     * time step, typically the next display frame.</p>
14158     *
14159     * <p>This method can be invoked from outside of the UI thread
14160     * only when this View is attached to a window.</p>
14161     *
14162     * @param left The left coordinate of the rectangle to invalidate.
14163     * @param top The top coordinate of the rectangle to invalidate.
14164     * @param right The right coordinate of the rectangle to invalidate.
14165     * @param bottom The bottom coordinate of the rectangle to invalidate.
14166     *
14167     * @see #invalidate(int, int, int, int)
14168     * @see #invalidate(Rect)
14169     */
14170    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14171        // We try only with the AttachInfo because there's no point in invalidating
14172        // if we are not attached to our window
14173        final AttachInfo attachInfo = mAttachInfo;
14174        if (attachInfo != null) {
14175            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14176            info.target = this;
14177            info.left = left;
14178            info.top = top;
14179            info.right = right;
14180            info.bottom = bottom;
14181
14182            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14183        }
14184    }
14185
14186    /**
14187     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14188     * This event is sent at most once every
14189     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14190     */
14191    private void postSendViewScrolledAccessibilityEventCallback() {
14192        if (mSendViewScrolledAccessibilityEvent == null) {
14193            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14194        }
14195        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14196            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14197            postDelayed(mSendViewScrolledAccessibilityEvent,
14198                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14199        }
14200    }
14201
14202    /**
14203     * Called by a parent to request that a child update its values for mScrollX
14204     * and mScrollY if necessary. This will typically be done if the child is
14205     * animating a scroll using a {@link android.widget.Scroller Scroller}
14206     * object.
14207     */
14208    public void computeScroll() {
14209    }
14210
14211    /**
14212     * <p>Indicate whether the horizontal edges are faded when the view is
14213     * scrolled horizontally.</p>
14214     *
14215     * @return true if the horizontal edges should are faded on scroll, false
14216     *         otherwise
14217     *
14218     * @see #setHorizontalFadingEdgeEnabled(boolean)
14219     *
14220     * @attr ref android.R.styleable#View_requiresFadingEdge
14221     */
14222    public boolean isHorizontalFadingEdgeEnabled() {
14223        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14224    }
14225
14226    /**
14227     * <p>Define whether the horizontal edges should be faded when this view
14228     * is scrolled horizontally.</p>
14229     *
14230     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14231     *                                    be faded when the view is scrolled
14232     *                                    horizontally
14233     *
14234     * @see #isHorizontalFadingEdgeEnabled()
14235     *
14236     * @attr ref android.R.styleable#View_requiresFadingEdge
14237     */
14238    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14239        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14240            if (horizontalFadingEdgeEnabled) {
14241                initScrollCache();
14242            }
14243
14244            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14245        }
14246    }
14247
14248    /**
14249     * <p>Indicate whether the vertical edges are faded when the view is
14250     * scrolled horizontally.</p>
14251     *
14252     * @return true if the vertical edges should are faded on scroll, false
14253     *         otherwise
14254     *
14255     * @see #setVerticalFadingEdgeEnabled(boolean)
14256     *
14257     * @attr ref android.R.styleable#View_requiresFadingEdge
14258     */
14259    public boolean isVerticalFadingEdgeEnabled() {
14260        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14261    }
14262
14263    /**
14264     * <p>Define whether the vertical edges should be faded when this view
14265     * is scrolled vertically.</p>
14266     *
14267     * @param verticalFadingEdgeEnabled true if the vertical edges should
14268     *                                  be faded when the view is scrolled
14269     *                                  vertically
14270     *
14271     * @see #isVerticalFadingEdgeEnabled()
14272     *
14273     * @attr ref android.R.styleable#View_requiresFadingEdge
14274     */
14275    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14276        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14277            if (verticalFadingEdgeEnabled) {
14278                initScrollCache();
14279            }
14280
14281            mViewFlags ^= FADING_EDGE_VERTICAL;
14282        }
14283    }
14284
14285    /**
14286     * Returns the strength, or intensity, of the top faded edge. The strength is
14287     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14288     * returns 0.0 or 1.0 but no value in between.
14289     *
14290     * Subclasses should override this method to provide a smoother fade transition
14291     * when scrolling occurs.
14292     *
14293     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14294     */
14295    protected float getTopFadingEdgeStrength() {
14296        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14297    }
14298
14299    /**
14300     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14301     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14302     * returns 0.0 or 1.0 but no value in between.
14303     *
14304     * Subclasses should override this method to provide a smoother fade transition
14305     * when scrolling occurs.
14306     *
14307     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14308     */
14309    protected float getBottomFadingEdgeStrength() {
14310        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14311                computeVerticalScrollRange() ? 1.0f : 0.0f;
14312    }
14313
14314    /**
14315     * Returns the strength, or intensity, of the left faded edge. The strength is
14316     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14317     * returns 0.0 or 1.0 but no value in between.
14318     *
14319     * Subclasses should override this method to provide a smoother fade transition
14320     * when scrolling occurs.
14321     *
14322     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14323     */
14324    protected float getLeftFadingEdgeStrength() {
14325        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14326    }
14327
14328    /**
14329     * Returns the strength, or intensity, of the right faded edge. The strength is
14330     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14331     * returns 0.0 or 1.0 but no value in between.
14332     *
14333     * Subclasses should override this method to provide a smoother fade transition
14334     * when scrolling occurs.
14335     *
14336     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14337     */
14338    protected float getRightFadingEdgeStrength() {
14339        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14340                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14341    }
14342
14343    /**
14344     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14345     * scrollbar is not drawn by default.</p>
14346     *
14347     * @return true if the horizontal scrollbar should be painted, false
14348     *         otherwise
14349     *
14350     * @see #setHorizontalScrollBarEnabled(boolean)
14351     */
14352    public boolean isHorizontalScrollBarEnabled() {
14353        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14354    }
14355
14356    /**
14357     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14358     * scrollbar is not drawn by default.</p>
14359     *
14360     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14361     *                                   be painted
14362     *
14363     * @see #isHorizontalScrollBarEnabled()
14364     */
14365    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14366        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14367            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14368            computeOpaqueFlags();
14369            resolvePadding();
14370        }
14371    }
14372
14373    /**
14374     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14375     * scrollbar is not drawn by default.</p>
14376     *
14377     * @return true if the vertical scrollbar should be painted, false
14378     *         otherwise
14379     *
14380     * @see #setVerticalScrollBarEnabled(boolean)
14381     */
14382    public boolean isVerticalScrollBarEnabled() {
14383        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14384    }
14385
14386    /**
14387     * <p>Define whether the vertical scrollbar should be drawn or not. The
14388     * scrollbar is not drawn by default.</p>
14389     *
14390     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14391     *                                 be painted
14392     *
14393     * @see #isVerticalScrollBarEnabled()
14394     */
14395    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14396        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14397            mViewFlags ^= SCROLLBARS_VERTICAL;
14398            computeOpaqueFlags();
14399            resolvePadding();
14400        }
14401    }
14402
14403    /**
14404     * @hide
14405     */
14406    protected void recomputePadding() {
14407        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14408    }
14409
14410    /**
14411     * Define whether scrollbars will fade when the view is not scrolling.
14412     *
14413     * @param fadeScrollbars whether to enable fading
14414     *
14415     * @attr ref android.R.styleable#View_fadeScrollbars
14416     */
14417    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14418        initScrollCache();
14419        final ScrollabilityCache scrollabilityCache = mScrollCache;
14420        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14421        if (fadeScrollbars) {
14422            scrollabilityCache.state = ScrollabilityCache.OFF;
14423        } else {
14424            scrollabilityCache.state = ScrollabilityCache.ON;
14425        }
14426    }
14427
14428    /**
14429     *
14430     * Returns true if scrollbars will fade when this view is not scrolling
14431     *
14432     * @return true if scrollbar fading is enabled
14433     *
14434     * @attr ref android.R.styleable#View_fadeScrollbars
14435     */
14436    public boolean isScrollbarFadingEnabled() {
14437        return mScrollCache != null && mScrollCache.fadeScrollBars;
14438    }
14439
14440    /**
14441     *
14442     * Returns the delay before scrollbars fade.
14443     *
14444     * @return the delay before scrollbars fade
14445     *
14446     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14447     */
14448    public int getScrollBarDefaultDelayBeforeFade() {
14449        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14450                mScrollCache.scrollBarDefaultDelayBeforeFade;
14451    }
14452
14453    /**
14454     * Define the delay before scrollbars fade.
14455     *
14456     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14457     *
14458     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14459     */
14460    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14461        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14462    }
14463
14464    /**
14465     *
14466     * Returns the scrollbar fade duration.
14467     *
14468     * @return the scrollbar fade duration
14469     *
14470     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14471     */
14472    public int getScrollBarFadeDuration() {
14473        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14474                mScrollCache.scrollBarFadeDuration;
14475    }
14476
14477    /**
14478     * Define the scrollbar fade duration.
14479     *
14480     * @param scrollBarFadeDuration - the scrollbar fade duration
14481     *
14482     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14483     */
14484    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14485        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14486    }
14487
14488    /**
14489     *
14490     * Returns the scrollbar size.
14491     *
14492     * @return the scrollbar size
14493     *
14494     * @attr ref android.R.styleable#View_scrollbarSize
14495     */
14496    public int getScrollBarSize() {
14497        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14498                mScrollCache.scrollBarSize;
14499    }
14500
14501    /**
14502     * Define the scrollbar size.
14503     *
14504     * @param scrollBarSize - the scrollbar size
14505     *
14506     * @attr ref android.R.styleable#View_scrollbarSize
14507     */
14508    public void setScrollBarSize(int scrollBarSize) {
14509        getScrollCache().scrollBarSize = scrollBarSize;
14510    }
14511
14512    /**
14513     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14514     * inset. When inset, they add to the padding of the view. And the scrollbars
14515     * can be drawn inside the padding area or on the edge of the view. For example,
14516     * if a view has a background drawable and you want to draw the scrollbars
14517     * inside the padding specified by the drawable, you can use
14518     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14519     * appear at the edge of the view, ignoring the padding, then you can use
14520     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14521     * @param style the style of the scrollbars. Should be one of
14522     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14523     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14524     * @see #SCROLLBARS_INSIDE_OVERLAY
14525     * @see #SCROLLBARS_INSIDE_INSET
14526     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14527     * @see #SCROLLBARS_OUTSIDE_INSET
14528     *
14529     * @attr ref android.R.styleable#View_scrollbarStyle
14530     */
14531    public void setScrollBarStyle(@ScrollBarStyle int style) {
14532        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14533            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14534            computeOpaqueFlags();
14535            resolvePadding();
14536        }
14537    }
14538
14539    /**
14540     * <p>Returns the current scrollbar style.</p>
14541     * @return the current scrollbar style
14542     * @see #SCROLLBARS_INSIDE_OVERLAY
14543     * @see #SCROLLBARS_INSIDE_INSET
14544     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14545     * @see #SCROLLBARS_OUTSIDE_INSET
14546     *
14547     * @attr ref android.R.styleable#View_scrollbarStyle
14548     */
14549    @ViewDebug.ExportedProperty(mapping = {
14550            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14551            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14552            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14553            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14554    })
14555    @ScrollBarStyle
14556    public int getScrollBarStyle() {
14557        return mViewFlags & SCROLLBARS_STYLE_MASK;
14558    }
14559
14560    /**
14561     * <p>Compute the horizontal range that the horizontal scrollbar
14562     * represents.</p>
14563     *
14564     * <p>The range is expressed in arbitrary units that must be the same as the
14565     * units used by {@link #computeHorizontalScrollExtent()} and
14566     * {@link #computeHorizontalScrollOffset()}.</p>
14567     *
14568     * <p>The default range is the drawing width of this view.</p>
14569     *
14570     * @return the total horizontal range represented by the horizontal
14571     *         scrollbar
14572     *
14573     * @see #computeHorizontalScrollExtent()
14574     * @see #computeHorizontalScrollOffset()
14575     * @see android.widget.ScrollBarDrawable
14576     */
14577    protected int computeHorizontalScrollRange() {
14578        return getWidth();
14579    }
14580
14581    /**
14582     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14583     * within the horizontal range. This value is used to compute the position
14584     * of the thumb within the scrollbar's track.</p>
14585     *
14586     * <p>The range is expressed in arbitrary units that must be the same as the
14587     * units used by {@link #computeHorizontalScrollRange()} and
14588     * {@link #computeHorizontalScrollExtent()}.</p>
14589     *
14590     * <p>The default offset is the scroll offset of this view.</p>
14591     *
14592     * @return the horizontal offset of the scrollbar's thumb
14593     *
14594     * @see #computeHorizontalScrollRange()
14595     * @see #computeHorizontalScrollExtent()
14596     * @see android.widget.ScrollBarDrawable
14597     */
14598    protected int computeHorizontalScrollOffset() {
14599        return mScrollX;
14600    }
14601
14602    /**
14603     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14604     * within the horizontal range. This value is used to compute the length
14605     * of the thumb within the scrollbar's track.</p>
14606     *
14607     * <p>The range is expressed in arbitrary units that must be the same as the
14608     * units used by {@link #computeHorizontalScrollRange()} and
14609     * {@link #computeHorizontalScrollOffset()}.</p>
14610     *
14611     * <p>The default extent is the drawing width of this view.</p>
14612     *
14613     * @return the horizontal extent of the scrollbar's thumb
14614     *
14615     * @see #computeHorizontalScrollRange()
14616     * @see #computeHorizontalScrollOffset()
14617     * @see android.widget.ScrollBarDrawable
14618     */
14619    protected int computeHorizontalScrollExtent() {
14620        return getWidth();
14621    }
14622
14623    /**
14624     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14625     *
14626     * <p>The range is expressed in arbitrary units that must be the same as the
14627     * units used by {@link #computeVerticalScrollExtent()} and
14628     * {@link #computeVerticalScrollOffset()}.</p>
14629     *
14630     * @return the total vertical range represented by the vertical scrollbar
14631     *
14632     * <p>The default range is the drawing height of this view.</p>
14633     *
14634     * @see #computeVerticalScrollExtent()
14635     * @see #computeVerticalScrollOffset()
14636     * @see android.widget.ScrollBarDrawable
14637     */
14638    protected int computeVerticalScrollRange() {
14639        return getHeight();
14640    }
14641
14642    /**
14643     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14644     * within the horizontal range. This value is used to compute the position
14645     * of the thumb within the scrollbar's track.</p>
14646     *
14647     * <p>The range is expressed in arbitrary units that must be the same as the
14648     * units used by {@link #computeVerticalScrollRange()} and
14649     * {@link #computeVerticalScrollExtent()}.</p>
14650     *
14651     * <p>The default offset is the scroll offset of this view.</p>
14652     *
14653     * @return the vertical offset of the scrollbar's thumb
14654     *
14655     * @see #computeVerticalScrollRange()
14656     * @see #computeVerticalScrollExtent()
14657     * @see android.widget.ScrollBarDrawable
14658     */
14659    protected int computeVerticalScrollOffset() {
14660        return mScrollY;
14661    }
14662
14663    /**
14664     * <p>Compute the vertical extent of the vertical scrollbar's thumb
14665     * within the vertical range. This value is used to compute the length
14666     * of the thumb within the scrollbar's track.</p>
14667     *
14668     * <p>The range is expressed in arbitrary units that must be the same as the
14669     * units used by {@link #computeVerticalScrollRange()} and
14670     * {@link #computeVerticalScrollOffset()}.</p>
14671     *
14672     * <p>The default extent is the drawing height of this view.</p>
14673     *
14674     * @return the vertical extent of the scrollbar's thumb
14675     *
14676     * @see #computeVerticalScrollRange()
14677     * @see #computeVerticalScrollOffset()
14678     * @see android.widget.ScrollBarDrawable
14679     */
14680    protected int computeVerticalScrollExtent() {
14681        return getHeight();
14682    }
14683
14684    /**
14685     * Check if this view can be scrolled horizontally in a certain direction.
14686     *
14687     * @param direction Negative to check scrolling left, positive to check scrolling right.
14688     * @return true if this view can be scrolled in the specified direction, false otherwise.
14689     */
14690    public boolean canScrollHorizontally(int direction) {
14691        final int offset = computeHorizontalScrollOffset();
14692        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
14693        if (range == 0) return false;
14694        if (direction < 0) {
14695            return offset > 0;
14696        } else {
14697            return offset < range - 1;
14698        }
14699    }
14700
14701    /**
14702     * Check if this view can be scrolled vertically in a certain direction.
14703     *
14704     * @param direction Negative to check scrolling up, positive to check scrolling down.
14705     * @return true if this view can be scrolled in the specified direction, false otherwise.
14706     */
14707    public boolean canScrollVertically(int direction) {
14708        final int offset = computeVerticalScrollOffset();
14709        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
14710        if (range == 0) return false;
14711        if (direction < 0) {
14712            return offset > 0;
14713        } else {
14714            return offset < range - 1;
14715        }
14716    }
14717
14718    void getScrollIndicatorBounds(@NonNull Rect out) {
14719        out.left = mScrollX;
14720        out.right = mScrollX + mRight - mLeft;
14721        out.top = mScrollY;
14722        out.bottom = mScrollY + mBottom - mTop;
14723    }
14724
14725    private void onDrawScrollIndicators(Canvas c) {
14726        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
14727            // No scroll indicators enabled.
14728            return;
14729        }
14730
14731        final Drawable dr = mScrollIndicatorDrawable;
14732        if (dr == null) {
14733            // Scroll indicators aren't supported here.
14734            return;
14735        }
14736
14737        final int h = dr.getIntrinsicHeight();
14738        final int w = dr.getIntrinsicWidth();
14739        final Rect rect = mAttachInfo.mTmpInvalRect;
14740        getScrollIndicatorBounds(rect);
14741
14742        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
14743            final boolean canScrollUp = canScrollVertically(-1);
14744            if (canScrollUp) {
14745                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
14746                dr.draw(c);
14747            }
14748        }
14749
14750        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
14751            final boolean canScrollDown = canScrollVertically(1);
14752            if (canScrollDown) {
14753                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
14754                dr.draw(c);
14755            }
14756        }
14757
14758        final int leftRtl;
14759        final int rightRtl;
14760        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14761            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
14762            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
14763        } else {
14764            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
14765            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
14766        }
14767
14768        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
14769        if ((mPrivateFlags3 & leftMask) != 0) {
14770            final boolean canScrollLeft = canScrollHorizontally(-1);
14771            if (canScrollLeft) {
14772                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
14773                dr.draw(c);
14774            }
14775        }
14776
14777        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
14778        if ((mPrivateFlags3 & rightMask) != 0) {
14779            final boolean canScrollRight = canScrollHorizontally(1);
14780            if (canScrollRight) {
14781                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
14782                dr.draw(c);
14783            }
14784        }
14785    }
14786
14787    private void getHorizontalScrollBarBounds(Rect bounds) {
14788        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14789        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14790                && !isVerticalScrollBarHidden();
14791        final int size = getHorizontalScrollbarHeight();
14792        final int verticalScrollBarGap = drawVerticalScrollBar ?
14793                getVerticalScrollbarWidth() : 0;
14794        final int width = mRight - mLeft;
14795        final int height = mBottom - mTop;
14796        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
14797        bounds.left = mScrollX + (mPaddingLeft & inside);
14798        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
14799        bounds.bottom = bounds.top + size;
14800    }
14801
14802    private void getVerticalScrollBarBounds(Rect bounds) {
14803        if (mRoundScrollbarRenderer == null) {
14804            getStraightVerticalScrollBarBounds(bounds);
14805        } else {
14806            getRoundVerticalScrollBarBounds(bounds);
14807        }
14808    }
14809
14810    private void getRoundVerticalScrollBarBounds(Rect bounds) {
14811        final int width = mRight - mLeft;
14812        final int height = mBottom - mTop;
14813        // Do not take padding into account as we always want the scrollbars
14814        // to hug the screen for round wearable devices.
14815        bounds.left = mScrollX;
14816        bounds.top = mScrollY;
14817        bounds.right = bounds.left + width;
14818        bounds.bottom = mScrollY + height;
14819    }
14820
14821    private void getStraightVerticalScrollBarBounds(Rect bounds) {
14822        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14823        final int size = getVerticalScrollbarWidth();
14824        int verticalScrollbarPosition = mVerticalScrollbarPosition;
14825        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
14826            verticalScrollbarPosition = isLayoutRtl() ?
14827                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
14828        }
14829        final int width = mRight - mLeft;
14830        final int height = mBottom - mTop;
14831        switch (verticalScrollbarPosition) {
14832            default:
14833            case SCROLLBAR_POSITION_RIGHT:
14834                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
14835                break;
14836            case SCROLLBAR_POSITION_LEFT:
14837                bounds.left = mScrollX + (mUserPaddingLeft & inside);
14838                break;
14839        }
14840        bounds.top = mScrollY + (mPaddingTop & inside);
14841        bounds.right = bounds.left + size;
14842        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
14843    }
14844
14845    /**
14846     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
14847     * scrollbars are painted only if they have been awakened first.</p>
14848     *
14849     * @param canvas the canvas on which to draw the scrollbars
14850     *
14851     * @see #awakenScrollBars(int)
14852     */
14853    protected final void onDrawScrollBars(Canvas canvas) {
14854        // scrollbars are drawn only when the animation is running
14855        final ScrollabilityCache cache = mScrollCache;
14856
14857        if (cache != null) {
14858
14859            int state = cache.state;
14860
14861            if (state == ScrollabilityCache.OFF) {
14862                return;
14863            }
14864
14865            boolean invalidate = false;
14866
14867            if (state == ScrollabilityCache.FADING) {
14868                // We're fading -- get our fade interpolation
14869                if (cache.interpolatorValues == null) {
14870                    cache.interpolatorValues = new float[1];
14871                }
14872
14873                float[] values = cache.interpolatorValues;
14874
14875                // Stops the animation if we're done
14876                if (cache.scrollBarInterpolator.timeToValues(values) ==
14877                        Interpolator.Result.FREEZE_END) {
14878                    cache.state = ScrollabilityCache.OFF;
14879                } else {
14880                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
14881                }
14882
14883                // This will make the scroll bars inval themselves after
14884                // drawing. We only want this when we're fading so that
14885                // we prevent excessive redraws
14886                invalidate = true;
14887            } else {
14888                // We're just on -- but we may have been fading before so
14889                // reset alpha
14890                cache.scrollBar.mutate().setAlpha(255);
14891            }
14892
14893            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
14894            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14895                    && !isVerticalScrollBarHidden();
14896
14897            // Fork out the scroll bar drawing for round wearable devices.
14898            if (mRoundScrollbarRenderer != null) {
14899                if (drawVerticalScrollBar) {
14900                    final Rect bounds = cache.mScrollBarBounds;
14901                    getVerticalScrollBarBounds(bounds);
14902                    mRoundScrollbarRenderer.drawRoundScrollbars(
14903                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
14904                    if (invalidate) {
14905                        invalidate();
14906                    }
14907                }
14908                // Do not draw horizontal scroll bars for round wearable devices.
14909            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
14910                final ScrollBarDrawable scrollBar = cache.scrollBar;
14911
14912                if (drawHorizontalScrollBar) {
14913                    scrollBar.setParameters(computeHorizontalScrollRange(),
14914                            computeHorizontalScrollOffset(),
14915                            computeHorizontalScrollExtent(), false);
14916                    final Rect bounds = cache.mScrollBarBounds;
14917                    getHorizontalScrollBarBounds(bounds);
14918                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14919                            bounds.right, bounds.bottom);
14920                    if (invalidate) {
14921                        invalidate(bounds);
14922                    }
14923                }
14924
14925                if (drawVerticalScrollBar) {
14926                    scrollBar.setParameters(computeVerticalScrollRange(),
14927                            computeVerticalScrollOffset(),
14928                            computeVerticalScrollExtent(), true);
14929                    final Rect bounds = cache.mScrollBarBounds;
14930                    getVerticalScrollBarBounds(bounds);
14931                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14932                            bounds.right, bounds.bottom);
14933                    if (invalidate) {
14934                        invalidate(bounds);
14935                    }
14936                }
14937            }
14938        }
14939    }
14940
14941    /**
14942     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
14943     * FastScroller is visible.
14944     * @return whether to temporarily hide the vertical scrollbar
14945     * @hide
14946     */
14947    protected boolean isVerticalScrollBarHidden() {
14948        return false;
14949    }
14950
14951    /**
14952     * <p>Draw the horizontal scrollbar if
14953     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
14954     *
14955     * @param canvas the canvas on which to draw the scrollbar
14956     * @param scrollBar the scrollbar's drawable
14957     *
14958     * @see #isHorizontalScrollBarEnabled()
14959     * @see #computeHorizontalScrollRange()
14960     * @see #computeHorizontalScrollExtent()
14961     * @see #computeHorizontalScrollOffset()
14962     * @see android.widget.ScrollBarDrawable
14963     * @hide
14964     */
14965    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
14966            int l, int t, int r, int b) {
14967        scrollBar.setBounds(l, t, r, b);
14968        scrollBar.draw(canvas);
14969    }
14970
14971    /**
14972     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
14973     * returns true.</p>
14974     *
14975     * @param canvas the canvas on which to draw the scrollbar
14976     * @param scrollBar the scrollbar's drawable
14977     *
14978     * @see #isVerticalScrollBarEnabled()
14979     * @see #computeVerticalScrollRange()
14980     * @see #computeVerticalScrollExtent()
14981     * @see #computeVerticalScrollOffset()
14982     * @see android.widget.ScrollBarDrawable
14983     * @hide
14984     */
14985    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14986            int l, int t, int r, int b) {
14987        scrollBar.setBounds(l, t, r, b);
14988        scrollBar.draw(canvas);
14989    }
14990
14991    /**
14992     * Implement this to do your drawing.
14993     *
14994     * @param canvas the canvas on which the background will be drawn
14995     */
14996    protected void onDraw(Canvas canvas) {
14997    }
14998
14999    /*
15000     * Caller is responsible for calling requestLayout if necessary.
15001     * (This allows addViewInLayout to not request a new layout.)
15002     */
15003    void assignParent(ViewParent parent) {
15004        if (mParent == null) {
15005            mParent = parent;
15006        } else if (parent == null) {
15007            mParent = null;
15008        } else {
15009            throw new RuntimeException("view " + this + " being added, but"
15010                    + " it already has a parent");
15011        }
15012    }
15013
15014    /**
15015     * This is called when the view is attached to a window.  At this point it
15016     * has a Surface and will start drawing.  Note that this function is
15017     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15018     * however it may be called any time before the first onDraw -- including
15019     * before or after {@link #onMeasure(int, int)}.
15020     *
15021     * @see #onDetachedFromWindow()
15022     */
15023    @CallSuper
15024    protected void onAttachedToWindow() {
15025        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15026            mParent.requestTransparentRegion(this);
15027        }
15028
15029        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15030
15031        jumpDrawablesToCurrentState();
15032
15033        resetSubtreeAccessibilityStateChanged();
15034
15035        // rebuild, since Outline not maintained while View is detached
15036        rebuildOutline();
15037
15038        if (isFocused()) {
15039            InputMethodManager imm = InputMethodManager.peekInstance();
15040            if (imm != null) {
15041                imm.focusIn(this);
15042            }
15043        }
15044    }
15045
15046    /**
15047     * Resolve all RTL related properties.
15048     *
15049     * @return true if resolution of RTL properties has been done
15050     *
15051     * @hide
15052     */
15053    public boolean resolveRtlPropertiesIfNeeded() {
15054        if (!needRtlPropertiesResolution()) return false;
15055
15056        // Order is important here: LayoutDirection MUST be resolved first
15057        if (!isLayoutDirectionResolved()) {
15058            resolveLayoutDirection();
15059            resolveLayoutParams();
15060        }
15061        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15062        if (!isTextDirectionResolved()) {
15063            resolveTextDirection();
15064        }
15065        if (!isTextAlignmentResolved()) {
15066            resolveTextAlignment();
15067        }
15068        // Should resolve Drawables before Padding because we need the layout direction of the
15069        // Drawable to correctly resolve Padding.
15070        if (!areDrawablesResolved()) {
15071            resolveDrawables();
15072        }
15073        if (!isPaddingResolved()) {
15074            resolvePadding();
15075        }
15076        onRtlPropertiesChanged(getLayoutDirection());
15077        return true;
15078    }
15079
15080    /**
15081     * Reset resolution of all RTL related properties.
15082     *
15083     * @hide
15084     */
15085    public void resetRtlProperties() {
15086        resetResolvedLayoutDirection();
15087        resetResolvedTextDirection();
15088        resetResolvedTextAlignment();
15089        resetResolvedPadding();
15090        resetResolvedDrawables();
15091    }
15092
15093    /**
15094     * @see #onScreenStateChanged(int)
15095     */
15096    void dispatchScreenStateChanged(int screenState) {
15097        onScreenStateChanged(screenState);
15098    }
15099
15100    /**
15101     * This method is called whenever the state of the screen this view is
15102     * attached to changes. A state change will usually occurs when the screen
15103     * turns on or off (whether it happens automatically or the user does it
15104     * manually.)
15105     *
15106     * @param screenState The new state of the screen. Can be either
15107     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15108     */
15109    public void onScreenStateChanged(int screenState) {
15110    }
15111
15112    /**
15113     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15114     */
15115    private boolean hasRtlSupport() {
15116        return mContext.getApplicationInfo().hasRtlSupport();
15117    }
15118
15119    /**
15120     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15121     * RTL not supported)
15122     */
15123    private boolean isRtlCompatibilityMode() {
15124        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15125        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15126    }
15127
15128    /**
15129     * @return true if RTL properties need resolution.
15130     *
15131     */
15132    private boolean needRtlPropertiesResolution() {
15133        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15134    }
15135
15136    /**
15137     * Called when any RTL property (layout direction or text direction or text alignment) has
15138     * been changed.
15139     *
15140     * Subclasses need to override this method to take care of cached information that depends on the
15141     * resolved layout direction, or to inform child views that inherit their layout direction.
15142     *
15143     * The default implementation does nothing.
15144     *
15145     * @param layoutDirection the direction of the layout
15146     *
15147     * @see #LAYOUT_DIRECTION_LTR
15148     * @see #LAYOUT_DIRECTION_RTL
15149     */
15150    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15151    }
15152
15153    /**
15154     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15155     * that the parent directionality can and will be resolved before its children.
15156     *
15157     * @return true if resolution has been done, false otherwise.
15158     *
15159     * @hide
15160     */
15161    public boolean resolveLayoutDirection() {
15162        // Clear any previous layout direction resolution
15163        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15164
15165        if (hasRtlSupport()) {
15166            // Set resolved depending on layout direction
15167            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15168                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15169                case LAYOUT_DIRECTION_INHERIT:
15170                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15171                    // later to get the correct resolved value
15172                    if (!canResolveLayoutDirection()) return false;
15173
15174                    // Parent has not yet resolved, LTR is still the default
15175                    try {
15176                        if (!mParent.isLayoutDirectionResolved()) return false;
15177
15178                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15179                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15180                        }
15181                    } catch (AbstractMethodError e) {
15182                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15183                                " does not fully implement ViewParent", e);
15184                    }
15185                    break;
15186                case LAYOUT_DIRECTION_RTL:
15187                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15188                    break;
15189                case LAYOUT_DIRECTION_LOCALE:
15190                    if((LAYOUT_DIRECTION_RTL ==
15191                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15192                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15193                    }
15194                    break;
15195                default:
15196                    // Nothing to do, LTR by default
15197            }
15198        }
15199
15200        // Set to resolved
15201        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15202        return true;
15203    }
15204
15205    /**
15206     * Check if layout direction resolution can be done.
15207     *
15208     * @return true if layout direction resolution can be done otherwise return false.
15209     */
15210    public boolean canResolveLayoutDirection() {
15211        switch (getRawLayoutDirection()) {
15212            case LAYOUT_DIRECTION_INHERIT:
15213                if (mParent != null) {
15214                    try {
15215                        return mParent.canResolveLayoutDirection();
15216                    } catch (AbstractMethodError e) {
15217                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15218                                " does not fully implement ViewParent", e);
15219                    }
15220                }
15221                return false;
15222
15223            default:
15224                return true;
15225        }
15226    }
15227
15228    /**
15229     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15230     * {@link #onMeasure(int, int)}.
15231     *
15232     * @hide
15233     */
15234    public void resetResolvedLayoutDirection() {
15235        // Reset the current resolved bits
15236        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15237    }
15238
15239    /**
15240     * @return true if the layout direction is inherited.
15241     *
15242     * @hide
15243     */
15244    public boolean isLayoutDirectionInherited() {
15245        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15246    }
15247
15248    /**
15249     * @return true if layout direction has been resolved.
15250     */
15251    public boolean isLayoutDirectionResolved() {
15252        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15253    }
15254
15255    /**
15256     * Return if padding has been resolved
15257     *
15258     * @hide
15259     */
15260    boolean isPaddingResolved() {
15261        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15262    }
15263
15264    /**
15265     * Resolves padding depending on layout direction, if applicable, and
15266     * recomputes internal padding values to adjust for scroll bars.
15267     *
15268     * @hide
15269     */
15270    public void resolvePadding() {
15271        final int resolvedLayoutDirection = getLayoutDirection();
15272
15273        if (!isRtlCompatibilityMode()) {
15274            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15275            // If start / end padding are defined, they will be resolved (hence overriding) to
15276            // left / right or right / left depending on the resolved layout direction.
15277            // If start / end padding are not defined, use the left / right ones.
15278            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15279                Rect padding = sThreadLocal.get();
15280                if (padding == null) {
15281                    padding = new Rect();
15282                    sThreadLocal.set(padding);
15283                }
15284                mBackground.getPadding(padding);
15285                if (!mLeftPaddingDefined) {
15286                    mUserPaddingLeftInitial = padding.left;
15287                }
15288                if (!mRightPaddingDefined) {
15289                    mUserPaddingRightInitial = padding.right;
15290                }
15291            }
15292            switch (resolvedLayoutDirection) {
15293                case LAYOUT_DIRECTION_RTL:
15294                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15295                        mUserPaddingRight = mUserPaddingStart;
15296                    } else {
15297                        mUserPaddingRight = mUserPaddingRightInitial;
15298                    }
15299                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15300                        mUserPaddingLeft = mUserPaddingEnd;
15301                    } else {
15302                        mUserPaddingLeft = mUserPaddingLeftInitial;
15303                    }
15304                    break;
15305                case LAYOUT_DIRECTION_LTR:
15306                default:
15307                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15308                        mUserPaddingLeft = mUserPaddingStart;
15309                    } else {
15310                        mUserPaddingLeft = mUserPaddingLeftInitial;
15311                    }
15312                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15313                        mUserPaddingRight = mUserPaddingEnd;
15314                    } else {
15315                        mUserPaddingRight = mUserPaddingRightInitial;
15316                    }
15317            }
15318
15319            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15320        }
15321
15322        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15323        onRtlPropertiesChanged(resolvedLayoutDirection);
15324
15325        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15326    }
15327
15328    /**
15329     * Reset the resolved layout direction.
15330     *
15331     * @hide
15332     */
15333    public void resetResolvedPadding() {
15334        resetResolvedPaddingInternal();
15335    }
15336
15337    /**
15338     * Used when we only want to reset *this* view's padding and not trigger overrides
15339     * in ViewGroup that reset children too.
15340     */
15341    void resetResolvedPaddingInternal() {
15342        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15343    }
15344
15345    /**
15346     * This is called when the view is detached from a window.  At this point it
15347     * no longer has a surface for drawing.
15348     *
15349     * @see #onAttachedToWindow()
15350     */
15351    @CallSuper
15352    protected void onDetachedFromWindow() {
15353    }
15354
15355    /**
15356     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15357     * after onDetachedFromWindow().
15358     *
15359     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15360     * The super method should be called at the end of the overridden method to ensure
15361     * subclasses are destroyed first
15362     *
15363     * @hide
15364     */
15365    @CallSuper
15366    protected void onDetachedFromWindowInternal() {
15367        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15368        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15369        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15370
15371        removeUnsetPressCallback();
15372        removeLongPressCallback();
15373        removePerformClickCallback();
15374        removeSendViewScrolledAccessibilityEventCallback();
15375        stopNestedScroll();
15376
15377        // Anything that started animating right before detach should already
15378        // be in its final state when re-attached.
15379        jumpDrawablesToCurrentState();
15380
15381        destroyDrawingCache();
15382
15383        cleanupDraw();
15384        mCurrentAnimation = null;
15385    }
15386
15387    private void cleanupDraw() {
15388        resetDisplayList();
15389        if (mAttachInfo != null) {
15390            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15391        }
15392    }
15393
15394    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15395    }
15396
15397    /**
15398     * @return The number of times this view has been attached to a window
15399     */
15400    protected int getWindowAttachCount() {
15401        return mWindowAttachCount;
15402    }
15403
15404    /**
15405     * Retrieve a unique token identifying the window this view is attached to.
15406     * @return Return the window's token for use in
15407     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15408     */
15409    public IBinder getWindowToken() {
15410        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15411    }
15412
15413    /**
15414     * Retrieve the {@link WindowId} for the window this view is
15415     * currently attached to.
15416     */
15417    public WindowId getWindowId() {
15418        if (mAttachInfo == null) {
15419            return null;
15420        }
15421        if (mAttachInfo.mWindowId == null) {
15422            try {
15423                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15424                        mAttachInfo.mWindowToken);
15425                mAttachInfo.mWindowId = new WindowId(
15426                        mAttachInfo.mIWindowId);
15427            } catch (RemoteException e) {
15428            }
15429        }
15430        return mAttachInfo.mWindowId;
15431    }
15432
15433    /**
15434     * Retrieve a unique token identifying the top-level "real" window of
15435     * the window that this view is attached to.  That is, this is like
15436     * {@link #getWindowToken}, except if the window this view in is a panel
15437     * window (attached to another containing window), then the token of
15438     * the containing window is returned instead.
15439     *
15440     * @return Returns the associated window token, either
15441     * {@link #getWindowToken()} or the containing window's token.
15442     */
15443    public IBinder getApplicationWindowToken() {
15444        AttachInfo ai = mAttachInfo;
15445        if (ai != null) {
15446            IBinder appWindowToken = ai.mPanelParentWindowToken;
15447            if (appWindowToken == null) {
15448                appWindowToken = ai.mWindowToken;
15449            }
15450            return appWindowToken;
15451        }
15452        return null;
15453    }
15454
15455    /**
15456     * Gets the logical display to which the view's window has been attached.
15457     *
15458     * @return The logical display, or null if the view is not currently attached to a window.
15459     */
15460    public Display getDisplay() {
15461        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15462    }
15463
15464    /**
15465     * Retrieve private session object this view hierarchy is using to
15466     * communicate with the window manager.
15467     * @return the session object to communicate with the window manager
15468     */
15469    /*package*/ IWindowSession getWindowSession() {
15470        return mAttachInfo != null ? mAttachInfo.mSession : null;
15471    }
15472
15473    /**
15474     * Return the visibility value of the least visible component passed.
15475     */
15476    int combineVisibility(int vis1, int vis2) {
15477        // This works because VISIBLE < INVISIBLE < GONE.
15478        return Math.max(vis1, vis2);
15479    }
15480
15481    /**
15482     * @param info the {@link android.view.View.AttachInfo} to associated with
15483     *        this view
15484     */
15485    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15486        mAttachInfo = info;
15487        if (mOverlay != null) {
15488            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15489        }
15490        mWindowAttachCount++;
15491        // We will need to evaluate the drawable state at least once.
15492        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15493        if (mFloatingTreeObserver != null) {
15494            info.mTreeObserver.merge(mFloatingTreeObserver);
15495            mFloatingTreeObserver = null;
15496        }
15497
15498        registerPendingFrameMetricsObservers();
15499
15500        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15501            mAttachInfo.mScrollContainers.add(this);
15502            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15503        }
15504        // Transfer all pending runnables.
15505        if (mRunQueue != null) {
15506            mRunQueue.executeActions(info.mHandler);
15507            mRunQueue = null;
15508        }
15509        performCollectViewAttributes(mAttachInfo, visibility);
15510        onAttachedToWindow();
15511
15512        ListenerInfo li = mListenerInfo;
15513        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15514                li != null ? li.mOnAttachStateChangeListeners : null;
15515        if (listeners != null && listeners.size() > 0) {
15516            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15517            // perform the dispatching. The iterator is a safe guard against listeners that
15518            // could mutate the list by calling the various add/remove methods. This prevents
15519            // the array from being modified while we iterate it.
15520            for (OnAttachStateChangeListener listener : listeners) {
15521                listener.onViewAttachedToWindow(this);
15522            }
15523        }
15524
15525        int vis = info.mWindowVisibility;
15526        if (vis != GONE) {
15527            onWindowVisibilityChanged(vis);
15528            if (isShown()) {
15529                // Calling onVisibilityAggregated directly here since the subtree will also
15530                // receive dispatchAttachedToWindow and this same call
15531                onVisibilityAggregated(vis == VISIBLE);
15532            }
15533        }
15534
15535        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15536        // As all views in the subtree will already receive dispatchAttachedToWindow
15537        // traversing the subtree again here is not desired.
15538        onVisibilityChanged(this, visibility);
15539
15540        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15541            // If nobody has evaluated the drawable state yet, then do it now.
15542            refreshDrawableState();
15543        }
15544        needGlobalAttributesUpdate(false);
15545    }
15546
15547    void dispatchDetachedFromWindow() {
15548        AttachInfo info = mAttachInfo;
15549        if (info != null) {
15550            int vis = info.mWindowVisibility;
15551            if (vis != GONE) {
15552                onWindowVisibilityChanged(GONE);
15553                if (isShown()) {
15554                    // Invoking onVisibilityAggregated directly here since the subtree
15555                    // will also receive detached from window
15556                    onVisibilityAggregated(false);
15557                }
15558            }
15559        }
15560
15561        onDetachedFromWindow();
15562        onDetachedFromWindowInternal();
15563
15564        InputMethodManager imm = InputMethodManager.peekInstance();
15565        if (imm != null) {
15566            imm.onViewDetachedFromWindow(this);
15567        }
15568
15569        ListenerInfo li = mListenerInfo;
15570        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15571                li != null ? li.mOnAttachStateChangeListeners : null;
15572        if (listeners != null && listeners.size() > 0) {
15573            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15574            // perform the dispatching. The iterator is a safe guard against listeners that
15575            // could mutate the list by calling the various add/remove methods. This prevents
15576            // the array from being modified while we iterate it.
15577            for (OnAttachStateChangeListener listener : listeners) {
15578                listener.onViewDetachedFromWindow(this);
15579            }
15580        }
15581
15582        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15583            mAttachInfo.mScrollContainers.remove(this);
15584            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15585        }
15586
15587        mAttachInfo = null;
15588        if (mOverlay != null) {
15589            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15590        }
15591    }
15592
15593    /**
15594     * Cancel any deferred high-level input events that were previously posted to the event queue.
15595     *
15596     * <p>Many views post high-level events such as click handlers to the event queue
15597     * to run deferred in order to preserve a desired user experience - clearing visible
15598     * pressed states before executing, etc. This method will abort any events of this nature
15599     * that are currently in flight.</p>
15600     *
15601     * <p>Custom views that generate their own high-level deferred input events should override
15602     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15603     *
15604     * <p>This will also cancel pending input events for any child views.</p>
15605     *
15606     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15607     * This will not impact newer events posted after this call that may occur as a result of
15608     * lower-level input events still waiting in the queue. If you are trying to prevent
15609     * double-submitted  events for the duration of some sort of asynchronous transaction
15610     * you should also take other steps to protect against unexpected double inputs e.g. calling
15611     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15612     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15613     */
15614    public final void cancelPendingInputEvents() {
15615        dispatchCancelPendingInputEvents();
15616    }
15617
15618    /**
15619     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15620     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15621     */
15622    void dispatchCancelPendingInputEvents() {
15623        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15624        onCancelPendingInputEvents();
15625        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15626            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15627                    " did not call through to super.onCancelPendingInputEvents()");
15628        }
15629    }
15630
15631    /**
15632     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15633     * a parent view.
15634     *
15635     * <p>This method is responsible for removing any pending high-level input events that were
15636     * posted to the event queue to run later. Custom view classes that post their own deferred
15637     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15638     * {@link android.os.Handler} should override this method, call
15639     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15640     * </p>
15641     */
15642    public void onCancelPendingInputEvents() {
15643        removePerformClickCallback();
15644        cancelLongPress();
15645        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
15646    }
15647
15648    /**
15649     * Store this view hierarchy's frozen state into the given container.
15650     *
15651     * @param container The SparseArray in which to save the view's state.
15652     *
15653     * @see #restoreHierarchyState(android.util.SparseArray)
15654     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15655     * @see #onSaveInstanceState()
15656     */
15657    public void saveHierarchyState(SparseArray<Parcelable> container) {
15658        dispatchSaveInstanceState(container);
15659    }
15660
15661    /**
15662     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
15663     * this view and its children. May be overridden to modify how freezing happens to a
15664     * view's children; for example, some views may want to not store state for their children.
15665     *
15666     * @param container The SparseArray in which to save the view's state.
15667     *
15668     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15669     * @see #saveHierarchyState(android.util.SparseArray)
15670     * @see #onSaveInstanceState()
15671     */
15672    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
15673        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
15674            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15675            Parcelable state = onSaveInstanceState();
15676            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15677                throw new IllegalStateException(
15678                        "Derived class did not call super.onSaveInstanceState()");
15679            }
15680            if (state != null) {
15681                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
15682                // + ": " + state);
15683                container.put(mID, state);
15684            }
15685        }
15686    }
15687
15688    /**
15689     * Hook allowing a view to generate a representation of its internal state
15690     * that can later be used to create a new instance with that same state.
15691     * This state should only contain information that is not persistent or can
15692     * not be reconstructed later. For example, you will never store your
15693     * current position on screen because that will be computed again when a
15694     * new instance of the view is placed in its view hierarchy.
15695     * <p>
15696     * Some examples of things you may store here: the current cursor position
15697     * in a text view (but usually not the text itself since that is stored in a
15698     * content provider or other persistent storage), the currently selected
15699     * item in a list view.
15700     *
15701     * @return Returns a Parcelable object containing the view's current dynamic
15702     *         state, or null if there is nothing interesting to save. The
15703     *         default implementation returns null.
15704     * @see #onRestoreInstanceState(android.os.Parcelable)
15705     * @see #saveHierarchyState(android.util.SparseArray)
15706     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15707     * @see #setSaveEnabled(boolean)
15708     */
15709    @CallSuper
15710    protected Parcelable onSaveInstanceState() {
15711        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15712        if (mStartActivityRequestWho != null) {
15713            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
15714            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
15715            return state;
15716        }
15717        return BaseSavedState.EMPTY_STATE;
15718    }
15719
15720    /**
15721     * Restore this view hierarchy's frozen state from the given container.
15722     *
15723     * @param container The SparseArray which holds previously frozen states.
15724     *
15725     * @see #saveHierarchyState(android.util.SparseArray)
15726     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15727     * @see #onRestoreInstanceState(android.os.Parcelable)
15728     */
15729    public void restoreHierarchyState(SparseArray<Parcelable> container) {
15730        dispatchRestoreInstanceState(container);
15731    }
15732
15733    /**
15734     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
15735     * state for this view and its children. May be overridden to modify how restoring
15736     * happens to a view's children; for example, some views may want to not store state
15737     * for their children.
15738     *
15739     * @param container The SparseArray which holds previously saved state.
15740     *
15741     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15742     * @see #restoreHierarchyState(android.util.SparseArray)
15743     * @see #onRestoreInstanceState(android.os.Parcelable)
15744     */
15745    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
15746        if (mID != NO_ID) {
15747            Parcelable state = container.get(mID);
15748            if (state != null) {
15749                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
15750                // + ": " + state);
15751                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15752                onRestoreInstanceState(state);
15753                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15754                    throw new IllegalStateException(
15755                            "Derived class did not call super.onRestoreInstanceState()");
15756                }
15757            }
15758        }
15759    }
15760
15761    /**
15762     * Hook allowing a view to re-apply a representation of its internal state that had previously
15763     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
15764     * null state.
15765     *
15766     * @param state The frozen state that had previously been returned by
15767     *        {@link #onSaveInstanceState}.
15768     *
15769     * @see #onSaveInstanceState()
15770     * @see #restoreHierarchyState(android.util.SparseArray)
15771     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15772     */
15773    @CallSuper
15774    protected void onRestoreInstanceState(Parcelable state) {
15775        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15776        if (state != null && !(state instanceof AbsSavedState)) {
15777            throw new IllegalArgumentException("Wrong state class, expecting View State but "
15778                    + "received " + state.getClass().toString() + " instead. This usually happens "
15779                    + "when two views of different type have the same id in the same hierarchy. "
15780                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
15781                    + "other views do not use the same id.");
15782        }
15783        if (state != null && state instanceof BaseSavedState) {
15784            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
15785        }
15786    }
15787
15788    /**
15789     * <p>Return the time at which the drawing of the view hierarchy started.</p>
15790     *
15791     * @return the drawing start time in milliseconds
15792     */
15793    public long getDrawingTime() {
15794        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
15795    }
15796
15797    /**
15798     * <p>Enables or disables the duplication of the parent's state into this view. When
15799     * duplication is enabled, this view gets its drawable state from its parent rather
15800     * than from its own internal properties.</p>
15801     *
15802     * <p>Note: in the current implementation, setting this property to true after the
15803     * view was added to a ViewGroup might have no effect at all. This property should
15804     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
15805     *
15806     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
15807     * property is enabled, an exception will be thrown.</p>
15808     *
15809     * <p>Note: if the child view uses and updates additional states which are unknown to the
15810     * parent, these states should not be affected by this method.</p>
15811     *
15812     * @param enabled True to enable duplication of the parent's drawable state, false
15813     *                to disable it.
15814     *
15815     * @see #getDrawableState()
15816     * @see #isDuplicateParentStateEnabled()
15817     */
15818    public void setDuplicateParentStateEnabled(boolean enabled) {
15819        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
15820    }
15821
15822    /**
15823     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
15824     *
15825     * @return True if this view's drawable state is duplicated from the parent,
15826     *         false otherwise
15827     *
15828     * @see #getDrawableState()
15829     * @see #setDuplicateParentStateEnabled(boolean)
15830     */
15831    public boolean isDuplicateParentStateEnabled() {
15832        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
15833    }
15834
15835    /**
15836     * <p>Specifies the type of layer backing this view. The layer can be
15837     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15838     * {@link #LAYER_TYPE_HARDWARE}.</p>
15839     *
15840     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15841     * instance that controls how the layer is composed on screen. The following
15842     * properties of the paint are taken into account when composing the layer:</p>
15843     * <ul>
15844     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15845     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15846     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15847     * </ul>
15848     *
15849     * <p>If this view has an alpha value set to < 1.0 by calling
15850     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
15851     * by this view's alpha value.</p>
15852     *
15853     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
15854     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
15855     * for more information on when and how to use layers.</p>
15856     *
15857     * @param layerType The type of layer to use with this view, must be one of
15858     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15859     *        {@link #LAYER_TYPE_HARDWARE}
15860     * @param paint The paint used to compose the layer. This argument is optional
15861     *        and can be null. It is ignored when the layer type is
15862     *        {@link #LAYER_TYPE_NONE}
15863     *
15864     * @see #getLayerType()
15865     * @see #LAYER_TYPE_NONE
15866     * @see #LAYER_TYPE_SOFTWARE
15867     * @see #LAYER_TYPE_HARDWARE
15868     * @see #setAlpha(float)
15869     *
15870     * @attr ref android.R.styleable#View_layerType
15871     */
15872    public void setLayerType(int layerType, @Nullable Paint paint) {
15873        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
15874            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
15875                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
15876        }
15877
15878        boolean typeChanged = mRenderNode.setLayerType(layerType);
15879
15880        if (!typeChanged) {
15881            setLayerPaint(paint);
15882            return;
15883        }
15884
15885        if (layerType != LAYER_TYPE_SOFTWARE) {
15886            // Destroy any previous software drawing cache if present
15887            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
15888            // drawing cache created in View#draw when drawing to a SW canvas.
15889            destroyDrawingCache();
15890        }
15891
15892        mLayerType = layerType;
15893        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
15894        mRenderNode.setLayerPaint(mLayerPaint);
15895
15896        // draw() behaves differently if we are on a layer, so we need to
15897        // invalidate() here
15898        invalidateParentCaches();
15899        invalidate(true);
15900    }
15901
15902    /**
15903     * Updates the {@link Paint} object used with the current layer (used only if the current
15904     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
15905     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
15906     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
15907     * ensure that the view gets redrawn immediately.
15908     *
15909     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15910     * instance that controls how the layer is composed on screen. The following
15911     * properties of the paint are taken into account when composing the layer:</p>
15912     * <ul>
15913     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15914     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15915     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15916     * </ul>
15917     *
15918     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
15919     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
15920     *
15921     * @param paint The paint used to compose the layer. This argument is optional
15922     *        and can be null. It is ignored when the layer type is
15923     *        {@link #LAYER_TYPE_NONE}
15924     *
15925     * @see #setLayerType(int, android.graphics.Paint)
15926     */
15927    public void setLayerPaint(@Nullable Paint paint) {
15928        int layerType = getLayerType();
15929        if (layerType != LAYER_TYPE_NONE) {
15930            mLayerPaint = paint;
15931            if (layerType == LAYER_TYPE_HARDWARE) {
15932                if (mRenderNode.setLayerPaint(paint)) {
15933                    invalidateViewProperty(false, false);
15934                }
15935            } else {
15936                invalidate();
15937            }
15938        }
15939    }
15940
15941    /**
15942     * Indicates what type of layer is currently associated with this view. By default
15943     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
15944     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
15945     * for more information on the different types of layers.
15946     *
15947     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15948     *         {@link #LAYER_TYPE_HARDWARE}
15949     *
15950     * @see #setLayerType(int, android.graphics.Paint)
15951     * @see #buildLayer()
15952     * @see #LAYER_TYPE_NONE
15953     * @see #LAYER_TYPE_SOFTWARE
15954     * @see #LAYER_TYPE_HARDWARE
15955     */
15956    public int getLayerType() {
15957        return mLayerType;
15958    }
15959
15960    /**
15961     * Forces this view's layer to be created and this view to be rendered
15962     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
15963     * invoking this method will have no effect.
15964     *
15965     * This method can for instance be used to render a view into its layer before
15966     * starting an animation. If this view is complex, rendering into the layer
15967     * before starting the animation will avoid skipping frames.
15968     *
15969     * @throws IllegalStateException If this view is not attached to a window
15970     *
15971     * @see #setLayerType(int, android.graphics.Paint)
15972     */
15973    public void buildLayer() {
15974        if (mLayerType == LAYER_TYPE_NONE) return;
15975
15976        final AttachInfo attachInfo = mAttachInfo;
15977        if (attachInfo == null) {
15978            throw new IllegalStateException("This view must be attached to a window first");
15979        }
15980
15981        if (getWidth() == 0 || getHeight() == 0) {
15982            return;
15983        }
15984
15985        switch (mLayerType) {
15986            case LAYER_TYPE_HARDWARE:
15987                updateDisplayListIfDirty();
15988                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
15989                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
15990                }
15991                break;
15992            case LAYER_TYPE_SOFTWARE:
15993                buildDrawingCache(true);
15994                break;
15995        }
15996    }
15997
15998    /**
15999     * Destroys all hardware rendering resources. This method is invoked
16000     * when the system needs to reclaim resources. Upon execution of this
16001     * method, you should free any OpenGL resources created by the view.
16002     *
16003     * Note: you <strong>must</strong> call
16004     * <code>super.destroyHardwareResources()</code> when overriding
16005     * this method.
16006     *
16007     * @hide
16008     */
16009    @CallSuper
16010    protected void destroyHardwareResources() {
16011        // Although the Layer will be destroyed by RenderNode, we want to release
16012        // the staging display list, which is also a signal to RenderNode that it's
16013        // safe to free its copy of the display list as it knows that we will
16014        // push an updated DisplayList if we try to draw again
16015        resetDisplayList();
16016    }
16017
16018    /**
16019     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16020     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16021     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16022     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16023     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16024     * null.</p>
16025     *
16026     * <p>Enabling the drawing cache is similar to
16027     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16028     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16029     * drawing cache has no effect on rendering because the system uses a different mechanism
16030     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16031     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16032     * for information on how to enable software and hardware layers.</p>
16033     *
16034     * <p>This API can be used to manually generate
16035     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16036     * {@link #getDrawingCache()}.</p>
16037     *
16038     * @param enabled true to enable the drawing cache, false otherwise
16039     *
16040     * @see #isDrawingCacheEnabled()
16041     * @see #getDrawingCache()
16042     * @see #buildDrawingCache()
16043     * @see #setLayerType(int, android.graphics.Paint)
16044     */
16045    public void setDrawingCacheEnabled(boolean enabled) {
16046        mCachingFailed = false;
16047        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16048    }
16049
16050    /**
16051     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16052     *
16053     * @return true if the drawing cache is enabled
16054     *
16055     * @see #setDrawingCacheEnabled(boolean)
16056     * @see #getDrawingCache()
16057     */
16058    @ViewDebug.ExportedProperty(category = "drawing")
16059    public boolean isDrawingCacheEnabled() {
16060        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16061    }
16062
16063    /**
16064     * Debugging utility which recursively outputs the dirty state of a view and its
16065     * descendants.
16066     *
16067     * @hide
16068     */
16069    @SuppressWarnings({"UnusedDeclaration"})
16070    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16071        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16072                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16073                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16074                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16075        if (clear) {
16076            mPrivateFlags &= clearMask;
16077        }
16078        if (this instanceof ViewGroup) {
16079            ViewGroup parent = (ViewGroup) this;
16080            final int count = parent.getChildCount();
16081            for (int i = 0; i < count; i++) {
16082                final View child = parent.getChildAt(i);
16083                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16084            }
16085        }
16086    }
16087
16088    /**
16089     * This method is used by ViewGroup to cause its children to restore or recreate their
16090     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16091     * to recreate its own display list, which would happen if it went through the normal
16092     * draw/dispatchDraw mechanisms.
16093     *
16094     * @hide
16095     */
16096    protected void dispatchGetDisplayList() {}
16097
16098    /**
16099     * A view that is not attached or hardware accelerated cannot create a display list.
16100     * This method checks these conditions and returns the appropriate result.
16101     *
16102     * @return true if view has the ability to create a display list, false otherwise.
16103     *
16104     * @hide
16105     */
16106    public boolean canHaveDisplayList() {
16107        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
16108    }
16109
16110    /**
16111     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
16112     * @hide
16113     */
16114    @NonNull
16115    public RenderNode updateDisplayListIfDirty() {
16116        final RenderNode renderNode = mRenderNode;
16117        if (!canHaveDisplayList()) {
16118            // can't populate RenderNode, don't try
16119            return renderNode;
16120        }
16121
16122        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16123                || !renderNode.isValid()
16124                || (mRecreateDisplayList)) {
16125            // Don't need to recreate the display list, just need to tell our
16126            // children to restore/recreate theirs
16127            if (renderNode.isValid()
16128                    && !mRecreateDisplayList) {
16129                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16130                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16131                dispatchGetDisplayList();
16132
16133                return renderNode; // no work needed
16134            }
16135
16136            // If we got here, we're recreating it. Mark it as such to ensure that
16137            // we copy in child display lists into ours in drawChild()
16138            mRecreateDisplayList = true;
16139
16140            int width = mRight - mLeft;
16141            int height = mBottom - mTop;
16142            int layerType = getLayerType();
16143
16144            final DisplayListCanvas canvas = renderNode.start(width, height);
16145            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16146
16147            try {
16148                if (layerType == LAYER_TYPE_SOFTWARE) {
16149                    buildDrawingCache(true);
16150                    Bitmap cache = getDrawingCache(true);
16151                    if (cache != null) {
16152                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16153                    }
16154                } else {
16155                    computeScroll();
16156
16157                    canvas.translate(-mScrollX, -mScrollY);
16158                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16159                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16160
16161                    // Fast path for layouts with no backgrounds
16162                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16163                        dispatchDraw(canvas);
16164                        if (mOverlay != null && !mOverlay.isEmpty()) {
16165                            mOverlay.getOverlayView().draw(canvas);
16166                        }
16167                    } else {
16168                        draw(canvas);
16169                    }
16170                }
16171            } finally {
16172                renderNode.end(canvas);
16173                setDisplayListProperties(renderNode);
16174            }
16175        } else {
16176            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16177            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16178        }
16179        return renderNode;
16180    }
16181
16182    private void resetDisplayList() {
16183        if (mRenderNode.isValid()) {
16184            mRenderNode.discardDisplayList();
16185        }
16186
16187        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16188            mBackgroundRenderNode.discardDisplayList();
16189        }
16190    }
16191
16192    /**
16193     * Called when the passed RenderNode is removed from the draw tree
16194     * @hide
16195     */
16196    public void onRenderNodeDetached(RenderNode renderNode) {
16197    }
16198
16199    /**
16200     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16201     *
16202     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16203     *
16204     * @see #getDrawingCache(boolean)
16205     */
16206    public Bitmap getDrawingCache() {
16207        return getDrawingCache(false);
16208    }
16209
16210    /**
16211     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16212     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16213     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16214     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16215     * request the drawing cache by calling this method and draw it on screen if the
16216     * returned bitmap is not null.</p>
16217     *
16218     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16219     * this method will create a bitmap of the same size as this view. Because this bitmap
16220     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16221     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16222     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16223     * size than the view. This implies that your application must be able to handle this
16224     * size.</p>
16225     *
16226     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16227     *        the current density of the screen when the application is in compatibility
16228     *        mode.
16229     *
16230     * @return A bitmap representing this view or null if cache is disabled.
16231     *
16232     * @see #setDrawingCacheEnabled(boolean)
16233     * @see #isDrawingCacheEnabled()
16234     * @see #buildDrawingCache(boolean)
16235     * @see #destroyDrawingCache()
16236     */
16237    public Bitmap getDrawingCache(boolean autoScale) {
16238        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16239            return null;
16240        }
16241        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16242            buildDrawingCache(autoScale);
16243        }
16244        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16245    }
16246
16247    /**
16248     * <p>Frees the resources used by the drawing cache. If you call
16249     * {@link #buildDrawingCache()} manually without calling
16250     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16251     * should cleanup the cache with this method afterwards.</p>
16252     *
16253     * @see #setDrawingCacheEnabled(boolean)
16254     * @see #buildDrawingCache()
16255     * @see #getDrawingCache()
16256     */
16257    public void destroyDrawingCache() {
16258        if (mDrawingCache != null) {
16259            mDrawingCache.recycle();
16260            mDrawingCache = null;
16261        }
16262        if (mUnscaledDrawingCache != null) {
16263            mUnscaledDrawingCache.recycle();
16264            mUnscaledDrawingCache = null;
16265        }
16266    }
16267
16268    /**
16269     * Setting a solid background color for the drawing cache's bitmaps will improve
16270     * performance and memory usage. Note, though that this should only be used if this
16271     * view will always be drawn on top of a solid color.
16272     *
16273     * @param color The background color to use for the drawing cache's bitmap
16274     *
16275     * @see #setDrawingCacheEnabled(boolean)
16276     * @see #buildDrawingCache()
16277     * @see #getDrawingCache()
16278     */
16279    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16280        if (color != mDrawingCacheBackgroundColor) {
16281            mDrawingCacheBackgroundColor = color;
16282            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16283        }
16284    }
16285
16286    /**
16287     * @see #setDrawingCacheBackgroundColor(int)
16288     *
16289     * @return The background color to used for the drawing cache's bitmap
16290     */
16291    @ColorInt
16292    public int getDrawingCacheBackgroundColor() {
16293        return mDrawingCacheBackgroundColor;
16294    }
16295
16296    /**
16297     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16298     *
16299     * @see #buildDrawingCache(boolean)
16300     */
16301    public void buildDrawingCache() {
16302        buildDrawingCache(false);
16303    }
16304
16305    /**
16306     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16307     *
16308     * <p>If you call {@link #buildDrawingCache()} manually without calling
16309     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16310     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16311     *
16312     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16313     * this method will create a bitmap of the same size as this view. Because this bitmap
16314     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16315     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16316     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16317     * size than the view. This implies that your application must be able to handle this
16318     * size.</p>
16319     *
16320     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16321     * you do not need the drawing cache bitmap, calling this method will increase memory
16322     * usage and cause the view to be rendered in software once, thus negatively impacting
16323     * performance.</p>
16324     *
16325     * @see #getDrawingCache()
16326     * @see #destroyDrawingCache()
16327     */
16328    public void buildDrawingCache(boolean autoScale) {
16329        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16330                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16331            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16332                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16333                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16334            }
16335            try {
16336                buildDrawingCacheImpl(autoScale);
16337            } finally {
16338                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16339            }
16340        }
16341    }
16342
16343    /**
16344     * private, internal implementation of buildDrawingCache, used to enable tracing
16345     */
16346    private void buildDrawingCacheImpl(boolean autoScale) {
16347        mCachingFailed = false;
16348
16349        int width = mRight - mLeft;
16350        int height = mBottom - mTop;
16351
16352        final AttachInfo attachInfo = mAttachInfo;
16353        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16354
16355        if (autoScale && scalingRequired) {
16356            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16357            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16358        }
16359
16360        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16361        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16362        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16363
16364        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16365        final long drawingCacheSize =
16366                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16367        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16368            if (width > 0 && height > 0) {
16369                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16370                        + " too large to fit into a software layer (or drawing cache), needs "
16371                        + projectedBitmapSize + " bytes, only "
16372                        + drawingCacheSize + " available");
16373            }
16374            destroyDrawingCache();
16375            mCachingFailed = true;
16376            return;
16377        }
16378
16379        boolean clear = true;
16380        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16381
16382        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16383            Bitmap.Config quality;
16384            if (!opaque) {
16385                // Never pick ARGB_4444 because it looks awful
16386                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16387                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16388                    case DRAWING_CACHE_QUALITY_AUTO:
16389                    case DRAWING_CACHE_QUALITY_LOW:
16390                    case DRAWING_CACHE_QUALITY_HIGH:
16391                    default:
16392                        quality = Bitmap.Config.ARGB_8888;
16393                        break;
16394                }
16395            } else {
16396                // Optimization for translucent windows
16397                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16398                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16399            }
16400
16401            // Try to cleanup memory
16402            if (bitmap != null) bitmap.recycle();
16403
16404            try {
16405                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16406                        width, height, quality);
16407                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16408                if (autoScale) {
16409                    mDrawingCache = bitmap;
16410                } else {
16411                    mUnscaledDrawingCache = bitmap;
16412                }
16413                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16414            } catch (OutOfMemoryError e) {
16415                // If there is not enough memory to create the bitmap cache, just
16416                // ignore the issue as bitmap caches are not required to draw the
16417                // view hierarchy
16418                if (autoScale) {
16419                    mDrawingCache = null;
16420                } else {
16421                    mUnscaledDrawingCache = null;
16422                }
16423                mCachingFailed = true;
16424                return;
16425            }
16426
16427            clear = drawingCacheBackgroundColor != 0;
16428        }
16429
16430        Canvas canvas;
16431        if (attachInfo != null) {
16432            canvas = attachInfo.mCanvas;
16433            if (canvas == null) {
16434                canvas = new Canvas();
16435            }
16436            canvas.setBitmap(bitmap);
16437            // Temporarily clobber the cached Canvas in case one of our children
16438            // is also using a drawing cache. Without this, the children would
16439            // steal the canvas by attaching their own bitmap to it and bad, bad
16440            // thing would happen (invisible views, corrupted drawings, etc.)
16441            attachInfo.mCanvas = null;
16442        } else {
16443            // This case should hopefully never or seldom happen
16444            canvas = new Canvas(bitmap);
16445        }
16446
16447        if (clear) {
16448            bitmap.eraseColor(drawingCacheBackgroundColor);
16449        }
16450
16451        computeScroll();
16452        final int restoreCount = canvas.save();
16453
16454        if (autoScale && scalingRequired) {
16455            final float scale = attachInfo.mApplicationScale;
16456            canvas.scale(scale, scale);
16457        }
16458
16459        canvas.translate(-mScrollX, -mScrollY);
16460
16461        mPrivateFlags |= PFLAG_DRAWN;
16462        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16463                mLayerType != LAYER_TYPE_NONE) {
16464            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16465        }
16466
16467        // Fast path for layouts with no backgrounds
16468        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16469            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16470            dispatchDraw(canvas);
16471            if (mOverlay != null && !mOverlay.isEmpty()) {
16472                mOverlay.getOverlayView().draw(canvas);
16473            }
16474        } else {
16475            draw(canvas);
16476        }
16477
16478        canvas.restoreToCount(restoreCount);
16479        canvas.setBitmap(null);
16480
16481        if (attachInfo != null) {
16482            // Restore the cached Canvas for our siblings
16483            attachInfo.mCanvas = canvas;
16484        }
16485    }
16486
16487    /**
16488     * Create a snapshot of the view into a bitmap.  We should probably make
16489     * some form of this public, but should think about the API.
16490     *
16491     * @hide
16492     */
16493    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16494        int width = mRight - mLeft;
16495        int height = mBottom - mTop;
16496
16497        final AttachInfo attachInfo = mAttachInfo;
16498        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16499        width = (int) ((width * scale) + 0.5f);
16500        height = (int) ((height * scale) + 0.5f);
16501
16502        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16503                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16504        if (bitmap == null) {
16505            throw new OutOfMemoryError();
16506        }
16507
16508        Resources resources = getResources();
16509        if (resources != null) {
16510            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16511        }
16512
16513        Canvas canvas;
16514        if (attachInfo != null) {
16515            canvas = attachInfo.mCanvas;
16516            if (canvas == null) {
16517                canvas = new Canvas();
16518            }
16519            canvas.setBitmap(bitmap);
16520            // Temporarily clobber the cached Canvas in case one of our children
16521            // is also using a drawing cache. Without this, the children would
16522            // steal the canvas by attaching their own bitmap to it and bad, bad
16523            // things would happen (invisible views, corrupted drawings, etc.)
16524            attachInfo.mCanvas = null;
16525        } else {
16526            // This case should hopefully never or seldom happen
16527            canvas = new Canvas(bitmap);
16528        }
16529
16530        if ((backgroundColor & 0xff000000) != 0) {
16531            bitmap.eraseColor(backgroundColor);
16532        }
16533
16534        computeScroll();
16535        final int restoreCount = canvas.save();
16536        canvas.scale(scale, scale);
16537        canvas.translate(-mScrollX, -mScrollY);
16538
16539        // Temporarily remove the dirty mask
16540        int flags = mPrivateFlags;
16541        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16542
16543        // Fast path for layouts with no backgrounds
16544        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16545            dispatchDraw(canvas);
16546            if (mOverlay != null && !mOverlay.isEmpty()) {
16547                mOverlay.getOverlayView().draw(canvas);
16548            }
16549        } else {
16550            draw(canvas);
16551        }
16552
16553        mPrivateFlags = flags;
16554
16555        canvas.restoreToCount(restoreCount);
16556        canvas.setBitmap(null);
16557
16558        if (attachInfo != null) {
16559            // Restore the cached Canvas for our siblings
16560            attachInfo.mCanvas = canvas;
16561        }
16562
16563        return bitmap;
16564    }
16565
16566    /**
16567     * Indicates whether this View is currently in edit mode. A View is usually
16568     * in edit mode when displayed within a developer tool. For instance, if
16569     * this View is being drawn by a visual user interface builder, this method
16570     * should return true.
16571     *
16572     * Subclasses should check the return value of this method to provide
16573     * different behaviors if their normal behavior might interfere with the
16574     * host environment. For instance: the class spawns a thread in its
16575     * constructor, the drawing code relies on device-specific features, etc.
16576     *
16577     * This method is usually checked in the drawing code of custom widgets.
16578     *
16579     * @return True if this View is in edit mode, false otherwise.
16580     */
16581    public boolean isInEditMode() {
16582        return false;
16583    }
16584
16585    /**
16586     * If the View draws content inside its padding and enables fading edges,
16587     * it needs to support padding offsets. Padding offsets are added to the
16588     * fading edges to extend the length of the fade so that it covers pixels
16589     * drawn inside the padding.
16590     *
16591     * Subclasses of this class should override this method if they need
16592     * to draw content inside the padding.
16593     *
16594     * @return True if padding offset must be applied, false otherwise.
16595     *
16596     * @see #getLeftPaddingOffset()
16597     * @see #getRightPaddingOffset()
16598     * @see #getTopPaddingOffset()
16599     * @see #getBottomPaddingOffset()
16600     *
16601     * @since CURRENT
16602     */
16603    protected boolean isPaddingOffsetRequired() {
16604        return false;
16605    }
16606
16607    /**
16608     * Amount by which to extend the left fading region. Called only when
16609     * {@link #isPaddingOffsetRequired()} returns true.
16610     *
16611     * @return The left padding offset in pixels.
16612     *
16613     * @see #isPaddingOffsetRequired()
16614     *
16615     * @since CURRENT
16616     */
16617    protected int getLeftPaddingOffset() {
16618        return 0;
16619    }
16620
16621    /**
16622     * Amount by which to extend the right fading region. Called only when
16623     * {@link #isPaddingOffsetRequired()} returns true.
16624     *
16625     * @return The right padding offset in pixels.
16626     *
16627     * @see #isPaddingOffsetRequired()
16628     *
16629     * @since CURRENT
16630     */
16631    protected int getRightPaddingOffset() {
16632        return 0;
16633    }
16634
16635    /**
16636     * Amount by which to extend the top fading region. Called only when
16637     * {@link #isPaddingOffsetRequired()} returns true.
16638     *
16639     * @return The top padding offset in pixels.
16640     *
16641     * @see #isPaddingOffsetRequired()
16642     *
16643     * @since CURRENT
16644     */
16645    protected int getTopPaddingOffset() {
16646        return 0;
16647    }
16648
16649    /**
16650     * Amount by which to extend the bottom fading region. Called only when
16651     * {@link #isPaddingOffsetRequired()} returns true.
16652     *
16653     * @return The bottom padding offset in pixels.
16654     *
16655     * @see #isPaddingOffsetRequired()
16656     *
16657     * @since CURRENT
16658     */
16659    protected int getBottomPaddingOffset() {
16660        return 0;
16661    }
16662
16663    /**
16664     * @hide
16665     * @param offsetRequired
16666     */
16667    protected int getFadeTop(boolean offsetRequired) {
16668        int top = mPaddingTop;
16669        if (offsetRequired) top += getTopPaddingOffset();
16670        return top;
16671    }
16672
16673    /**
16674     * @hide
16675     * @param offsetRequired
16676     */
16677    protected int getFadeHeight(boolean offsetRequired) {
16678        int padding = mPaddingTop;
16679        if (offsetRequired) padding += getTopPaddingOffset();
16680        return mBottom - mTop - mPaddingBottom - padding;
16681    }
16682
16683    /**
16684     * <p>Indicates whether this view is attached to a hardware accelerated
16685     * window or not.</p>
16686     *
16687     * <p>Even if this method returns true, it does not mean that every call
16688     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
16689     * accelerated {@link android.graphics.Canvas}. For instance, if this view
16690     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
16691     * window is hardware accelerated,
16692     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
16693     * return false, and this method will return true.</p>
16694     *
16695     * @return True if the view is attached to a window and the window is
16696     *         hardware accelerated; false in any other case.
16697     */
16698    @ViewDebug.ExportedProperty(category = "drawing")
16699    public boolean isHardwareAccelerated() {
16700        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
16701    }
16702
16703    /**
16704     * Sets a rectangular area on this view to which the view will be clipped
16705     * when it is drawn. Setting the value to null will remove the clip bounds
16706     * and the view will draw normally, using its full bounds.
16707     *
16708     * @param clipBounds The rectangular area, in the local coordinates of
16709     * this view, to which future drawing operations will be clipped.
16710     */
16711    public void setClipBounds(Rect clipBounds) {
16712        if (clipBounds == mClipBounds
16713                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
16714            return;
16715        }
16716        if (clipBounds != null) {
16717            if (mClipBounds == null) {
16718                mClipBounds = new Rect(clipBounds);
16719            } else {
16720                mClipBounds.set(clipBounds);
16721            }
16722        } else {
16723            mClipBounds = null;
16724        }
16725        mRenderNode.setClipBounds(mClipBounds);
16726        invalidateViewProperty(false, false);
16727    }
16728
16729    /**
16730     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
16731     *
16732     * @return A copy of the current clip bounds if clip bounds are set,
16733     * otherwise null.
16734     */
16735    public Rect getClipBounds() {
16736        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
16737    }
16738
16739
16740    /**
16741     * Populates an output rectangle with the clip bounds of the view,
16742     * returning {@code true} if successful or {@code false} if the view's
16743     * clip bounds are {@code null}.
16744     *
16745     * @param outRect rectangle in which to place the clip bounds of the view
16746     * @return {@code true} if successful or {@code false} if the view's
16747     *         clip bounds are {@code null}
16748     */
16749    public boolean getClipBounds(Rect outRect) {
16750        if (mClipBounds != null) {
16751            outRect.set(mClipBounds);
16752            return true;
16753        }
16754        return false;
16755    }
16756
16757    /**
16758     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
16759     * case of an active Animation being run on the view.
16760     */
16761    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
16762            Animation a, boolean scalingRequired) {
16763        Transformation invalidationTransform;
16764        final int flags = parent.mGroupFlags;
16765        final boolean initialized = a.isInitialized();
16766        if (!initialized) {
16767            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
16768            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
16769            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
16770            onAnimationStart();
16771        }
16772
16773        final Transformation t = parent.getChildTransformation();
16774        boolean more = a.getTransformation(drawingTime, t, 1f);
16775        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
16776            if (parent.mInvalidationTransformation == null) {
16777                parent.mInvalidationTransformation = new Transformation();
16778            }
16779            invalidationTransform = parent.mInvalidationTransformation;
16780            a.getTransformation(drawingTime, invalidationTransform, 1f);
16781        } else {
16782            invalidationTransform = t;
16783        }
16784
16785        if (more) {
16786            if (!a.willChangeBounds()) {
16787                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
16788                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
16789                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
16790                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
16791                    // The child need to draw an animation, potentially offscreen, so
16792                    // make sure we do not cancel invalidate requests
16793                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16794                    parent.invalidate(mLeft, mTop, mRight, mBottom);
16795                }
16796            } else {
16797                if (parent.mInvalidateRegion == null) {
16798                    parent.mInvalidateRegion = new RectF();
16799                }
16800                final RectF region = parent.mInvalidateRegion;
16801                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
16802                        invalidationTransform);
16803
16804                // The child need to draw an animation, potentially offscreen, so
16805                // make sure we do not cancel invalidate requests
16806                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16807
16808                final int left = mLeft + (int) region.left;
16809                final int top = mTop + (int) region.top;
16810                parent.invalidate(left, top, left + (int) (region.width() + .5f),
16811                        top + (int) (region.height() + .5f));
16812            }
16813        }
16814        return more;
16815    }
16816
16817    /**
16818     * This method is called by getDisplayList() when a display list is recorded for a View.
16819     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
16820     */
16821    void setDisplayListProperties(RenderNode renderNode) {
16822        if (renderNode != null) {
16823            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
16824            renderNode.setClipToBounds(mParent instanceof ViewGroup
16825                    && ((ViewGroup) mParent).getClipChildren());
16826
16827            float alpha = 1;
16828            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
16829                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16830                ViewGroup parentVG = (ViewGroup) mParent;
16831                final Transformation t = parentVG.getChildTransformation();
16832                if (parentVG.getChildStaticTransformation(this, t)) {
16833                    final int transformType = t.getTransformationType();
16834                    if (transformType != Transformation.TYPE_IDENTITY) {
16835                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
16836                            alpha = t.getAlpha();
16837                        }
16838                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
16839                            renderNode.setStaticMatrix(t.getMatrix());
16840                        }
16841                    }
16842                }
16843            }
16844            if (mTransformationInfo != null) {
16845                alpha *= getFinalAlpha();
16846                if (alpha < 1) {
16847                    final int multipliedAlpha = (int) (255 * alpha);
16848                    if (onSetAlpha(multipliedAlpha)) {
16849                        alpha = 1;
16850                    }
16851                }
16852                renderNode.setAlpha(alpha);
16853            } else if (alpha < 1) {
16854                renderNode.setAlpha(alpha);
16855            }
16856        }
16857    }
16858
16859    /**
16860     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
16861     *
16862     * This is where the View specializes rendering behavior based on layer type,
16863     * and hardware acceleration.
16864     */
16865    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
16866        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
16867        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
16868         *
16869         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
16870         * HW accelerated, it can't handle drawing RenderNodes.
16871         */
16872        boolean drawingWithRenderNode = mAttachInfo != null
16873                && mAttachInfo.mHardwareAccelerated
16874                && hardwareAcceleratedCanvas;
16875
16876        boolean more = false;
16877        final boolean childHasIdentityMatrix = hasIdentityMatrix();
16878        final int parentFlags = parent.mGroupFlags;
16879
16880        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
16881            parent.getChildTransformation().clear();
16882            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16883        }
16884
16885        Transformation transformToApply = null;
16886        boolean concatMatrix = false;
16887        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
16888        final Animation a = getAnimation();
16889        if (a != null) {
16890            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
16891            concatMatrix = a.willChangeTransformationMatrix();
16892            if (concatMatrix) {
16893                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16894            }
16895            transformToApply = parent.getChildTransformation();
16896        } else {
16897            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
16898                // No longer animating: clear out old animation matrix
16899                mRenderNode.setAnimationMatrix(null);
16900                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16901            }
16902            if (!drawingWithRenderNode
16903                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16904                final Transformation t = parent.getChildTransformation();
16905                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
16906                if (hasTransform) {
16907                    final int transformType = t.getTransformationType();
16908                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
16909                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
16910                }
16911            }
16912        }
16913
16914        concatMatrix |= !childHasIdentityMatrix;
16915
16916        // Sets the flag as early as possible to allow draw() implementations
16917        // to call invalidate() successfully when doing animations
16918        mPrivateFlags |= PFLAG_DRAWN;
16919
16920        if (!concatMatrix &&
16921                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
16922                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
16923                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
16924                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
16925            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
16926            return more;
16927        }
16928        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
16929
16930        if (hardwareAcceleratedCanvas) {
16931            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
16932            // retain the flag's value temporarily in the mRecreateDisplayList flag
16933            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
16934            mPrivateFlags &= ~PFLAG_INVALIDATED;
16935        }
16936
16937        RenderNode renderNode = null;
16938        Bitmap cache = null;
16939        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
16940        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
16941             if (layerType != LAYER_TYPE_NONE) {
16942                 // If not drawing with RenderNode, treat HW layers as SW
16943                 layerType = LAYER_TYPE_SOFTWARE;
16944                 buildDrawingCache(true);
16945            }
16946            cache = getDrawingCache(true);
16947        }
16948
16949        if (drawingWithRenderNode) {
16950            // Delay getting the display list until animation-driven alpha values are
16951            // set up and possibly passed on to the view
16952            renderNode = updateDisplayListIfDirty();
16953            if (!renderNode.isValid()) {
16954                // Uncommon, but possible. If a view is removed from the hierarchy during the call
16955                // to getDisplayList(), the display list will be marked invalid and we should not
16956                // try to use it again.
16957                renderNode = null;
16958                drawingWithRenderNode = false;
16959            }
16960        }
16961
16962        int sx = 0;
16963        int sy = 0;
16964        if (!drawingWithRenderNode) {
16965            computeScroll();
16966            sx = mScrollX;
16967            sy = mScrollY;
16968        }
16969
16970        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
16971        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
16972
16973        int restoreTo = -1;
16974        if (!drawingWithRenderNode || transformToApply != null) {
16975            restoreTo = canvas.save();
16976        }
16977        if (offsetForScroll) {
16978            canvas.translate(mLeft - sx, mTop - sy);
16979        } else {
16980            if (!drawingWithRenderNode) {
16981                canvas.translate(mLeft, mTop);
16982            }
16983            if (scalingRequired) {
16984                if (drawingWithRenderNode) {
16985                    // TODO: Might not need this if we put everything inside the DL
16986                    restoreTo = canvas.save();
16987                }
16988                // mAttachInfo cannot be null, otherwise scalingRequired == false
16989                final float scale = 1.0f / mAttachInfo.mApplicationScale;
16990                canvas.scale(scale, scale);
16991            }
16992        }
16993
16994        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
16995        if (transformToApply != null
16996                || alpha < 1
16997                || !hasIdentityMatrix()
16998                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16999            if (transformToApply != null || !childHasIdentityMatrix) {
17000                int transX = 0;
17001                int transY = 0;
17002
17003                if (offsetForScroll) {
17004                    transX = -sx;
17005                    transY = -sy;
17006                }
17007
17008                if (transformToApply != null) {
17009                    if (concatMatrix) {
17010                        if (drawingWithRenderNode) {
17011                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17012                        } else {
17013                            // Undo the scroll translation, apply the transformation matrix,
17014                            // then redo the scroll translate to get the correct result.
17015                            canvas.translate(-transX, -transY);
17016                            canvas.concat(transformToApply.getMatrix());
17017                            canvas.translate(transX, transY);
17018                        }
17019                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17020                    }
17021
17022                    float transformAlpha = transformToApply.getAlpha();
17023                    if (transformAlpha < 1) {
17024                        alpha *= transformAlpha;
17025                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17026                    }
17027                }
17028
17029                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17030                    canvas.translate(-transX, -transY);
17031                    canvas.concat(getMatrix());
17032                    canvas.translate(transX, transY);
17033                }
17034            }
17035
17036            // Deal with alpha if it is or used to be <1
17037            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17038                if (alpha < 1) {
17039                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17040                } else {
17041                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17042                }
17043                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17044                if (!drawingWithDrawingCache) {
17045                    final int multipliedAlpha = (int) (255 * alpha);
17046                    if (!onSetAlpha(multipliedAlpha)) {
17047                        if (drawingWithRenderNode) {
17048                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17049                        } else if (layerType == LAYER_TYPE_NONE) {
17050                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17051                                    multipliedAlpha);
17052                        }
17053                    } else {
17054                        // Alpha is handled by the child directly, clobber the layer's alpha
17055                        mPrivateFlags |= PFLAG_ALPHA_SET;
17056                    }
17057                }
17058            }
17059        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17060            onSetAlpha(255);
17061            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17062        }
17063
17064        if (!drawingWithRenderNode) {
17065            // apply clips directly, since RenderNode won't do it for this draw
17066            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17067                if (offsetForScroll) {
17068                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17069                } else {
17070                    if (!scalingRequired || cache == null) {
17071                        canvas.clipRect(0, 0, getWidth(), getHeight());
17072                    } else {
17073                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17074                    }
17075                }
17076            }
17077
17078            if (mClipBounds != null) {
17079                // clip bounds ignore scroll
17080                canvas.clipRect(mClipBounds);
17081            }
17082        }
17083
17084        if (!drawingWithDrawingCache) {
17085            if (drawingWithRenderNode) {
17086                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17087                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17088            } else {
17089                // Fast path for layouts with no backgrounds
17090                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17091                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17092                    dispatchDraw(canvas);
17093                } else {
17094                    draw(canvas);
17095                }
17096            }
17097        } else if (cache != null) {
17098            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17099            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17100                // no layer paint, use temporary paint to draw bitmap
17101                Paint cachePaint = parent.mCachePaint;
17102                if (cachePaint == null) {
17103                    cachePaint = new Paint();
17104                    cachePaint.setDither(false);
17105                    parent.mCachePaint = cachePaint;
17106                }
17107                cachePaint.setAlpha((int) (alpha * 255));
17108                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17109            } else {
17110                // use layer paint to draw the bitmap, merging the two alphas, but also restore
17111                int layerPaintAlpha = mLayerPaint.getAlpha();
17112                if (alpha < 1) {
17113                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17114                }
17115                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17116                if (alpha < 1) {
17117                    mLayerPaint.setAlpha(layerPaintAlpha);
17118                }
17119            }
17120        }
17121
17122        if (restoreTo >= 0) {
17123            canvas.restoreToCount(restoreTo);
17124        }
17125
17126        if (a != null && !more) {
17127            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17128                onSetAlpha(255);
17129            }
17130            parent.finishAnimatingView(this, a);
17131        }
17132
17133        if (more && hardwareAcceleratedCanvas) {
17134            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17135                // alpha animations should cause the child to recreate its display list
17136                invalidate(true);
17137            }
17138        }
17139
17140        mRecreateDisplayList = false;
17141
17142        return more;
17143    }
17144
17145    /**
17146     * Manually render this view (and all of its children) to the given Canvas.
17147     * The view must have already done a full layout before this function is
17148     * called.  When implementing a view, implement
17149     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17150     * If you do need to override this method, call the superclass version.
17151     *
17152     * @param canvas The Canvas to which the View is rendered.
17153     */
17154    @CallSuper
17155    public void draw(Canvas canvas) {
17156        final int privateFlags = mPrivateFlags;
17157        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17158                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17159        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17160
17161        /*
17162         * Draw traversal performs several drawing steps which must be executed
17163         * in the appropriate order:
17164         *
17165         *      1. Draw the background
17166         *      2. If necessary, save the canvas' layers to prepare for fading
17167         *      3. Draw view's content
17168         *      4. Draw children
17169         *      5. If necessary, draw the fading edges and restore layers
17170         *      6. Draw decorations (scrollbars for instance)
17171         */
17172
17173        // Step 1, draw the background, if needed
17174        int saveCount;
17175
17176        if (!dirtyOpaque) {
17177            drawBackground(canvas);
17178        }
17179
17180        // skip step 2 & 5 if possible (common case)
17181        final int viewFlags = mViewFlags;
17182        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17183        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17184        if (!verticalEdges && !horizontalEdges) {
17185            // Step 3, draw the content
17186            if (!dirtyOpaque) onDraw(canvas);
17187
17188            // Step 4, draw the children
17189            dispatchDraw(canvas);
17190
17191            // Overlay is part of the content and draws beneath Foreground
17192            if (mOverlay != null && !mOverlay.isEmpty()) {
17193                mOverlay.getOverlayView().dispatchDraw(canvas);
17194            }
17195
17196            // Step 6, draw decorations (foreground, scrollbars)
17197            onDrawForeground(canvas);
17198
17199            // we're done...
17200            return;
17201        }
17202
17203        /*
17204         * Here we do the full fledged routine...
17205         * (this is an uncommon case where speed matters less,
17206         * this is why we repeat some of the tests that have been
17207         * done above)
17208         */
17209
17210        boolean drawTop = false;
17211        boolean drawBottom = false;
17212        boolean drawLeft = false;
17213        boolean drawRight = false;
17214
17215        float topFadeStrength = 0.0f;
17216        float bottomFadeStrength = 0.0f;
17217        float leftFadeStrength = 0.0f;
17218        float rightFadeStrength = 0.0f;
17219
17220        // Step 2, save the canvas' layers
17221        int paddingLeft = mPaddingLeft;
17222
17223        final boolean offsetRequired = isPaddingOffsetRequired();
17224        if (offsetRequired) {
17225            paddingLeft += getLeftPaddingOffset();
17226        }
17227
17228        int left = mScrollX + paddingLeft;
17229        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17230        int top = mScrollY + getFadeTop(offsetRequired);
17231        int bottom = top + getFadeHeight(offsetRequired);
17232
17233        if (offsetRequired) {
17234            right += getRightPaddingOffset();
17235            bottom += getBottomPaddingOffset();
17236        }
17237
17238        final ScrollabilityCache scrollabilityCache = mScrollCache;
17239        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17240        int length = (int) fadeHeight;
17241
17242        // clip the fade length if top and bottom fades overlap
17243        // overlapping fades produce odd-looking artifacts
17244        if (verticalEdges && (top + length > bottom - length)) {
17245            length = (bottom - top) / 2;
17246        }
17247
17248        // also clip horizontal fades if necessary
17249        if (horizontalEdges && (left + length > right - length)) {
17250            length = (right - left) / 2;
17251        }
17252
17253        if (verticalEdges) {
17254            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17255            drawTop = topFadeStrength * fadeHeight > 1.0f;
17256            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17257            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17258        }
17259
17260        if (horizontalEdges) {
17261            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17262            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17263            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17264            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17265        }
17266
17267        saveCount = canvas.getSaveCount();
17268
17269        int solidColor = getSolidColor();
17270        if (solidColor == 0) {
17271            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17272
17273            if (drawTop) {
17274                canvas.saveLayer(left, top, right, top + length, null, flags);
17275            }
17276
17277            if (drawBottom) {
17278                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17279            }
17280
17281            if (drawLeft) {
17282                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17283            }
17284
17285            if (drawRight) {
17286                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17287            }
17288        } else {
17289            scrollabilityCache.setFadeColor(solidColor);
17290        }
17291
17292        // Step 3, draw the content
17293        if (!dirtyOpaque) onDraw(canvas);
17294
17295        // Step 4, draw the children
17296        dispatchDraw(canvas);
17297
17298        // Step 5, draw the fade effect and restore layers
17299        final Paint p = scrollabilityCache.paint;
17300        final Matrix matrix = scrollabilityCache.matrix;
17301        final Shader fade = scrollabilityCache.shader;
17302
17303        if (drawTop) {
17304            matrix.setScale(1, fadeHeight * topFadeStrength);
17305            matrix.postTranslate(left, top);
17306            fade.setLocalMatrix(matrix);
17307            p.setShader(fade);
17308            canvas.drawRect(left, top, right, top + length, p);
17309        }
17310
17311        if (drawBottom) {
17312            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17313            matrix.postRotate(180);
17314            matrix.postTranslate(left, bottom);
17315            fade.setLocalMatrix(matrix);
17316            p.setShader(fade);
17317            canvas.drawRect(left, bottom - length, right, bottom, p);
17318        }
17319
17320        if (drawLeft) {
17321            matrix.setScale(1, fadeHeight * leftFadeStrength);
17322            matrix.postRotate(-90);
17323            matrix.postTranslate(left, top);
17324            fade.setLocalMatrix(matrix);
17325            p.setShader(fade);
17326            canvas.drawRect(left, top, left + length, bottom, p);
17327        }
17328
17329        if (drawRight) {
17330            matrix.setScale(1, fadeHeight * rightFadeStrength);
17331            matrix.postRotate(90);
17332            matrix.postTranslate(right, top);
17333            fade.setLocalMatrix(matrix);
17334            p.setShader(fade);
17335            canvas.drawRect(right - length, top, right, bottom, p);
17336        }
17337
17338        canvas.restoreToCount(saveCount);
17339
17340        // Overlay is part of the content and draws beneath Foreground
17341        if (mOverlay != null && !mOverlay.isEmpty()) {
17342            mOverlay.getOverlayView().dispatchDraw(canvas);
17343        }
17344
17345        // Step 6, draw decorations (foreground, scrollbars)
17346        onDrawForeground(canvas);
17347    }
17348
17349    /**
17350     * Draws the background onto the specified canvas.
17351     *
17352     * @param canvas Canvas on which to draw the background
17353     */
17354    private void drawBackground(Canvas canvas) {
17355        final Drawable background = mBackground;
17356        if (background == null) {
17357            return;
17358        }
17359
17360        setBackgroundBounds();
17361
17362        // Attempt to use a display list if requested.
17363        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17364                && mAttachInfo.mHardwareRenderer != null) {
17365            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17366
17367            final RenderNode renderNode = mBackgroundRenderNode;
17368            if (renderNode != null && renderNode.isValid()) {
17369                setBackgroundRenderNodeProperties(renderNode);
17370                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17371                return;
17372            }
17373        }
17374
17375        final int scrollX = mScrollX;
17376        final int scrollY = mScrollY;
17377        if ((scrollX | scrollY) == 0) {
17378            background.draw(canvas);
17379        } else {
17380            canvas.translate(scrollX, scrollY);
17381            background.draw(canvas);
17382            canvas.translate(-scrollX, -scrollY);
17383        }
17384    }
17385
17386    /**
17387     * Sets the correct background bounds and rebuilds the outline, if needed.
17388     * <p/>
17389     * This is called by LayoutLib.
17390     */
17391    void setBackgroundBounds() {
17392        if (mBackgroundSizeChanged && mBackground != null) {
17393            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17394            mBackgroundSizeChanged = false;
17395            rebuildOutline();
17396        }
17397    }
17398
17399    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17400        renderNode.setTranslationX(mScrollX);
17401        renderNode.setTranslationY(mScrollY);
17402    }
17403
17404    /**
17405     * Creates a new display list or updates the existing display list for the
17406     * specified Drawable.
17407     *
17408     * @param drawable Drawable for which to create a display list
17409     * @param renderNode Existing RenderNode, or {@code null}
17410     * @return A valid display list for the specified drawable
17411     */
17412    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17413        if (renderNode == null) {
17414            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17415        }
17416
17417        final Rect bounds = drawable.getBounds();
17418        final int width = bounds.width();
17419        final int height = bounds.height();
17420        final DisplayListCanvas canvas = renderNode.start(width, height);
17421
17422        // Reverse left/top translation done by drawable canvas, which will
17423        // instead be applied by rendernode's LTRB bounds below. This way, the
17424        // drawable's bounds match with its rendernode bounds and its content
17425        // will lie within those bounds in the rendernode tree.
17426        canvas.translate(-bounds.left, -bounds.top);
17427
17428        try {
17429            drawable.draw(canvas);
17430        } finally {
17431            renderNode.end(canvas);
17432        }
17433
17434        // Set up drawable properties that are view-independent.
17435        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17436        renderNode.setProjectBackwards(drawable.isProjected());
17437        renderNode.setProjectionReceiver(true);
17438        renderNode.setClipToBounds(false);
17439        return renderNode;
17440    }
17441
17442    /**
17443     * Returns the overlay for this view, creating it if it does not yet exist.
17444     * Adding drawables to the overlay will cause them to be displayed whenever
17445     * the view itself is redrawn. Objects in the overlay should be actively
17446     * managed: remove them when they should not be displayed anymore. The
17447     * overlay will always have the same size as its host view.
17448     *
17449     * <p>Note: Overlays do not currently work correctly with {@link
17450     * SurfaceView} or {@link TextureView}; contents in overlays for these
17451     * types of views may not display correctly.</p>
17452     *
17453     * @return The ViewOverlay object for this view.
17454     * @see ViewOverlay
17455     */
17456    public ViewOverlay getOverlay() {
17457        if (mOverlay == null) {
17458            mOverlay = new ViewOverlay(mContext, this);
17459        }
17460        return mOverlay;
17461    }
17462
17463    /**
17464     * Override this if your view is known to always be drawn on top of a solid color background,
17465     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17466     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17467     * should be set to 0xFF.
17468     *
17469     * @see #setVerticalFadingEdgeEnabled(boolean)
17470     * @see #setHorizontalFadingEdgeEnabled(boolean)
17471     *
17472     * @return The known solid color background for this view, or 0 if the color may vary
17473     */
17474    @ViewDebug.ExportedProperty(category = "drawing")
17475    @ColorInt
17476    public int getSolidColor() {
17477        return 0;
17478    }
17479
17480    /**
17481     * Build a human readable string representation of the specified view flags.
17482     *
17483     * @param flags the view flags to convert to a string
17484     * @return a String representing the supplied flags
17485     */
17486    private static String printFlags(int flags) {
17487        String output = "";
17488        int numFlags = 0;
17489        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17490            output += "TAKES_FOCUS";
17491            numFlags++;
17492        }
17493
17494        switch (flags & VISIBILITY_MASK) {
17495        case INVISIBLE:
17496            if (numFlags > 0) {
17497                output += " ";
17498            }
17499            output += "INVISIBLE";
17500            // USELESS HERE numFlags++;
17501            break;
17502        case GONE:
17503            if (numFlags > 0) {
17504                output += " ";
17505            }
17506            output += "GONE";
17507            // USELESS HERE numFlags++;
17508            break;
17509        default:
17510            break;
17511        }
17512        return output;
17513    }
17514
17515    /**
17516     * Build a human readable string representation of the specified private
17517     * view flags.
17518     *
17519     * @param privateFlags the private view flags to convert to a string
17520     * @return a String representing the supplied flags
17521     */
17522    private static String printPrivateFlags(int privateFlags) {
17523        String output = "";
17524        int numFlags = 0;
17525
17526        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17527            output += "WANTS_FOCUS";
17528            numFlags++;
17529        }
17530
17531        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17532            if (numFlags > 0) {
17533                output += " ";
17534            }
17535            output += "FOCUSED";
17536            numFlags++;
17537        }
17538
17539        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17540            if (numFlags > 0) {
17541                output += " ";
17542            }
17543            output += "SELECTED";
17544            numFlags++;
17545        }
17546
17547        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17548            if (numFlags > 0) {
17549                output += " ";
17550            }
17551            output += "IS_ROOT_NAMESPACE";
17552            numFlags++;
17553        }
17554
17555        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17556            if (numFlags > 0) {
17557                output += " ";
17558            }
17559            output += "HAS_BOUNDS";
17560            numFlags++;
17561        }
17562
17563        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17564            if (numFlags > 0) {
17565                output += " ";
17566            }
17567            output += "DRAWN";
17568            // USELESS HERE numFlags++;
17569        }
17570        return output;
17571    }
17572
17573    /**
17574     * <p>Indicates whether or not this view's layout will be requested during
17575     * the next hierarchy layout pass.</p>
17576     *
17577     * @return true if the layout will be forced during next layout pass
17578     */
17579    public boolean isLayoutRequested() {
17580        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17581    }
17582
17583    /**
17584     * Return true if o is a ViewGroup that is laying out using optical bounds.
17585     * @hide
17586     */
17587    public static boolean isLayoutModeOptical(Object o) {
17588        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17589    }
17590
17591    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17592        Insets parentInsets = mParent instanceof View ?
17593                ((View) mParent).getOpticalInsets() : Insets.NONE;
17594        Insets childInsets = getOpticalInsets();
17595        return setFrame(
17596                left   + parentInsets.left - childInsets.left,
17597                top    + parentInsets.top  - childInsets.top,
17598                right  + parentInsets.left + childInsets.right,
17599                bottom + parentInsets.top  + childInsets.bottom);
17600    }
17601
17602    /**
17603     * Assign a size and position to a view and all of its
17604     * descendants
17605     *
17606     * <p>This is the second phase of the layout mechanism.
17607     * (The first is measuring). In this phase, each parent calls
17608     * layout on all of its children to position them.
17609     * This is typically done using the child measurements
17610     * that were stored in the measure pass().</p>
17611     *
17612     * <p>Derived classes should not override this method.
17613     * Derived classes with children should override
17614     * onLayout. In that method, they should
17615     * call layout on each of their children.</p>
17616     *
17617     * @param l Left position, relative to parent
17618     * @param t Top position, relative to parent
17619     * @param r Right position, relative to parent
17620     * @param b Bottom position, relative to parent
17621     */
17622    @SuppressWarnings({"unchecked"})
17623    public void layout(int l, int t, int r, int b) {
17624        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
17625            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
17626            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17627        }
17628
17629        int oldL = mLeft;
17630        int oldT = mTop;
17631        int oldB = mBottom;
17632        int oldR = mRight;
17633
17634        boolean changed = isLayoutModeOptical(mParent) ?
17635                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
17636
17637        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17638            onLayout(changed, l, t, r, b);
17639
17640            if (shouldDrawRoundScrollbar()) {
17641                if(mRoundScrollbarRenderer == null) {
17642                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
17643                }
17644            } else {
17645                mRoundScrollbarRenderer = null;
17646            }
17647
17648            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
17649
17650            ListenerInfo li = mListenerInfo;
17651            if (li != null && li.mOnLayoutChangeListeners != null) {
17652                ArrayList<OnLayoutChangeListener> listenersCopy =
17653                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
17654                int numListeners = listenersCopy.size();
17655                for (int i = 0; i < numListeners; ++i) {
17656                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
17657                }
17658            }
17659        }
17660
17661        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
17662        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
17663    }
17664
17665    /**
17666     * Called from layout when this view should
17667     * assign a size and position to each of its children.
17668     *
17669     * Derived classes with children should override
17670     * this method and call layout on each of
17671     * their children.
17672     * @param changed This is a new size or position for this view
17673     * @param left Left position, relative to parent
17674     * @param top Top position, relative to parent
17675     * @param right Right position, relative to parent
17676     * @param bottom Bottom position, relative to parent
17677     */
17678    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
17679    }
17680
17681    /**
17682     * Assign a size and position to this view.
17683     *
17684     * This is called from layout.
17685     *
17686     * @param left Left position, relative to parent
17687     * @param top Top position, relative to parent
17688     * @param right Right position, relative to parent
17689     * @param bottom Bottom position, relative to parent
17690     * @return true if the new size and position are different than the
17691     *         previous ones
17692     * {@hide}
17693     */
17694    protected boolean setFrame(int left, int top, int right, int bottom) {
17695        boolean changed = false;
17696
17697        if (DBG) {
17698            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
17699                    + right + "," + bottom + ")");
17700        }
17701
17702        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
17703            changed = true;
17704
17705            // Remember our drawn bit
17706            int drawn = mPrivateFlags & PFLAG_DRAWN;
17707
17708            int oldWidth = mRight - mLeft;
17709            int oldHeight = mBottom - mTop;
17710            int newWidth = right - left;
17711            int newHeight = bottom - top;
17712            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
17713
17714            // Invalidate our old position
17715            invalidate(sizeChanged);
17716
17717            mLeft = left;
17718            mTop = top;
17719            mRight = right;
17720            mBottom = bottom;
17721            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
17722
17723            mPrivateFlags |= PFLAG_HAS_BOUNDS;
17724
17725
17726            if (sizeChanged) {
17727                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
17728            }
17729
17730            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
17731                // If we are visible, force the DRAWN bit to on so that
17732                // this invalidate will go through (at least to our parent).
17733                // This is because someone may have invalidated this view
17734                // before this call to setFrame came in, thereby clearing
17735                // the DRAWN bit.
17736                mPrivateFlags |= PFLAG_DRAWN;
17737                invalidate(sizeChanged);
17738                // parent display list may need to be recreated based on a change in the bounds
17739                // of any child
17740                invalidateParentCaches();
17741            }
17742
17743            // Reset drawn bit to original value (invalidate turns it off)
17744            mPrivateFlags |= drawn;
17745
17746            mBackgroundSizeChanged = true;
17747            if (mForegroundInfo != null) {
17748                mForegroundInfo.mBoundsChanged = true;
17749            }
17750
17751            notifySubtreeAccessibilityStateChangedIfNeeded();
17752        }
17753        return changed;
17754    }
17755
17756    /**
17757     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
17758     * @hide
17759     */
17760    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
17761        setFrame(left, top, right, bottom);
17762    }
17763
17764    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
17765        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
17766        if (mOverlay != null) {
17767            mOverlay.getOverlayView().setRight(newWidth);
17768            mOverlay.getOverlayView().setBottom(newHeight);
17769        }
17770        rebuildOutline();
17771    }
17772
17773    /**
17774     * Finalize inflating a view from XML.  This is called as the last phase
17775     * of inflation, after all child views have been added.
17776     *
17777     * <p>Even if the subclass overrides onFinishInflate, they should always be
17778     * sure to call the super method, so that we get called.
17779     */
17780    @CallSuper
17781    protected void onFinishInflate() {
17782    }
17783
17784    /**
17785     * Returns the resources associated with this view.
17786     *
17787     * @return Resources object.
17788     */
17789    public Resources getResources() {
17790        return mResources;
17791    }
17792
17793    /**
17794     * Invalidates the specified Drawable.
17795     *
17796     * @param drawable the drawable to invalidate
17797     */
17798    @Override
17799    public void invalidateDrawable(@NonNull Drawable drawable) {
17800        if (verifyDrawable(drawable)) {
17801            final Rect dirty = drawable.getDirtyBounds();
17802            final int scrollX = mScrollX;
17803            final int scrollY = mScrollY;
17804
17805            invalidate(dirty.left + scrollX, dirty.top + scrollY,
17806                    dirty.right + scrollX, dirty.bottom + scrollY);
17807            rebuildOutline();
17808        }
17809    }
17810
17811    /**
17812     * Schedules an action on a drawable to occur at a specified time.
17813     *
17814     * @param who the recipient of the action
17815     * @param what the action to run on the drawable
17816     * @param when the time at which the action must occur. Uses the
17817     *        {@link SystemClock#uptimeMillis} timebase.
17818     */
17819    @Override
17820    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
17821        if (verifyDrawable(who) && what != null) {
17822            final long delay = when - SystemClock.uptimeMillis();
17823            if (mAttachInfo != null) {
17824                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
17825                        Choreographer.CALLBACK_ANIMATION, what, who,
17826                        Choreographer.subtractFrameDelay(delay));
17827            } else {
17828                // Postpone the runnable until we know
17829                // on which thread it needs to run.
17830                getRunQueue().postDelayed(what, delay);
17831            }
17832        }
17833    }
17834
17835    /**
17836     * Cancels a scheduled action on a drawable.
17837     *
17838     * @param who the recipient of the action
17839     * @param what the action to cancel
17840     */
17841    @Override
17842    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
17843        if (verifyDrawable(who) && what != null) {
17844            if (mAttachInfo != null) {
17845                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17846                        Choreographer.CALLBACK_ANIMATION, what, who);
17847            }
17848            getRunQueue().removeCallbacks(what);
17849        }
17850    }
17851
17852    /**
17853     * Unschedule any events associated with the given Drawable.  This can be
17854     * used when selecting a new Drawable into a view, so that the previous
17855     * one is completely unscheduled.
17856     *
17857     * @param who The Drawable to unschedule.
17858     *
17859     * @see #drawableStateChanged
17860     */
17861    public void unscheduleDrawable(Drawable who) {
17862        if (mAttachInfo != null && who != null) {
17863            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17864                    Choreographer.CALLBACK_ANIMATION, null, who);
17865        }
17866    }
17867
17868    /**
17869     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
17870     * that the View directionality can and will be resolved before its Drawables.
17871     *
17872     * Will call {@link View#onResolveDrawables} when resolution is done.
17873     *
17874     * @hide
17875     */
17876    protected void resolveDrawables() {
17877        // Drawables resolution may need to happen before resolving the layout direction (which is
17878        // done only during the measure() call).
17879        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
17880        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
17881        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
17882        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
17883        // direction to be resolved as its resolved value will be the same as its raw value.
17884        if (!isLayoutDirectionResolved() &&
17885                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
17886            return;
17887        }
17888
17889        final int layoutDirection = isLayoutDirectionResolved() ?
17890                getLayoutDirection() : getRawLayoutDirection();
17891
17892        if (mBackground != null) {
17893            mBackground.setLayoutDirection(layoutDirection);
17894        }
17895        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17896            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
17897        }
17898        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
17899        onResolveDrawables(layoutDirection);
17900    }
17901
17902    boolean areDrawablesResolved() {
17903        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
17904    }
17905
17906    /**
17907     * Called when layout direction has been resolved.
17908     *
17909     * The default implementation does nothing.
17910     *
17911     * @param layoutDirection The resolved layout direction.
17912     *
17913     * @see #LAYOUT_DIRECTION_LTR
17914     * @see #LAYOUT_DIRECTION_RTL
17915     *
17916     * @hide
17917     */
17918    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
17919    }
17920
17921    /**
17922     * @hide
17923     */
17924    protected void resetResolvedDrawables() {
17925        resetResolvedDrawablesInternal();
17926    }
17927
17928    void resetResolvedDrawablesInternal() {
17929        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
17930    }
17931
17932    /**
17933     * If your view subclass is displaying its own Drawable objects, it should
17934     * override this function and return true for any Drawable it is
17935     * displaying.  This allows animations for those drawables to be
17936     * scheduled.
17937     *
17938     * <p>Be sure to call through to the super class when overriding this
17939     * function.
17940     *
17941     * @param who The Drawable to verify.  Return true if it is one you are
17942     *            displaying, else return the result of calling through to the
17943     *            super class.
17944     *
17945     * @return boolean If true than the Drawable is being displayed in the
17946     *         view; else false and it is not allowed to animate.
17947     *
17948     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
17949     * @see #drawableStateChanged()
17950     */
17951    @CallSuper
17952    protected boolean verifyDrawable(@NonNull Drawable who) {
17953        // Avoid verifying the scroll bar drawable so that we don't end up in
17954        // an invalidation loop. This effectively prevents the scroll bar
17955        // drawable from triggering invalidations and scheduling runnables.
17956        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
17957    }
17958
17959    /**
17960     * This function is called whenever the state of the view changes in such
17961     * a way that it impacts the state of drawables being shown.
17962     * <p>
17963     * If the View has a StateListAnimator, it will also be called to run necessary state
17964     * change animations.
17965     * <p>
17966     * Be sure to call through to the superclass when overriding this function.
17967     *
17968     * @see Drawable#setState(int[])
17969     */
17970    @CallSuper
17971    protected void drawableStateChanged() {
17972        final int[] state = getDrawableState();
17973        boolean changed = false;
17974
17975        final Drawable bg = mBackground;
17976        if (bg != null && bg.isStateful()) {
17977            changed |= bg.setState(state);
17978        }
17979
17980        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17981        if (fg != null && fg.isStateful()) {
17982            changed |= fg.setState(state);
17983        }
17984
17985        if (mScrollCache != null) {
17986            final Drawable scrollBar = mScrollCache.scrollBar;
17987            if (scrollBar != null && scrollBar.isStateful()) {
17988                changed |= scrollBar.setState(state)
17989                        && mScrollCache.state != ScrollabilityCache.OFF;
17990            }
17991        }
17992
17993        if (mStateListAnimator != null) {
17994            mStateListAnimator.setState(state);
17995        }
17996
17997        if (changed) {
17998            invalidate();
17999        }
18000    }
18001
18002    /**
18003     * This function is called whenever the view hotspot changes and needs to
18004     * be propagated to drawables or child views managed by the view.
18005     * <p>
18006     * Dispatching to child views is handled by
18007     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18008     * <p>
18009     * Be sure to call through to the superclass when overriding this function.
18010     *
18011     * @param x hotspot x coordinate
18012     * @param y hotspot y coordinate
18013     */
18014    @CallSuper
18015    public void drawableHotspotChanged(float x, float y) {
18016        if (mBackground != null) {
18017            mBackground.setHotspot(x, y);
18018        }
18019        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18020            mForegroundInfo.mDrawable.setHotspot(x, y);
18021        }
18022
18023        dispatchDrawableHotspotChanged(x, y);
18024    }
18025
18026    /**
18027     * Dispatches drawableHotspotChanged to all of this View's children.
18028     *
18029     * @param x hotspot x coordinate
18030     * @param y hotspot y coordinate
18031     * @see #drawableHotspotChanged(float, float)
18032     */
18033    public void dispatchDrawableHotspotChanged(float x, float y) {
18034    }
18035
18036    /**
18037     * Call this to force a view to update its drawable state. This will cause
18038     * drawableStateChanged to be called on this view. Views that are interested
18039     * in the new state should call getDrawableState.
18040     *
18041     * @see #drawableStateChanged
18042     * @see #getDrawableState
18043     */
18044    public void refreshDrawableState() {
18045        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18046        drawableStateChanged();
18047
18048        ViewParent parent = mParent;
18049        if (parent != null) {
18050            parent.childDrawableStateChanged(this);
18051        }
18052    }
18053
18054    /**
18055     * Return an array of resource IDs of the drawable states representing the
18056     * current state of the view.
18057     *
18058     * @return The current drawable state
18059     *
18060     * @see Drawable#setState(int[])
18061     * @see #drawableStateChanged()
18062     * @see #onCreateDrawableState(int)
18063     */
18064    public final int[] getDrawableState() {
18065        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
18066            return mDrawableState;
18067        } else {
18068            mDrawableState = onCreateDrawableState(0);
18069            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
18070            return mDrawableState;
18071        }
18072    }
18073
18074    /**
18075     * Generate the new {@link android.graphics.drawable.Drawable} state for
18076     * this view. This is called by the view
18077     * system when the cached Drawable state is determined to be invalid.  To
18078     * retrieve the current state, you should use {@link #getDrawableState}.
18079     *
18080     * @param extraSpace if non-zero, this is the number of extra entries you
18081     * would like in the returned array in which you can place your own
18082     * states.
18083     *
18084     * @return Returns an array holding the current {@link Drawable} state of
18085     * the view.
18086     *
18087     * @see #mergeDrawableStates(int[], int[])
18088     */
18089    protected int[] onCreateDrawableState(int extraSpace) {
18090        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
18091                mParent instanceof View) {
18092            return ((View) mParent).onCreateDrawableState(extraSpace);
18093        }
18094
18095        int[] drawableState;
18096
18097        int privateFlags = mPrivateFlags;
18098
18099        int viewStateIndex = 0;
18100        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
18101        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
18102        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
18103        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
18104        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
18105        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
18106        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
18107                ThreadedRenderer.isAvailable()) {
18108            // This is set if HW acceleration is requested, even if the current
18109            // process doesn't allow it.  This is just to allow app preview
18110            // windows to better match their app.
18111            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
18112        }
18113        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
18114
18115        final int privateFlags2 = mPrivateFlags2;
18116        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
18117            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
18118        }
18119        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
18120            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
18121        }
18122
18123        drawableState = StateSet.get(viewStateIndex);
18124
18125        //noinspection ConstantIfStatement
18126        if (false) {
18127            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18128            Log.i("View", toString()
18129                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18130                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18131                    + " fo=" + hasFocus()
18132                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18133                    + " wf=" + hasWindowFocus()
18134                    + ": " + Arrays.toString(drawableState));
18135        }
18136
18137        if (extraSpace == 0) {
18138            return drawableState;
18139        }
18140
18141        final int[] fullState;
18142        if (drawableState != null) {
18143            fullState = new int[drawableState.length + extraSpace];
18144            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18145        } else {
18146            fullState = new int[extraSpace];
18147        }
18148
18149        return fullState;
18150    }
18151
18152    /**
18153     * Merge your own state values in <var>additionalState</var> into the base
18154     * state values <var>baseState</var> that were returned by
18155     * {@link #onCreateDrawableState(int)}.
18156     *
18157     * @param baseState The base state values returned by
18158     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18159     * own additional state values.
18160     *
18161     * @param additionalState The additional state values you would like
18162     * added to <var>baseState</var>; this array is not modified.
18163     *
18164     * @return As a convenience, the <var>baseState</var> array you originally
18165     * passed into the function is returned.
18166     *
18167     * @see #onCreateDrawableState(int)
18168     */
18169    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18170        final int N = baseState.length;
18171        int i = N - 1;
18172        while (i >= 0 && baseState[i] == 0) {
18173            i--;
18174        }
18175        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18176        return baseState;
18177    }
18178
18179    /**
18180     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18181     * on all Drawable objects associated with this view.
18182     * <p>
18183     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18184     * attached to this view.
18185     */
18186    @CallSuper
18187    public void jumpDrawablesToCurrentState() {
18188        if (mBackground != null) {
18189            mBackground.jumpToCurrentState();
18190        }
18191        if (mStateListAnimator != null) {
18192            mStateListAnimator.jumpToCurrentState();
18193        }
18194        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18195            mForegroundInfo.mDrawable.jumpToCurrentState();
18196        }
18197    }
18198
18199    /**
18200     * Sets the background color for this view.
18201     * @param color the color of the background
18202     */
18203    @RemotableViewMethod
18204    public void setBackgroundColor(@ColorInt int color) {
18205        if (mBackground instanceof ColorDrawable) {
18206            ((ColorDrawable) mBackground.mutate()).setColor(color);
18207            computeOpaqueFlags();
18208            mBackgroundResource = 0;
18209        } else {
18210            setBackground(new ColorDrawable(color));
18211        }
18212    }
18213
18214    /**
18215     * Set the background to a given resource. The resource should refer to
18216     * a Drawable object or 0 to remove the background.
18217     * @param resid The identifier of the resource.
18218     *
18219     * @attr ref android.R.styleable#View_background
18220     */
18221    @RemotableViewMethod
18222    public void setBackgroundResource(@DrawableRes int resid) {
18223        if (resid != 0 && resid == mBackgroundResource) {
18224            return;
18225        }
18226
18227        Drawable d = null;
18228        if (resid != 0) {
18229            d = mContext.getDrawable(resid);
18230        }
18231        setBackground(d);
18232
18233        mBackgroundResource = resid;
18234    }
18235
18236    /**
18237     * Set the background to a given Drawable, or remove the background. If the
18238     * background has padding, this View's padding is set to the background's
18239     * padding. However, when a background is removed, this View's padding isn't
18240     * touched. If setting the padding is desired, please use
18241     * {@link #setPadding(int, int, int, int)}.
18242     *
18243     * @param background The Drawable to use as the background, or null to remove the
18244     *        background
18245     */
18246    public void setBackground(Drawable background) {
18247        //noinspection deprecation
18248        setBackgroundDrawable(background);
18249    }
18250
18251    /**
18252     * @deprecated use {@link #setBackground(Drawable)} instead
18253     */
18254    @Deprecated
18255    public void setBackgroundDrawable(Drawable background) {
18256        computeOpaqueFlags();
18257
18258        if (background == mBackground) {
18259            return;
18260        }
18261
18262        boolean requestLayout = false;
18263
18264        mBackgroundResource = 0;
18265
18266        /*
18267         * Regardless of whether we're setting a new background or not, we want
18268         * to clear the previous drawable. setVisible first while we still have the callback set.
18269         */
18270        if (mBackground != null) {
18271            if (isAttachedToWindow()) {
18272                mBackground.setVisible(false, false);
18273            }
18274            mBackground.setCallback(null);
18275            unscheduleDrawable(mBackground);
18276        }
18277
18278        if (background != null) {
18279            Rect padding = sThreadLocal.get();
18280            if (padding == null) {
18281                padding = new Rect();
18282                sThreadLocal.set(padding);
18283            }
18284            resetResolvedDrawablesInternal();
18285            background.setLayoutDirection(getLayoutDirection());
18286            if (background.getPadding(padding)) {
18287                resetResolvedPaddingInternal();
18288                switch (background.getLayoutDirection()) {
18289                    case LAYOUT_DIRECTION_RTL:
18290                        mUserPaddingLeftInitial = padding.right;
18291                        mUserPaddingRightInitial = padding.left;
18292                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18293                        break;
18294                    case LAYOUT_DIRECTION_LTR:
18295                    default:
18296                        mUserPaddingLeftInitial = padding.left;
18297                        mUserPaddingRightInitial = padding.right;
18298                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18299                }
18300                mLeftPaddingDefined = false;
18301                mRightPaddingDefined = false;
18302            }
18303
18304            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18305            // if it has a different minimum size, we should layout again
18306            if (mBackground == null
18307                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18308                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18309                requestLayout = true;
18310            }
18311
18312            // Set mBackground before we set this as the callback and start making other
18313            // background drawable state change calls. In particular, the setVisible call below
18314            // can result in drawables attempting to start animations or otherwise invalidate,
18315            // which requires the view set as the callback (us) to recognize the drawable as
18316            // belonging to it as per verifyDrawable.
18317            mBackground = background;
18318            if (background.isStateful()) {
18319                background.setState(getDrawableState());
18320            }
18321            if (isAttachedToWindow()) {
18322                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18323            }
18324
18325            applyBackgroundTint();
18326
18327            // Set callback last, since the view may still be initializing.
18328            background.setCallback(this);
18329
18330            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18331                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18332                requestLayout = true;
18333            }
18334        } else {
18335            /* Remove the background */
18336            mBackground = null;
18337            if ((mViewFlags & WILL_NOT_DRAW) != 0
18338                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18339                mPrivateFlags |= PFLAG_SKIP_DRAW;
18340            }
18341
18342            /*
18343             * When the background is set, we try to apply its padding to this
18344             * View. When the background is removed, we don't touch this View's
18345             * padding. This is noted in the Javadocs. Hence, we don't need to
18346             * requestLayout(), the invalidate() below is sufficient.
18347             */
18348
18349            // The old background's minimum size could have affected this
18350            // View's layout, so let's requestLayout
18351            requestLayout = true;
18352        }
18353
18354        computeOpaqueFlags();
18355
18356        if (requestLayout) {
18357            requestLayout();
18358        }
18359
18360        mBackgroundSizeChanged = true;
18361        invalidate(true);
18362        invalidateOutline();
18363    }
18364
18365    /**
18366     * Gets the background drawable
18367     *
18368     * @return The drawable used as the background for this view, if any.
18369     *
18370     * @see #setBackground(Drawable)
18371     *
18372     * @attr ref android.R.styleable#View_background
18373     */
18374    public Drawable getBackground() {
18375        return mBackground;
18376    }
18377
18378    /**
18379     * Applies a tint to the background drawable. Does not modify the current tint
18380     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18381     * <p>
18382     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18383     * mutate the drawable and apply the specified tint and tint mode using
18384     * {@link Drawable#setTintList(ColorStateList)}.
18385     *
18386     * @param tint the tint to apply, may be {@code null} to clear tint
18387     *
18388     * @attr ref android.R.styleable#View_backgroundTint
18389     * @see #getBackgroundTintList()
18390     * @see Drawable#setTintList(ColorStateList)
18391     */
18392    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18393        if (mBackgroundTint == null) {
18394            mBackgroundTint = new TintInfo();
18395        }
18396        mBackgroundTint.mTintList = tint;
18397        mBackgroundTint.mHasTintList = true;
18398
18399        applyBackgroundTint();
18400    }
18401
18402    /**
18403     * Return the tint applied to the background drawable, if specified.
18404     *
18405     * @return the tint applied to the background drawable
18406     * @attr ref android.R.styleable#View_backgroundTint
18407     * @see #setBackgroundTintList(ColorStateList)
18408     */
18409    @Nullable
18410    public ColorStateList getBackgroundTintList() {
18411        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18412    }
18413
18414    /**
18415     * Specifies the blending mode used to apply the tint specified by
18416     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18417     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18418     *
18419     * @param tintMode the blending mode used to apply the tint, may be
18420     *                 {@code null} to clear tint
18421     * @attr ref android.R.styleable#View_backgroundTintMode
18422     * @see #getBackgroundTintMode()
18423     * @see Drawable#setTintMode(PorterDuff.Mode)
18424     */
18425    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18426        if (mBackgroundTint == null) {
18427            mBackgroundTint = new TintInfo();
18428        }
18429        mBackgroundTint.mTintMode = tintMode;
18430        mBackgroundTint.mHasTintMode = true;
18431
18432        applyBackgroundTint();
18433    }
18434
18435    /**
18436     * Return the blending mode used to apply the tint to the background
18437     * drawable, if specified.
18438     *
18439     * @return the blending mode used to apply the tint to the background
18440     *         drawable
18441     * @attr ref android.R.styleable#View_backgroundTintMode
18442     * @see #setBackgroundTintMode(PorterDuff.Mode)
18443     */
18444    @Nullable
18445    public PorterDuff.Mode getBackgroundTintMode() {
18446        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18447    }
18448
18449    private void applyBackgroundTint() {
18450        if (mBackground != null && mBackgroundTint != null) {
18451            final TintInfo tintInfo = mBackgroundTint;
18452            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18453                mBackground = mBackground.mutate();
18454
18455                if (tintInfo.mHasTintList) {
18456                    mBackground.setTintList(tintInfo.mTintList);
18457                }
18458
18459                if (tintInfo.mHasTintMode) {
18460                    mBackground.setTintMode(tintInfo.mTintMode);
18461                }
18462
18463                // The drawable (or one of its children) may not have been
18464                // stateful before applying the tint, so let's try again.
18465                if (mBackground.isStateful()) {
18466                    mBackground.setState(getDrawableState());
18467                }
18468            }
18469        }
18470    }
18471
18472    /**
18473     * Returns the drawable used as the foreground of this View. The
18474     * foreground drawable, if non-null, is always drawn on top of the view's content.
18475     *
18476     * @return a Drawable or null if no foreground was set
18477     *
18478     * @see #onDrawForeground(Canvas)
18479     */
18480    public Drawable getForeground() {
18481        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18482    }
18483
18484    /**
18485     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18486     *
18487     * @param foreground the Drawable to be drawn on top of the children
18488     *
18489     * @attr ref android.R.styleable#View_foreground
18490     */
18491    public void setForeground(Drawable foreground) {
18492        if (mForegroundInfo == null) {
18493            if (foreground == null) {
18494                // Nothing to do.
18495                return;
18496            }
18497            mForegroundInfo = new ForegroundInfo();
18498        }
18499
18500        if (foreground == mForegroundInfo.mDrawable) {
18501            // Nothing to do
18502            return;
18503        }
18504
18505        if (mForegroundInfo.mDrawable != null) {
18506            if (isAttachedToWindow()) {
18507                mForegroundInfo.mDrawable.setVisible(false, false);
18508            }
18509            mForegroundInfo.mDrawable.setCallback(null);
18510            unscheduleDrawable(mForegroundInfo.mDrawable);
18511        }
18512
18513        mForegroundInfo.mDrawable = foreground;
18514        mForegroundInfo.mBoundsChanged = true;
18515        if (foreground != null) {
18516            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18517                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18518            }
18519            foreground.setLayoutDirection(getLayoutDirection());
18520            if (foreground.isStateful()) {
18521                foreground.setState(getDrawableState());
18522            }
18523            applyForegroundTint();
18524            if (isAttachedToWindow()) {
18525                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18526            }
18527            // Set callback last, since the view may still be initializing.
18528            foreground.setCallback(this);
18529        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18530            mPrivateFlags |= PFLAG_SKIP_DRAW;
18531        }
18532        requestLayout();
18533        invalidate();
18534    }
18535
18536    /**
18537     * Magic bit used to support features of framework-internal window decor implementation details.
18538     * This used to live exclusively in FrameLayout.
18539     *
18540     * @return true if the foreground should draw inside the padding region or false
18541     *         if it should draw inset by the view's padding
18542     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18543     */
18544    public boolean isForegroundInsidePadding() {
18545        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18546    }
18547
18548    /**
18549     * Describes how the foreground is positioned.
18550     *
18551     * @return foreground gravity.
18552     *
18553     * @see #setForegroundGravity(int)
18554     *
18555     * @attr ref android.R.styleable#View_foregroundGravity
18556     */
18557    public int getForegroundGravity() {
18558        return mForegroundInfo != null ? mForegroundInfo.mGravity
18559                : Gravity.START | Gravity.TOP;
18560    }
18561
18562    /**
18563     * Describes how the foreground is positioned. Defaults to START and TOP.
18564     *
18565     * @param gravity see {@link android.view.Gravity}
18566     *
18567     * @see #getForegroundGravity()
18568     *
18569     * @attr ref android.R.styleable#View_foregroundGravity
18570     */
18571    public void setForegroundGravity(int gravity) {
18572        if (mForegroundInfo == null) {
18573            mForegroundInfo = new ForegroundInfo();
18574        }
18575
18576        if (mForegroundInfo.mGravity != gravity) {
18577            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18578                gravity |= Gravity.START;
18579            }
18580
18581            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18582                gravity |= Gravity.TOP;
18583            }
18584
18585            mForegroundInfo.mGravity = gravity;
18586            requestLayout();
18587        }
18588    }
18589
18590    /**
18591     * Applies a tint to the foreground drawable. Does not modify the current tint
18592     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18593     * <p>
18594     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18595     * mutate the drawable and apply the specified tint and tint mode using
18596     * {@link Drawable#setTintList(ColorStateList)}.
18597     *
18598     * @param tint the tint to apply, may be {@code null} to clear tint
18599     *
18600     * @attr ref android.R.styleable#View_foregroundTint
18601     * @see #getForegroundTintList()
18602     * @see Drawable#setTintList(ColorStateList)
18603     */
18604    public void setForegroundTintList(@Nullable ColorStateList tint) {
18605        if (mForegroundInfo == null) {
18606            mForegroundInfo = new ForegroundInfo();
18607        }
18608        if (mForegroundInfo.mTintInfo == null) {
18609            mForegroundInfo.mTintInfo = new TintInfo();
18610        }
18611        mForegroundInfo.mTintInfo.mTintList = tint;
18612        mForegroundInfo.mTintInfo.mHasTintList = true;
18613
18614        applyForegroundTint();
18615    }
18616
18617    /**
18618     * Return the tint applied to the foreground drawable, if specified.
18619     *
18620     * @return the tint applied to the foreground drawable
18621     * @attr ref android.R.styleable#View_foregroundTint
18622     * @see #setForegroundTintList(ColorStateList)
18623     */
18624    @Nullable
18625    public ColorStateList getForegroundTintList() {
18626        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18627                ? mForegroundInfo.mTintInfo.mTintList : null;
18628    }
18629
18630    /**
18631     * Specifies the blending mode used to apply the tint specified by
18632     * {@link #setForegroundTintList(ColorStateList)}} to the background
18633     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18634     *
18635     * @param tintMode the blending mode used to apply the tint, may be
18636     *                 {@code null} to clear tint
18637     * @attr ref android.R.styleable#View_foregroundTintMode
18638     * @see #getForegroundTintMode()
18639     * @see Drawable#setTintMode(PorterDuff.Mode)
18640     */
18641    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18642        if (mForegroundInfo == null) {
18643            mForegroundInfo = new ForegroundInfo();
18644        }
18645        if (mForegroundInfo.mTintInfo == null) {
18646            mForegroundInfo.mTintInfo = new TintInfo();
18647        }
18648        mForegroundInfo.mTintInfo.mTintMode = tintMode;
18649        mForegroundInfo.mTintInfo.mHasTintMode = true;
18650
18651        applyForegroundTint();
18652    }
18653
18654    /**
18655     * Return the blending mode used to apply the tint to the foreground
18656     * drawable, if specified.
18657     *
18658     * @return the blending mode used to apply the tint to the foreground
18659     *         drawable
18660     * @attr ref android.R.styleable#View_foregroundTintMode
18661     * @see #setForegroundTintMode(PorterDuff.Mode)
18662     */
18663    @Nullable
18664    public PorterDuff.Mode getForegroundTintMode() {
18665        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18666                ? mForegroundInfo.mTintInfo.mTintMode : null;
18667    }
18668
18669    private void applyForegroundTint() {
18670        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
18671                && mForegroundInfo.mTintInfo != null) {
18672            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
18673            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18674                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
18675
18676                if (tintInfo.mHasTintList) {
18677                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
18678                }
18679
18680                if (tintInfo.mHasTintMode) {
18681                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
18682                }
18683
18684                // The drawable (or one of its children) may not have been
18685                // stateful before applying the tint, so let's try again.
18686                if (mForegroundInfo.mDrawable.isStateful()) {
18687                    mForegroundInfo.mDrawable.setState(getDrawableState());
18688                }
18689            }
18690        }
18691    }
18692
18693    /**
18694     * Draw any foreground content for this view.
18695     *
18696     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
18697     * drawable or other view-specific decorations. The foreground is drawn on top of the
18698     * primary view content.</p>
18699     *
18700     * @param canvas canvas to draw into
18701     */
18702    public void onDrawForeground(Canvas canvas) {
18703        onDrawScrollIndicators(canvas);
18704        onDrawScrollBars(canvas);
18705
18706        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18707        if (foreground != null) {
18708            if (mForegroundInfo.mBoundsChanged) {
18709                mForegroundInfo.mBoundsChanged = false;
18710                final Rect selfBounds = mForegroundInfo.mSelfBounds;
18711                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
18712
18713                if (mForegroundInfo.mInsidePadding) {
18714                    selfBounds.set(0, 0, getWidth(), getHeight());
18715                } else {
18716                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
18717                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
18718                }
18719
18720                final int ld = getLayoutDirection();
18721                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
18722                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
18723                foreground.setBounds(overlayBounds);
18724            }
18725
18726            foreground.draw(canvas);
18727        }
18728    }
18729
18730    /**
18731     * Sets the padding. The view may add on the space required to display
18732     * the scrollbars, depending on the style and visibility of the scrollbars.
18733     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
18734     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
18735     * from the values set in this call.
18736     *
18737     * @attr ref android.R.styleable#View_padding
18738     * @attr ref android.R.styleable#View_paddingBottom
18739     * @attr ref android.R.styleable#View_paddingLeft
18740     * @attr ref android.R.styleable#View_paddingRight
18741     * @attr ref android.R.styleable#View_paddingTop
18742     * @param left the left padding in pixels
18743     * @param top the top padding in pixels
18744     * @param right the right padding in pixels
18745     * @param bottom the bottom padding in pixels
18746     */
18747    public void setPadding(int left, int top, int right, int bottom) {
18748        resetResolvedPaddingInternal();
18749
18750        mUserPaddingStart = UNDEFINED_PADDING;
18751        mUserPaddingEnd = UNDEFINED_PADDING;
18752
18753        mUserPaddingLeftInitial = left;
18754        mUserPaddingRightInitial = right;
18755
18756        mLeftPaddingDefined = true;
18757        mRightPaddingDefined = true;
18758
18759        internalSetPadding(left, top, right, bottom);
18760    }
18761
18762    /**
18763     * @hide
18764     */
18765    protected void internalSetPadding(int left, int top, int right, int bottom) {
18766        mUserPaddingLeft = left;
18767        mUserPaddingRight = right;
18768        mUserPaddingBottom = bottom;
18769
18770        final int viewFlags = mViewFlags;
18771        boolean changed = false;
18772
18773        // Common case is there are no scroll bars.
18774        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
18775            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
18776                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
18777                        ? 0 : getVerticalScrollbarWidth();
18778                switch (mVerticalScrollbarPosition) {
18779                    case SCROLLBAR_POSITION_DEFAULT:
18780                        if (isLayoutRtl()) {
18781                            left += offset;
18782                        } else {
18783                            right += offset;
18784                        }
18785                        break;
18786                    case SCROLLBAR_POSITION_RIGHT:
18787                        right += offset;
18788                        break;
18789                    case SCROLLBAR_POSITION_LEFT:
18790                        left += offset;
18791                        break;
18792                }
18793            }
18794            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
18795                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
18796                        ? 0 : getHorizontalScrollbarHeight();
18797            }
18798        }
18799
18800        if (mPaddingLeft != left) {
18801            changed = true;
18802            mPaddingLeft = left;
18803        }
18804        if (mPaddingTop != top) {
18805            changed = true;
18806            mPaddingTop = top;
18807        }
18808        if (mPaddingRight != right) {
18809            changed = true;
18810            mPaddingRight = right;
18811        }
18812        if (mPaddingBottom != bottom) {
18813            changed = true;
18814            mPaddingBottom = bottom;
18815        }
18816
18817        if (changed) {
18818            requestLayout();
18819            invalidateOutline();
18820        }
18821    }
18822
18823    /**
18824     * Sets the relative padding. The view may add on the space required to display
18825     * the scrollbars, depending on the style and visibility of the scrollbars.
18826     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
18827     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
18828     * from the values set in this call.
18829     *
18830     * @attr ref android.R.styleable#View_padding
18831     * @attr ref android.R.styleable#View_paddingBottom
18832     * @attr ref android.R.styleable#View_paddingStart
18833     * @attr ref android.R.styleable#View_paddingEnd
18834     * @attr ref android.R.styleable#View_paddingTop
18835     * @param start the start padding in pixels
18836     * @param top the top padding in pixels
18837     * @param end the end padding in pixels
18838     * @param bottom the bottom padding in pixels
18839     */
18840    public void setPaddingRelative(int start, int top, int end, int bottom) {
18841        resetResolvedPaddingInternal();
18842
18843        mUserPaddingStart = start;
18844        mUserPaddingEnd = end;
18845        mLeftPaddingDefined = true;
18846        mRightPaddingDefined = true;
18847
18848        switch(getLayoutDirection()) {
18849            case LAYOUT_DIRECTION_RTL:
18850                mUserPaddingLeftInitial = end;
18851                mUserPaddingRightInitial = start;
18852                internalSetPadding(end, top, start, bottom);
18853                break;
18854            case LAYOUT_DIRECTION_LTR:
18855            default:
18856                mUserPaddingLeftInitial = start;
18857                mUserPaddingRightInitial = end;
18858                internalSetPadding(start, top, end, bottom);
18859        }
18860    }
18861
18862    /**
18863     * Returns the top padding of this view.
18864     *
18865     * @return the top padding in pixels
18866     */
18867    public int getPaddingTop() {
18868        return mPaddingTop;
18869    }
18870
18871    /**
18872     * Returns the bottom padding of this view. If there are inset and enabled
18873     * scrollbars, this value may include the space required to display the
18874     * scrollbars as well.
18875     *
18876     * @return the bottom padding in pixels
18877     */
18878    public int getPaddingBottom() {
18879        return mPaddingBottom;
18880    }
18881
18882    /**
18883     * Returns the left padding of this view. If there are inset and enabled
18884     * scrollbars, this value may include the space required to display the
18885     * scrollbars as well.
18886     *
18887     * @return the left padding in pixels
18888     */
18889    public int getPaddingLeft() {
18890        if (!isPaddingResolved()) {
18891            resolvePadding();
18892        }
18893        return mPaddingLeft;
18894    }
18895
18896    /**
18897     * Returns the start padding of this view depending on its resolved layout direction.
18898     * If there are inset and enabled scrollbars, this value may include the space
18899     * required to display the scrollbars as well.
18900     *
18901     * @return the start padding in pixels
18902     */
18903    public int getPaddingStart() {
18904        if (!isPaddingResolved()) {
18905            resolvePadding();
18906        }
18907        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18908                mPaddingRight : mPaddingLeft;
18909    }
18910
18911    /**
18912     * Returns the right padding of this view. If there are inset and enabled
18913     * scrollbars, this value may include the space required to display the
18914     * scrollbars as well.
18915     *
18916     * @return the right padding in pixels
18917     */
18918    public int getPaddingRight() {
18919        if (!isPaddingResolved()) {
18920            resolvePadding();
18921        }
18922        return mPaddingRight;
18923    }
18924
18925    /**
18926     * Returns the end padding of this view depending on its resolved layout direction.
18927     * If there are inset and enabled scrollbars, this value may include the space
18928     * required to display the scrollbars as well.
18929     *
18930     * @return the end padding in pixels
18931     */
18932    public int getPaddingEnd() {
18933        if (!isPaddingResolved()) {
18934            resolvePadding();
18935        }
18936        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18937                mPaddingLeft : mPaddingRight;
18938    }
18939
18940    /**
18941     * Return if the padding has been set through relative values
18942     * {@link #setPaddingRelative(int, int, int, int)} or through
18943     * @attr ref android.R.styleable#View_paddingStart or
18944     * @attr ref android.R.styleable#View_paddingEnd
18945     *
18946     * @return true if the padding is relative or false if it is not.
18947     */
18948    public boolean isPaddingRelative() {
18949        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
18950    }
18951
18952    Insets computeOpticalInsets() {
18953        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
18954    }
18955
18956    /**
18957     * @hide
18958     */
18959    public void resetPaddingToInitialValues() {
18960        if (isRtlCompatibilityMode()) {
18961            mPaddingLeft = mUserPaddingLeftInitial;
18962            mPaddingRight = mUserPaddingRightInitial;
18963            return;
18964        }
18965        if (isLayoutRtl()) {
18966            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
18967            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
18968        } else {
18969            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
18970            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
18971        }
18972    }
18973
18974    /**
18975     * @hide
18976     */
18977    public Insets getOpticalInsets() {
18978        if (mLayoutInsets == null) {
18979            mLayoutInsets = computeOpticalInsets();
18980        }
18981        return mLayoutInsets;
18982    }
18983
18984    /**
18985     * Set this view's optical insets.
18986     *
18987     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
18988     * property. Views that compute their own optical insets should call it as part of measurement.
18989     * This method does not request layout. If you are setting optical insets outside of
18990     * measure/layout itself you will want to call requestLayout() yourself.
18991     * </p>
18992     * @hide
18993     */
18994    public void setOpticalInsets(Insets insets) {
18995        mLayoutInsets = insets;
18996    }
18997
18998    /**
18999     * Changes the selection state of this view. A view can be selected or not.
19000     * Note that selection is not the same as focus. Views are typically
19001     * selected in the context of an AdapterView like ListView or GridView;
19002     * the selected view is the view that is highlighted.
19003     *
19004     * @param selected true if the view must be selected, false otherwise
19005     */
19006    public void setSelected(boolean selected) {
19007        //noinspection DoubleNegation
19008        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19009            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19010            if (!selected) resetPressedState();
19011            invalidate(true);
19012            refreshDrawableState();
19013            dispatchSetSelected(selected);
19014            if (selected) {
19015                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19016            } else {
19017                notifyViewAccessibilityStateChangedIfNeeded(
19018                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19019            }
19020        }
19021    }
19022
19023    /**
19024     * Dispatch setSelected to all of this View's children.
19025     *
19026     * @see #setSelected(boolean)
19027     *
19028     * @param selected The new selected state
19029     */
19030    protected void dispatchSetSelected(boolean selected) {
19031    }
19032
19033    /**
19034     * Indicates the selection state of this view.
19035     *
19036     * @return true if the view is selected, false otherwise
19037     */
19038    @ViewDebug.ExportedProperty
19039    public boolean isSelected() {
19040        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19041    }
19042
19043    /**
19044     * Changes the activated state of this view. A view can be activated or not.
19045     * Note that activation is not the same as selection.  Selection is
19046     * a transient property, representing the view (hierarchy) the user is
19047     * currently interacting with.  Activation is a longer-term state that the
19048     * user can move views in and out of.  For example, in a list view with
19049     * single or multiple selection enabled, the views in the current selection
19050     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19051     * here.)  The activated state is propagated down to children of the view it
19052     * is set on.
19053     *
19054     * @param activated true if the view must be activated, false otherwise
19055     */
19056    public void setActivated(boolean activated) {
19057        //noinspection DoubleNegation
19058        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19059            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19060            invalidate(true);
19061            refreshDrawableState();
19062            dispatchSetActivated(activated);
19063        }
19064    }
19065
19066    /**
19067     * Dispatch setActivated to all of this View's children.
19068     *
19069     * @see #setActivated(boolean)
19070     *
19071     * @param activated The new activated state
19072     */
19073    protected void dispatchSetActivated(boolean activated) {
19074    }
19075
19076    /**
19077     * Indicates the activation state of this view.
19078     *
19079     * @return true if the view is activated, false otherwise
19080     */
19081    @ViewDebug.ExportedProperty
19082    public boolean isActivated() {
19083        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
19084    }
19085
19086    /**
19087     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
19088     * observer can be used to get notifications when global events, like
19089     * layout, happen.
19090     *
19091     * The returned ViewTreeObserver observer is not guaranteed to remain
19092     * valid for the lifetime of this View. If the caller of this method keeps
19093     * a long-lived reference to ViewTreeObserver, it should always check for
19094     * the return value of {@link ViewTreeObserver#isAlive()}.
19095     *
19096     * @return The ViewTreeObserver for this view's hierarchy.
19097     */
19098    public ViewTreeObserver getViewTreeObserver() {
19099        if (mAttachInfo != null) {
19100            return mAttachInfo.mTreeObserver;
19101        }
19102        if (mFloatingTreeObserver == null) {
19103            mFloatingTreeObserver = new ViewTreeObserver();
19104        }
19105        return mFloatingTreeObserver;
19106    }
19107
19108    /**
19109     * <p>Finds the topmost view in the current view hierarchy.</p>
19110     *
19111     * @return the topmost view containing this view
19112     */
19113    public View getRootView() {
19114        if (mAttachInfo != null) {
19115            final View v = mAttachInfo.mRootView;
19116            if (v != null) {
19117                return v;
19118            }
19119        }
19120
19121        View parent = this;
19122
19123        while (parent.mParent != null && parent.mParent instanceof View) {
19124            parent = (View) parent.mParent;
19125        }
19126
19127        return parent;
19128    }
19129
19130    /**
19131     * Transforms a motion event from view-local coordinates to on-screen
19132     * coordinates.
19133     *
19134     * @param ev the view-local motion event
19135     * @return false if the transformation could not be applied
19136     * @hide
19137     */
19138    public boolean toGlobalMotionEvent(MotionEvent ev) {
19139        final AttachInfo info = mAttachInfo;
19140        if (info == null) {
19141            return false;
19142        }
19143
19144        final Matrix m = info.mTmpMatrix;
19145        m.set(Matrix.IDENTITY_MATRIX);
19146        transformMatrixToGlobal(m);
19147        ev.transform(m);
19148        return true;
19149    }
19150
19151    /**
19152     * Transforms a motion event from on-screen coordinates to view-local
19153     * coordinates.
19154     *
19155     * @param ev the on-screen motion event
19156     * @return false if the transformation could not be applied
19157     * @hide
19158     */
19159    public boolean toLocalMotionEvent(MotionEvent ev) {
19160        final AttachInfo info = mAttachInfo;
19161        if (info == null) {
19162            return false;
19163        }
19164
19165        final Matrix m = info.mTmpMatrix;
19166        m.set(Matrix.IDENTITY_MATRIX);
19167        transformMatrixToLocal(m);
19168        ev.transform(m);
19169        return true;
19170    }
19171
19172    /**
19173     * Modifies the input matrix such that it maps view-local coordinates to
19174     * on-screen coordinates.
19175     *
19176     * @param m input matrix to modify
19177     * @hide
19178     */
19179    public void transformMatrixToGlobal(Matrix m) {
19180        final ViewParent parent = mParent;
19181        if (parent instanceof View) {
19182            final View vp = (View) parent;
19183            vp.transformMatrixToGlobal(m);
19184            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19185        } else if (parent instanceof ViewRootImpl) {
19186            final ViewRootImpl vr = (ViewRootImpl) parent;
19187            vr.transformMatrixToGlobal(m);
19188            m.preTranslate(0, -vr.mCurScrollY);
19189        }
19190
19191        m.preTranslate(mLeft, mTop);
19192
19193        if (!hasIdentityMatrix()) {
19194            m.preConcat(getMatrix());
19195        }
19196    }
19197
19198    /**
19199     * Modifies the input matrix such that it maps on-screen coordinates to
19200     * view-local coordinates.
19201     *
19202     * @param m input matrix to modify
19203     * @hide
19204     */
19205    public void transformMatrixToLocal(Matrix m) {
19206        final ViewParent parent = mParent;
19207        if (parent instanceof View) {
19208            final View vp = (View) parent;
19209            vp.transformMatrixToLocal(m);
19210            m.postTranslate(vp.mScrollX, vp.mScrollY);
19211        } else if (parent instanceof ViewRootImpl) {
19212            final ViewRootImpl vr = (ViewRootImpl) parent;
19213            vr.transformMatrixToLocal(m);
19214            m.postTranslate(0, vr.mCurScrollY);
19215        }
19216
19217        m.postTranslate(-mLeft, -mTop);
19218
19219        if (!hasIdentityMatrix()) {
19220            m.postConcat(getInverseMatrix());
19221        }
19222    }
19223
19224    /**
19225     * @hide
19226     */
19227    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19228            @ViewDebug.IntToString(from = 0, to = "x"),
19229            @ViewDebug.IntToString(from = 1, to = "y")
19230    })
19231    public int[] getLocationOnScreen() {
19232        int[] location = new int[2];
19233        getLocationOnScreen(location);
19234        return location;
19235    }
19236
19237    /**
19238     * <p>Computes the coordinates of this view on the screen. The argument
19239     * must be an array of two integers. After the method returns, the array
19240     * contains the x and y location in that order.</p>
19241     *
19242     * @param outLocation an array of two integers in which to hold the coordinates
19243     */
19244    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19245        getLocationInWindow(outLocation);
19246
19247        final AttachInfo info = mAttachInfo;
19248        if (info != null) {
19249            outLocation[0] += info.mWindowLeft;
19250            outLocation[1] += info.mWindowTop;
19251        }
19252    }
19253
19254    /**
19255     * <p>Computes the coordinates of this view in its window. The argument
19256     * must be an array of two integers. After the method returns, the array
19257     * contains the x and y location in that order.</p>
19258     *
19259     * @param outLocation an array of two integers in which to hold the coordinates
19260     */
19261    public void getLocationInWindow(@Size(2) int[] outLocation) {
19262        if (outLocation == null || outLocation.length < 2) {
19263            throw new IllegalArgumentException("outLocation must be an array of two integers");
19264        }
19265
19266        outLocation[0] = 0;
19267        outLocation[1] = 0;
19268
19269        transformFromViewToWindowSpace(outLocation);
19270    }
19271
19272    /** @hide */
19273    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19274        if (inOutLocation == null || inOutLocation.length < 2) {
19275            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19276        }
19277
19278        if (mAttachInfo == null) {
19279            // When the view is not attached to a window, this method does not make sense
19280            inOutLocation[0] = inOutLocation[1] = 0;
19281            return;
19282        }
19283
19284        float position[] = mAttachInfo.mTmpTransformLocation;
19285        position[0] = inOutLocation[0];
19286        position[1] = inOutLocation[1];
19287
19288        if (!hasIdentityMatrix()) {
19289            getMatrix().mapPoints(position);
19290        }
19291
19292        position[0] += mLeft;
19293        position[1] += mTop;
19294
19295        ViewParent viewParent = mParent;
19296        while (viewParent instanceof View) {
19297            final View view = (View) viewParent;
19298
19299            position[0] -= view.mScrollX;
19300            position[1] -= view.mScrollY;
19301
19302            if (!view.hasIdentityMatrix()) {
19303                view.getMatrix().mapPoints(position);
19304            }
19305
19306            position[0] += view.mLeft;
19307            position[1] += view.mTop;
19308
19309            viewParent = view.mParent;
19310         }
19311
19312        if (viewParent instanceof ViewRootImpl) {
19313            // *cough*
19314            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19315            position[1] -= vr.mCurScrollY;
19316        }
19317
19318        inOutLocation[0] = Math.round(position[0]);
19319        inOutLocation[1] = Math.round(position[1]);
19320    }
19321
19322    /**
19323     * {@hide}
19324     * @param id the id of the view to be found
19325     * @return the view of the specified id, null if cannot be found
19326     */
19327    protected View findViewTraversal(@IdRes int id) {
19328        if (id == mID) {
19329            return this;
19330        }
19331        return null;
19332    }
19333
19334    /**
19335     * {@hide}
19336     * @param tag the tag of the view to be found
19337     * @return the view of specified tag, null if cannot be found
19338     */
19339    protected View findViewWithTagTraversal(Object tag) {
19340        if (tag != null && tag.equals(mTag)) {
19341            return this;
19342        }
19343        return null;
19344    }
19345
19346    /**
19347     * {@hide}
19348     * @param predicate The predicate to evaluate.
19349     * @param childToSkip If not null, ignores this child during the recursive traversal.
19350     * @return The first view that matches the predicate or null.
19351     */
19352    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19353        if (predicate.apply(this)) {
19354            return this;
19355        }
19356        return null;
19357    }
19358
19359    /**
19360     * Look for a child view with the given id.  If this view has the given
19361     * id, return this view.
19362     *
19363     * @param id The id to search for.
19364     * @return The view that has the given id in the hierarchy or null
19365     */
19366    @Nullable
19367    public final View findViewById(@IdRes int id) {
19368        if (id < 0) {
19369            return null;
19370        }
19371        return findViewTraversal(id);
19372    }
19373
19374    /**
19375     * Finds a view by its unuque and stable accessibility id.
19376     *
19377     * @param accessibilityId The searched accessibility id.
19378     * @return The found view.
19379     */
19380    final View findViewByAccessibilityId(int accessibilityId) {
19381        if (accessibilityId < 0) {
19382            return null;
19383        }
19384        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19385        if (view != null) {
19386            return view.includeForAccessibility() ? view : null;
19387        }
19388        return null;
19389    }
19390
19391    /**
19392     * Performs the traversal to find a view by its unuque and stable accessibility id.
19393     *
19394     * <strong>Note:</strong>This method does not stop at the root namespace
19395     * boundary since the user can touch the screen at an arbitrary location
19396     * potentially crossing the root namespace bounday which will send an
19397     * accessibility event to accessibility services and they should be able
19398     * to obtain the event source. Also accessibility ids are guaranteed to be
19399     * unique in the window.
19400     *
19401     * @param accessibilityId The accessibility id.
19402     * @return The found view.
19403     *
19404     * @hide
19405     */
19406    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19407        if (getAccessibilityViewId() == accessibilityId) {
19408            return this;
19409        }
19410        return null;
19411    }
19412
19413    /**
19414     * Look for a child view with the given tag.  If this view has the given
19415     * tag, return this view.
19416     *
19417     * @param tag The tag to search for, using "tag.equals(getTag())".
19418     * @return The View that has the given tag in the hierarchy or null
19419     */
19420    public final View findViewWithTag(Object tag) {
19421        if (tag == null) {
19422            return null;
19423        }
19424        return findViewWithTagTraversal(tag);
19425    }
19426
19427    /**
19428     * {@hide}
19429     * Look for a child view that matches the specified predicate.
19430     * If this view matches the predicate, return this view.
19431     *
19432     * @param predicate The predicate to evaluate.
19433     * @return The first view that matches the predicate or null.
19434     */
19435    public final View findViewByPredicate(Predicate<View> predicate) {
19436        return findViewByPredicateTraversal(predicate, null);
19437    }
19438
19439    /**
19440     * {@hide}
19441     * Look for a child view that matches the specified predicate,
19442     * starting with the specified view and its descendents and then
19443     * recusively searching the ancestors and siblings of that view
19444     * until this view is reached.
19445     *
19446     * This method is useful in cases where the predicate does not match
19447     * a single unique view (perhaps multiple views use the same id)
19448     * and we are trying to find the view that is "closest" in scope to the
19449     * starting view.
19450     *
19451     * @param start The view to start from.
19452     * @param predicate The predicate to evaluate.
19453     * @return The first view that matches the predicate or null.
19454     */
19455    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19456        View childToSkip = null;
19457        for (;;) {
19458            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19459            if (view != null || start == this) {
19460                return view;
19461            }
19462
19463            ViewParent parent = start.getParent();
19464            if (parent == null || !(parent instanceof View)) {
19465                return null;
19466            }
19467
19468            childToSkip = start;
19469            start = (View) parent;
19470        }
19471    }
19472
19473    /**
19474     * Sets the identifier for this view. The identifier does not have to be
19475     * unique in this view's hierarchy. The identifier should be a positive
19476     * number.
19477     *
19478     * @see #NO_ID
19479     * @see #getId()
19480     * @see #findViewById(int)
19481     *
19482     * @param id a number used to identify the view
19483     *
19484     * @attr ref android.R.styleable#View_id
19485     */
19486    public void setId(@IdRes int id) {
19487        mID = id;
19488        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19489            mID = generateViewId();
19490        }
19491    }
19492
19493    /**
19494     * {@hide}
19495     *
19496     * @param isRoot true if the view belongs to the root namespace, false
19497     *        otherwise
19498     */
19499    public void setIsRootNamespace(boolean isRoot) {
19500        if (isRoot) {
19501            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19502        } else {
19503            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19504        }
19505    }
19506
19507    /**
19508     * {@hide}
19509     *
19510     * @return true if the view belongs to the root namespace, false otherwise
19511     */
19512    public boolean isRootNamespace() {
19513        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19514    }
19515
19516    /**
19517     * Returns this view's identifier.
19518     *
19519     * @return a positive integer used to identify the view or {@link #NO_ID}
19520     *         if the view has no ID
19521     *
19522     * @see #setId(int)
19523     * @see #findViewById(int)
19524     * @attr ref android.R.styleable#View_id
19525     */
19526    @IdRes
19527    @ViewDebug.CapturedViewProperty
19528    public int getId() {
19529        return mID;
19530    }
19531
19532    /**
19533     * Returns this view's tag.
19534     *
19535     * @return the Object stored in this view as a tag, or {@code null} if not
19536     *         set
19537     *
19538     * @see #setTag(Object)
19539     * @see #getTag(int)
19540     */
19541    @ViewDebug.ExportedProperty
19542    public Object getTag() {
19543        return mTag;
19544    }
19545
19546    /**
19547     * Sets the tag associated with this view. A tag can be used to mark
19548     * a view in its hierarchy and does not have to be unique within the
19549     * hierarchy. Tags can also be used to store data within a view without
19550     * resorting to another data structure.
19551     *
19552     * @param tag an Object to tag the view with
19553     *
19554     * @see #getTag()
19555     * @see #setTag(int, Object)
19556     */
19557    public void setTag(final Object tag) {
19558        mTag = tag;
19559    }
19560
19561    /**
19562     * Returns the tag associated with this view and the specified key.
19563     *
19564     * @param key The key identifying the tag
19565     *
19566     * @return the Object stored in this view as a tag, or {@code null} if not
19567     *         set
19568     *
19569     * @see #setTag(int, Object)
19570     * @see #getTag()
19571     */
19572    public Object getTag(int key) {
19573        if (mKeyedTags != null) return mKeyedTags.get(key);
19574        return null;
19575    }
19576
19577    /**
19578     * Sets a tag associated with this view and a key. A tag can be used
19579     * to mark a view in its hierarchy and does not have to be unique within
19580     * the hierarchy. Tags can also be used to store data within a view
19581     * without resorting to another data structure.
19582     *
19583     * The specified key should be an id declared in the resources of the
19584     * application to ensure it is unique (see the <a
19585     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19586     * Keys identified as belonging to
19587     * the Android framework or not associated with any package will cause
19588     * an {@link IllegalArgumentException} to be thrown.
19589     *
19590     * @param key The key identifying the tag
19591     * @param tag An Object to tag the view with
19592     *
19593     * @throws IllegalArgumentException If they specified key is not valid
19594     *
19595     * @see #setTag(Object)
19596     * @see #getTag(int)
19597     */
19598    public void setTag(int key, final Object tag) {
19599        // If the package id is 0x00 or 0x01, it's either an undefined package
19600        // or a framework id
19601        if ((key >>> 24) < 2) {
19602            throw new IllegalArgumentException("The key must be an application-specific "
19603                    + "resource id.");
19604        }
19605
19606        setKeyedTag(key, tag);
19607    }
19608
19609    /**
19610     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
19611     * framework id.
19612     *
19613     * @hide
19614     */
19615    public void setTagInternal(int key, Object tag) {
19616        if ((key >>> 24) != 0x1) {
19617            throw new IllegalArgumentException("The key must be a framework-specific "
19618                    + "resource id.");
19619        }
19620
19621        setKeyedTag(key, tag);
19622    }
19623
19624    private void setKeyedTag(int key, Object tag) {
19625        if (mKeyedTags == null) {
19626            mKeyedTags = new SparseArray<Object>(2);
19627        }
19628
19629        mKeyedTags.put(key, tag);
19630    }
19631
19632    /**
19633     * Prints information about this view in the log output, with the tag
19634     * {@link #VIEW_LOG_TAG}.
19635     *
19636     * @hide
19637     */
19638    public void debug() {
19639        debug(0);
19640    }
19641
19642    /**
19643     * Prints information about this view in the log output, with the tag
19644     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
19645     * indentation defined by the <code>depth</code>.
19646     *
19647     * @param depth the indentation level
19648     *
19649     * @hide
19650     */
19651    protected void debug(int depth) {
19652        String output = debugIndent(depth - 1);
19653
19654        output += "+ " + this;
19655        int id = getId();
19656        if (id != -1) {
19657            output += " (id=" + id + ")";
19658        }
19659        Object tag = getTag();
19660        if (tag != null) {
19661            output += " (tag=" + tag + ")";
19662        }
19663        Log.d(VIEW_LOG_TAG, output);
19664
19665        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
19666            output = debugIndent(depth) + " FOCUSED";
19667            Log.d(VIEW_LOG_TAG, output);
19668        }
19669
19670        output = debugIndent(depth);
19671        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
19672                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
19673                + "} ";
19674        Log.d(VIEW_LOG_TAG, output);
19675
19676        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
19677                || mPaddingBottom != 0) {
19678            output = debugIndent(depth);
19679            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
19680                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
19681            Log.d(VIEW_LOG_TAG, output);
19682        }
19683
19684        output = debugIndent(depth);
19685        output += "mMeasureWidth=" + mMeasuredWidth +
19686                " mMeasureHeight=" + mMeasuredHeight;
19687        Log.d(VIEW_LOG_TAG, output);
19688
19689        output = debugIndent(depth);
19690        if (mLayoutParams == null) {
19691            output += "BAD! no layout params";
19692        } else {
19693            output = mLayoutParams.debug(output);
19694        }
19695        Log.d(VIEW_LOG_TAG, output);
19696
19697        output = debugIndent(depth);
19698        output += "flags={";
19699        output += View.printFlags(mViewFlags);
19700        output += "}";
19701        Log.d(VIEW_LOG_TAG, output);
19702
19703        output = debugIndent(depth);
19704        output += "privateFlags={";
19705        output += View.printPrivateFlags(mPrivateFlags);
19706        output += "}";
19707        Log.d(VIEW_LOG_TAG, output);
19708    }
19709
19710    /**
19711     * Creates a string of whitespaces used for indentation.
19712     *
19713     * @param depth the indentation level
19714     * @return a String containing (depth * 2 + 3) * 2 white spaces
19715     *
19716     * @hide
19717     */
19718    protected static String debugIndent(int depth) {
19719        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
19720        for (int i = 0; i < (depth * 2) + 3; i++) {
19721            spaces.append(' ').append(' ');
19722        }
19723        return spaces.toString();
19724    }
19725
19726    /**
19727     * <p>Return the offset of the widget's text baseline from the widget's top
19728     * boundary. If this widget does not support baseline alignment, this
19729     * method returns -1. </p>
19730     *
19731     * @return the offset of the baseline within the widget's bounds or -1
19732     *         if baseline alignment is not supported
19733     */
19734    @ViewDebug.ExportedProperty(category = "layout")
19735    public int getBaseline() {
19736        return -1;
19737    }
19738
19739    /**
19740     * Returns whether the view hierarchy is currently undergoing a layout pass. This
19741     * information is useful to avoid situations such as calling {@link #requestLayout()} during
19742     * a layout pass.
19743     *
19744     * @return whether the view hierarchy is currently undergoing a layout pass
19745     */
19746    public boolean isInLayout() {
19747        ViewRootImpl viewRoot = getViewRootImpl();
19748        return (viewRoot != null && viewRoot.isInLayout());
19749    }
19750
19751    /**
19752     * Call this when something has changed which has invalidated the
19753     * layout of this view. This will schedule a layout pass of the view
19754     * tree. This should not be called while the view hierarchy is currently in a layout
19755     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
19756     * end of the current layout pass (and then layout will run again) or after the current
19757     * frame is drawn and the next layout occurs.
19758     *
19759     * <p>Subclasses which override this method should call the superclass method to
19760     * handle possible request-during-layout errors correctly.</p>
19761     */
19762    @CallSuper
19763    public void requestLayout() {
19764        if (mMeasureCache != null) mMeasureCache.clear();
19765
19766        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
19767            // Only trigger request-during-layout logic if this is the view requesting it,
19768            // not the views in its parent hierarchy
19769            ViewRootImpl viewRoot = getViewRootImpl();
19770            if (viewRoot != null && viewRoot.isInLayout()) {
19771                if (!viewRoot.requestLayoutDuringLayout(this)) {
19772                    return;
19773                }
19774            }
19775            mAttachInfo.mViewRequestingLayout = this;
19776        }
19777
19778        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19779        mPrivateFlags |= PFLAG_INVALIDATED;
19780
19781        if (mParent != null && !mParent.isLayoutRequested()) {
19782            mParent.requestLayout();
19783        }
19784        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
19785            mAttachInfo.mViewRequestingLayout = null;
19786        }
19787    }
19788
19789    /**
19790     * Forces this view to be laid out during the next layout pass.
19791     * This method does not call requestLayout() or forceLayout()
19792     * on the parent.
19793     */
19794    public void forceLayout() {
19795        if (mMeasureCache != null) mMeasureCache.clear();
19796
19797        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19798        mPrivateFlags |= PFLAG_INVALIDATED;
19799    }
19800
19801    /**
19802     * <p>
19803     * This is called to find out how big a view should be. The parent
19804     * supplies constraint information in the width and height parameters.
19805     * </p>
19806     *
19807     * <p>
19808     * The actual measurement work of a view is performed in
19809     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
19810     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
19811     * </p>
19812     *
19813     *
19814     * @param widthMeasureSpec Horizontal space requirements as imposed by the
19815     *        parent
19816     * @param heightMeasureSpec Vertical space requirements as imposed by the
19817     *        parent
19818     *
19819     * @see #onMeasure(int, int)
19820     */
19821    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
19822        boolean optical = isLayoutModeOptical(this);
19823        if (optical != isLayoutModeOptical(mParent)) {
19824            Insets insets = getOpticalInsets();
19825            int oWidth  = insets.left + insets.right;
19826            int oHeight = insets.top  + insets.bottom;
19827            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
19828            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
19829        }
19830
19831        // Suppress sign extension for the low bytes
19832        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
19833        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
19834
19835        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19836
19837        // Optimize layout by avoiding an extra EXACTLY pass when the view is
19838        // already measured as the correct size. In API 23 and below, this
19839        // extra pass is required to make LinearLayout re-distribute weight.
19840        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
19841                || heightMeasureSpec != mOldHeightMeasureSpec;
19842        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
19843                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
19844        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
19845                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
19846        final boolean needsLayout = specChanged
19847                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
19848
19849        if (forceLayout || needsLayout) {
19850            // first clears the measured dimension flag
19851            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
19852
19853            resolveRtlPropertiesIfNeeded();
19854
19855            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
19856            if (cacheIndex < 0 || sIgnoreMeasureCache) {
19857                // measure ourselves, this should set the measured dimension flag back
19858                onMeasure(widthMeasureSpec, heightMeasureSpec);
19859                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19860            } else {
19861                long value = mMeasureCache.valueAt(cacheIndex);
19862                // Casting a long to int drops the high 32 bits, no mask needed
19863                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
19864                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19865            }
19866
19867            // flag not set, setMeasuredDimension() was not invoked, we raise
19868            // an exception to warn the developer
19869            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
19870                throw new IllegalStateException("View with id " + getId() + ": "
19871                        + getClass().getName() + "#onMeasure() did not set the"
19872                        + " measured dimension by calling"
19873                        + " setMeasuredDimension()");
19874            }
19875
19876            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
19877        }
19878
19879        mOldWidthMeasureSpec = widthMeasureSpec;
19880        mOldHeightMeasureSpec = heightMeasureSpec;
19881
19882        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
19883                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
19884    }
19885
19886    /**
19887     * <p>
19888     * Measure the view and its content to determine the measured width and the
19889     * measured height. This method is invoked by {@link #measure(int, int)} and
19890     * should be overridden by subclasses to provide accurate and efficient
19891     * measurement of their contents.
19892     * </p>
19893     *
19894     * <p>
19895     * <strong>CONTRACT:</strong> When overriding this method, you
19896     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
19897     * measured width and height of this view. Failure to do so will trigger an
19898     * <code>IllegalStateException</code>, thrown by
19899     * {@link #measure(int, int)}. Calling the superclass'
19900     * {@link #onMeasure(int, int)} is a valid use.
19901     * </p>
19902     *
19903     * <p>
19904     * The base class implementation of measure defaults to the background size,
19905     * unless a larger size is allowed by the MeasureSpec. Subclasses should
19906     * override {@link #onMeasure(int, int)} to provide better measurements of
19907     * their content.
19908     * </p>
19909     *
19910     * <p>
19911     * If this method is overridden, it is the subclass's responsibility to make
19912     * sure the measured height and width are at least the view's minimum height
19913     * and width ({@link #getSuggestedMinimumHeight()} and
19914     * {@link #getSuggestedMinimumWidth()}).
19915     * </p>
19916     *
19917     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
19918     *                         The requirements are encoded with
19919     *                         {@link android.view.View.MeasureSpec}.
19920     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
19921     *                         The requirements are encoded with
19922     *                         {@link android.view.View.MeasureSpec}.
19923     *
19924     * @see #getMeasuredWidth()
19925     * @see #getMeasuredHeight()
19926     * @see #setMeasuredDimension(int, int)
19927     * @see #getSuggestedMinimumHeight()
19928     * @see #getSuggestedMinimumWidth()
19929     * @see android.view.View.MeasureSpec#getMode(int)
19930     * @see android.view.View.MeasureSpec#getSize(int)
19931     */
19932    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19933        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
19934                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
19935    }
19936
19937    /**
19938     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
19939     * measured width and measured height. Failing to do so will trigger an
19940     * exception at measurement time.</p>
19941     *
19942     * @param measuredWidth The measured width of this view.  May be a complex
19943     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19944     * {@link #MEASURED_STATE_TOO_SMALL}.
19945     * @param measuredHeight The measured height of this view.  May be a complex
19946     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19947     * {@link #MEASURED_STATE_TOO_SMALL}.
19948     */
19949    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
19950        boolean optical = isLayoutModeOptical(this);
19951        if (optical != isLayoutModeOptical(mParent)) {
19952            Insets insets = getOpticalInsets();
19953            int opticalWidth  = insets.left + insets.right;
19954            int opticalHeight = insets.top  + insets.bottom;
19955
19956            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
19957            measuredHeight += optical ? opticalHeight : -opticalHeight;
19958        }
19959        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
19960    }
19961
19962    /**
19963     * Sets the measured dimension without extra processing for things like optical bounds.
19964     * Useful for reapplying consistent values that have already been cooked with adjustments
19965     * for optical bounds, etc. such as those from the measurement cache.
19966     *
19967     * @param measuredWidth The measured width of this view.  May be a complex
19968     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19969     * {@link #MEASURED_STATE_TOO_SMALL}.
19970     * @param measuredHeight The measured height of this view.  May be a complex
19971     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19972     * {@link #MEASURED_STATE_TOO_SMALL}.
19973     */
19974    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
19975        mMeasuredWidth = measuredWidth;
19976        mMeasuredHeight = measuredHeight;
19977
19978        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
19979    }
19980
19981    /**
19982     * Merge two states as returned by {@link #getMeasuredState()}.
19983     * @param curState The current state as returned from a view or the result
19984     * of combining multiple views.
19985     * @param newState The new view state to combine.
19986     * @return Returns a new integer reflecting the combination of the two
19987     * states.
19988     */
19989    public static int combineMeasuredStates(int curState, int newState) {
19990        return curState | newState;
19991    }
19992
19993    /**
19994     * Version of {@link #resolveSizeAndState(int, int, int)}
19995     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
19996     */
19997    public static int resolveSize(int size, int measureSpec) {
19998        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
19999    }
20000
20001    /**
20002     * Utility to reconcile a desired size and state, with constraints imposed
20003     * by a MeasureSpec. Will take the desired size, unless a different size
20004     * is imposed by the constraints. The returned value is a compound integer,
20005     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20006     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20007     * resulting size is smaller than the size the view wants to be.
20008     *
20009     * @param size How big the view wants to be.
20010     * @param measureSpec Constraints imposed by the parent.
20011     * @param childMeasuredState Size information bit mask for the view's
20012     *                           children.
20013     * @return Size information bit mask as defined by
20014     *         {@link #MEASURED_SIZE_MASK} and
20015     *         {@link #MEASURED_STATE_TOO_SMALL}.
20016     */
20017    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20018        final int specMode = MeasureSpec.getMode(measureSpec);
20019        final int specSize = MeasureSpec.getSize(measureSpec);
20020        final int result;
20021        switch (specMode) {
20022            case MeasureSpec.AT_MOST:
20023                if (specSize < size) {
20024                    result = specSize | MEASURED_STATE_TOO_SMALL;
20025                } else {
20026                    result = size;
20027                }
20028                break;
20029            case MeasureSpec.EXACTLY:
20030                result = specSize;
20031                break;
20032            case MeasureSpec.UNSPECIFIED:
20033            default:
20034                result = size;
20035        }
20036        return result | (childMeasuredState & MEASURED_STATE_MASK);
20037    }
20038
20039    /**
20040     * Utility to return a default size. Uses the supplied size if the
20041     * MeasureSpec imposed no constraints. Will get larger if allowed
20042     * by the MeasureSpec.
20043     *
20044     * @param size Default size for this view
20045     * @param measureSpec Constraints imposed by the parent
20046     * @return The size this view should be.
20047     */
20048    public static int getDefaultSize(int size, int measureSpec) {
20049        int result = size;
20050        int specMode = MeasureSpec.getMode(measureSpec);
20051        int specSize = MeasureSpec.getSize(measureSpec);
20052
20053        switch (specMode) {
20054        case MeasureSpec.UNSPECIFIED:
20055            result = size;
20056            break;
20057        case MeasureSpec.AT_MOST:
20058        case MeasureSpec.EXACTLY:
20059            result = specSize;
20060            break;
20061        }
20062        return result;
20063    }
20064
20065    /**
20066     * Returns the suggested minimum height that the view should use. This
20067     * returns the maximum of the view's minimum height
20068     * and the background's minimum height
20069     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
20070     * <p>
20071     * When being used in {@link #onMeasure(int, int)}, the caller should still
20072     * ensure the returned height is within the requirements of the parent.
20073     *
20074     * @return The suggested minimum height of the view.
20075     */
20076    protected int getSuggestedMinimumHeight() {
20077        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
20078
20079    }
20080
20081    /**
20082     * Returns the suggested minimum width that the view should use. This
20083     * returns the maximum of the view's minimum width
20084     * and the background's minimum width
20085     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
20086     * <p>
20087     * When being used in {@link #onMeasure(int, int)}, the caller should still
20088     * ensure the returned width is within the requirements of the parent.
20089     *
20090     * @return The suggested minimum width of the view.
20091     */
20092    protected int getSuggestedMinimumWidth() {
20093        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
20094    }
20095
20096    /**
20097     * Returns the minimum height of the view.
20098     *
20099     * @return the minimum height the view will try to be.
20100     *
20101     * @see #setMinimumHeight(int)
20102     *
20103     * @attr ref android.R.styleable#View_minHeight
20104     */
20105    public int getMinimumHeight() {
20106        return mMinHeight;
20107    }
20108
20109    /**
20110     * Sets the minimum height of the view. It is not guaranteed the view will
20111     * be able to achieve this minimum height (for example, if its parent layout
20112     * constrains it with less available height).
20113     *
20114     * @param minHeight The minimum height the view will try to be.
20115     *
20116     * @see #getMinimumHeight()
20117     *
20118     * @attr ref android.R.styleable#View_minHeight
20119     */
20120    @RemotableViewMethod
20121    public void setMinimumHeight(int minHeight) {
20122        mMinHeight = minHeight;
20123        requestLayout();
20124    }
20125
20126    /**
20127     * Returns the minimum width of the view.
20128     *
20129     * @return the minimum width the view will try to be.
20130     *
20131     * @see #setMinimumWidth(int)
20132     *
20133     * @attr ref android.R.styleable#View_minWidth
20134     */
20135    public int getMinimumWidth() {
20136        return mMinWidth;
20137    }
20138
20139    /**
20140     * Sets the minimum width of the view. It is not guaranteed the view will
20141     * be able to achieve this minimum width (for example, if its parent layout
20142     * constrains it with less available width).
20143     *
20144     * @param minWidth The minimum width the view will try to be.
20145     *
20146     * @see #getMinimumWidth()
20147     *
20148     * @attr ref android.R.styleable#View_minWidth
20149     */
20150    public void setMinimumWidth(int minWidth) {
20151        mMinWidth = minWidth;
20152        requestLayout();
20153
20154    }
20155
20156    /**
20157     * Get the animation currently associated with this view.
20158     *
20159     * @return The animation that is currently playing or
20160     *         scheduled to play for this view.
20161     */
20162    public Animation getAnimation() {
20163        return mCurrentAnimation;
20164    }
20165
20166    /**
20167     * Start the specified animation now.
20168     *
20169     * @param animation the animation to start now
20170     */
20171    public void startAnimation(Animation animation) {
20172        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20173        setAnimation(animation);
20174        invalidateParentCaches();
20175        invalidate(true);
20176    }
20177
20178    /**
20179     * Cancels any animations for this view.
20180     */
20181    public void clearAnimation() {
20182        if (mCurrentAnimation != null) {
20183            mCurrentAnimation.detach();
20184        }
20185        mCurrentAnimation = null;
20186        invalidateParentIfNeeded();
20187    }
20188
20189    /**
20190     * Sets the next animation to play for this view.
20191     * If you want the animation to play immediately, use
20192     * {@link #startAnimation(android.view.animation.Animation)} instead.
20193     * This method provides allows fine-grained
20194     * control over the start time and invalidation, but you
20195     * must make sure that 1) the animation has a start time set, and
20196     * 2) the view's parent (which controls animations on its children)
20197     * will be invalidated when the animation is supposed to
20198     * start.
20199     *
20200     * @param animation The next animation, or null.
20201     */
20202    public void setAnimation(Animation animation) {
20203        mCurrentAnimation = animation;
20204
20205        if (animation != null) {
20206            // If the screen is off assume the animation start time is now instead of
20207            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20208            // would cause the animation to start when the screen turns back on
20209            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20210                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20211                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20212            }
20213            animation.reset();
20214        }
20215    }
20216
20217    /**
20218     * Invoked by a parent ViewGroup to notify the start of the animation
20219     * currently associated with this view. If you override this method,
20220     * always call super.onAnimationStart();
20221     *
20222     * @see #setAnimation(android.view.animation.Animation)
20223     * @see #getAnimation()
20224     */
20225    @CallSuper
20226    protected void onAnimationStart() {
20227        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20228    }
20229
20230    /**
20231     * Invoked by a parent ViewGroup to notify the end of the animation
20232     * currently associated with this view. If you override this method,
20233     * always call super.onAnimationEnd();
20234     *
20235     * @see #setAnimation(android.view.animation.Animation)
20236     * @see #getAnimation()
20237     */
20238    @CallSuper
20239    protected void onAnimationEnd() {
20240        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20241    }
20242
20243    /**
20244     * Invoked if there is a Transform that involves alpha. Subclass that can
20245     * draw themselves with the specified alpha should return true, and then
20246     * respect that alpha when their onDraw() is called. If this returns false
20247     * then the view may be redirected to draw into an offscreen buffer to
20248     * fulfill the request, which will look fine, but may be slower than if the
20249     * subclass handles it internally. The default implementation returns false.
20250     *
20251     * @param alpha The alpha (0..255) to apply to the view's drawing
20252     * @return true if the view can draw with the specified alpha.
20253     */
20254    protected boolean onSetAlpha(int alpha) {
20255        return false;
20256    }
20257
20258    /**
20259     * This is used by the RootView to perform an optimization when
20260     * the view hierarchy contains one or several SurfaceView.
20261     * SurfaceView is always considered transparent, but its children are not,
20262     * therefore all View objects remove themselves from the global transparent
20263     * region (passed as a parameter to this function).
20264     *
20265     * @param region The transparent region for this ViewAncestor (window).
20266     *
20267     * @return Returns true if the effective visibility of the view at this
20268     * point is opaque, regardless of the transparent region; returns false
20269     * if it is possible for underlying windows to be seen behind the view.
20270     *
20271     * {@hide}
20272     */
20273    public boolean gatherTransparentRegion(Region region) {
20274        final AttachInfo attachInfo = mAttachInfo;
20275        if (region != null && attachInfo != null) {
20276            final int pflags = mPrivateFlags;
20277            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20278                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20279                // remove it from the transparent region.
20280                final int[] location = attachInfo.mTransparentLocation;
20281                getLocationInWindow(location);
20282                // When a view has Z value, then it will be better to leave some area below the view
20283                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
20284                // the bottom part needs more offset than the left, top and right parts due to the
20285                // spot light effects.
20286                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
20287                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
20288                        location[0] + mRight - mLeft + shadowOffset,
20289                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
20290            } else {
20291                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20292                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20293                    // the background drawable's non-transparent parts from this transparent region.
20294                    applyDrawableToTransparentRegion(mBackground, region);
20295                }
20296                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20297                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20298                    // Similarly, we remove the foreground drawable's non-transparent parts.
20299                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20300                }
20301            }
20302        }
20303        return true;
20304    }
20305
20306    /**
20307     * Play a sound effect for this view.
20308     *
20309     * <p>The framework will play sound effects for some built in actions, such as
20310     * clicking, but you may wish to play these effects in your widget,
20311     * for instance, for internal navigation.
20312     *
20313     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20314     * {@link #isSoundEffectsEnabled()} is true.
20315     *
20316     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20317     */
20318    public void playSoundEffect(int soundConstant) {
20319        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20320            return;
20321        }
20322        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20323    }
20324
20325    /**
20326     * BZZZTT!!1!
20327     *
20328     * <p>Provide haptic feedback to the user for this view.
20329     *
20330     * <p>The framework will provide haptic feedback for some built in actions,
20331     * such as long presses, but you may wish to provide feedback for your
20332     * own widget.
20333     *
20334     * <p>The feedback will only be performed if
20335     * {@link #isHapticFeedbackEnabled()} is true.
20336     *
20337     * @param feedbackConstant One of the constants defined in
20338     * {@link HapticFeedbackConstants}
20339     */
20340    public boolean performHapticFeedback(int feedbackConstant) {
20341        return performHapticFeedback(feedbackConstant, 0);
20342    }
20343
20344    /**
20345     * BZZZTT!!1!
20346     *
20347     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20348     *
20349     * @param feedbackConstant One of the constants defined in
20350     * {@link HapticFeedbackConstants}
20351     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20352     */
20353    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20354        if (mAttachInfo == null) {
20355            return false;
20356        }
20357        //noinspection SimplifiableIfStatement
20358        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20359                && !isHapticFeedbackEnabled()) {
20360            return false;
20361        }
20362        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20363                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20364    }
20365
20366    /**
20367     * Request that the visibility of the status bar or other screen/window
20368     * decorations be changed.
20369     *
20370     * <p>This method is used to put the over device UI into temporary modes
20371     * where the user's attention is focused more on the application content,
20372     * by dimming or hiding surrounding system affordances.  This is typically
20373     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20374     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20375     * to be placed behind the action bar (and with these flags other system
20376     * affordances) so that smooth transitions between hiding and showing them
20377     * can be done.
20378     *
20379     * <p>Two representative examples of the use of system UI visibility is
20380     * implementing a content browsing application (like a magazine reader)
20381     * and a video playing application.
20382     *
20383     * <p>The first code shows a typical implementation of a View in a content
20384     * browsing application.  In this implementation, the application goes
20385     * into a content-oriented mode by hiding the status bar and action bar,
20386     * and putting the navigation elements into lights out mode.  The user can
20387     * then interact with content while in this mode.  Such an application should
20388     * provide an easy way for the user to toggle out of the mode (such as to
20389     * check information in the status bar or access notifications).  In the
20390     * implementation here, this is done simply by tapping on the content.
20391     *
20392     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20393     *      content}
20394     *
20395     * <p>This second code sample shows a typical implementation of a View
20396     * in a video playing application.  In this situation, while the video is
20397     * playing the application would like to go into a complete full-screen mode,
20398     * to use as much of the display as possible for the video.  When in this state
20399     * the user can not interact with the application; the system intercepts
20400     * touching on the screen to pop the UI out of full screen mode.  See
20401     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20402     *
20403     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20404     *      content}
20405     *
20406     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20407     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20408     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20409     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20410     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20411     */
20412    public void setSystemUiVisibility(int visibility) {
20413        if (visibility != mSystemUiVisibility) {
20414            mSystemUiVisibility = visibility;
20415            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20416                mParent.recomputeViewAttributes(this);
20417            }
20418        }
20419    }
20420
20421    /**
20422     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20423     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20424     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20425     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20426     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20427     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20428     */
20429    public int getSystemUiVisibility() {
20430        return mSystemUiVisibility;
20431    }
20432
20433    /**
20434     * Returns the current system UI visibility that is currently set for
20435     * the entire window.  This is the combination of the
20436     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20437     * views in the window.
20438     */
20439    public int getWindowSystemUiVisibility() {
20440        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20441    }
20442
20443    /**
20444     * Override to find out when the window's requested system UI visibility
20445     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20446     * This is different from the callbacks received through
20447     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20448     * in that this is only telling you about the local request of the window,
20449     * not the actual values applied by the system.
20450     */
20451    public void onWindowSystemUiVisibilityChanged(int visible) {
20452    }
20453
20454    /**
20455     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20456     * the view hierarchy.
20457     */
20458    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20459        onWindowSystemUiVisibilityChanged(visible);
20460    }
20461
20462    /**
20463     * Set a listener to receive callbacks when the visibility of the system bar changes.
20464     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20465     */
20466    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20467        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20468        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20469            mParent.recomputeViewAttributes(this);
20470        }
20471    }
20472
20473    /**
20474     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20475     * the view hierarchy.
20476     */
20477    public void dispatchSystemUiVisibilityChanged(int visibility) {
20478        ListenerInfo li = mListenerInfo;
20479        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20480            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20481                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20482        }
20483    }
20484
20485    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20486        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20487        if (val != mSystemUiVisibility) {
20488            setSystemUiVisibility(val);
20489            return true;
20490        }
20491        return false;
20492    }
20493
20494    /** @hide */
20495    public void setDisabledSystemUiVisibility(int flags) {
20496        if (mAttachInfo != null) {
20497            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20498                mAttachInfo.mDisabledSystemUiVisibility = flags;
20499                if (mParent != null) {
20500                    mParent.recomputeViewAttributes(this);
20501                }
20502            }
20503        }
20504    }
20505
20506    /**
20507     * Creates an image that the system displays during the drag and drop
20508     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20509     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20510     * appearance as the given View. The default also positions the center of the drag shadow
20511     * directly under the touch point. If no View is provided (the constructor with no parameters
20512     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20513     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20514     * default is an invisible drag shadow.
20515     * <p>
20516     * You are not required to use the View you provide to the constructor as the basis of the
20517     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20518     * anything you want as the drag shadow.
20519     * </p>
20520     * <p>
20521     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20522     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20523     *  size and position of the drag shadow. It uses this data to construct a
20524     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20525     *  so that your application can draw the shadow image in the Canvas.
20526     * </p>
20527     *
20528     * <div class="special reference">
20529     * <h3>Developer Guides</h3>
20530     * <p>For a guide to implementing drag and drop features, read the
20531     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20532     * </div>
20533     */
20534    public static class DragShadowBuilder {
20535        private final WeakReference<View> mView;
20536
20537        /**
20538         * Constructs a shadow image builder based on a View. By default, the resulting drag
20539         * shadow will have the same appearance and dimensions as the View, with the touch point
20540         * over the center of the View.
20541         * @param view A View. Any View in scope can be used.
20542         */
20543        public DragShadowBuilder(View view) {
20544            mView = new WeakReference<View>(view);
20545        }
20546
20547        /**
20548         * Construct a shadow builder object with no associated View.  This
20549         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20550         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20551         * to supply the drag shadow's dimensions and appearance without
20552         * reference to any View object. If they are not overridden, then the result is an
20553         * invisible drag shadow.
20554         */
20555        public DragShadowBuilder() {
20556            mView = new WeakReference<View>(null);
20557        }
20558
20559        /**
20560         * Returns the View object that had been passed to the
20561         * {@link #View.DragShadowBuilder(View)}
20562         * constructor.  If that View parameter was {@code null} or if the
20563         * {@link #View.DragShadowBuilder()}
20564         * constructor was used to instantiate the builder object, this method will return
20565         * null.
20566         *
20567         * @return The View object associate with this builder object.
20568         */
20569        @SuppressWarnings({"JavadocReference"})
20570        final public View getView() {
20571            return mView.get();
20572        }
20573
20574        /**
20575         * Provides the metrics for the shadow image. These include the dimensions of
20576         * the shadow image, and the point within that shadow that should
20577         * be centered under the touch location while dragging.
20578         * <p>
20579         * The default implementation sets the dimensions of the shadow to be the
20580         * same as the dimensions of the View itself and centers the shadow under
20581         * the touch point.
20582         * </p>
20583         *
20584         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
20585         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20586         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20587         * image.
20588         *
20589         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
20590         * shadow image that should be underneath the touch point during the drag and drop
20591         * operation. Your application must set {@link android.graphics.Point#x} to the
20592         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20593         */
20594        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
20595            final View view = mView.get();
20596            if (view != null) {
20597                outShadowSize.set(view.getWidth(), view.getHeight());
20598                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
20599            } else {
20600                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20601            }
20602        }
20603
20604        /**
20605         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
20606         * based on the dimensions it received from the
20607         * {@link #onProvideShadowMetrics(Point, Point)} callback.
20608         *
20609         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
20610         */
20611        public void onDrawShadow(Canvas canvas) {
20612            final View view = mView.get();
20613            if (view != null) {
20614                view.draw(canvas);
20615            } else {
20616                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
20617            }
20618        }
20619    }
20620
20621    /**
20622     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
20623     * startDragAndDrop()} for newer platform versions.
20624     */
20625    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
20626                                   Object myLocalState, int flags) {
20627        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
20628    }
20629
20630    /**
20631     * Starts a drag and drop operation. When your application calls this method, it passes a
20632     * {@link android.view.View.DragShadowBuilder} object to the system. The
20633     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
20634     * to get metrics for the drag shadow, and then calls the object's
20635     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
20636     * <p>
20637     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
20638     *  drag events to all the View objects in your application that are currently visible. It does
20639     *  this either by calling the View object's drag listener (an implementation of
20640     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
20641     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
20642     *  Both are passed a {@link android.view.DragEvent} object that has a
20643     *  {@link android.view.DragEvent#getAction()} value of
20644     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
20645     * </p>
20646     * <p>
20647     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
20648     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
20649     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
20650     * to the View the user selected for dragging.
20651     * </p>
20652     * @param data A {@link android.content.ClipData} object pointing to the data to be
20653     * transferred by the drag and drop operation.
20654     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20655     * drag shadow.
20656     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
20657     * drop operation. This Object is put into every DragEvent object sent by the system during the
20658     * current drag.
20659     * <p>
20660     * myLocalState is a lightweight mechanism for the sending information from the dragged View
20661     * to the target Views. For example, it can contain flags that differentiate between a
20662     * a copy operation and a move operation.
20663     * </p>
20664     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
20665     * flags, or any combination of the following:
20666     *     <ul>
20667     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
20668     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
20669     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
20670     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
20671     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
20672     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
20673     *     </ul>
20674     * @return {@code true} if the method completes successfully, or
20675     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
20676     * do a drag, and so no drag operation is in progress.
20677     */
20678    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
20679            Object myLocalState, int flags) {
20680        if (ViewDebug.DEBUG_DRAG) {
20681            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
20682        }
20683        if (mAttachInfo == null) {
20684            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
20685            return false;
20686        }
20687        boolean okay = false;
20688
20689        Point shadowSize = new Point();
20690        Point shadowTouchPoint = new Point();
20691        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
20692
20693        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
20694                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
20695            throw new IllegalStateException("Drag shadow dimensions must not be negative");
20696        }
20697
20698        if (ViewDebug.DEBUG_DRAG) {
20699            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
20700                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
20701        }
20702        if (mAttachInfo.mDragSurface != null) {
20703            mAttachInfo.mDragSurface.release();
20704        }
20705        mAttachInfo.mDragSurface = new Surface();
20706        try {
20707            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
20708                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
20709            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
20710                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
20711            if (mAttachInfo.mDragToken != null) {
20712                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20713                try {
20714                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20715                    shadowBuilder.onDrawShadow(canvas);
20716                } finally {
20717                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20718                }
20719
20720                final ViewRootImpl root = getViewRootImpl();
20721
20722                // Cache the local state object for delivery with DragEvents
20723                root.setLocalDragState(myLocalState);
20724
20725                // repurpose 'shadowSize' for the last touch point
20726                root.getLastTouchPoint(shadowSize);
20727
20728                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
20729                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
20730                        shadowTouchPoint.x, shadowTouchPoint.y, data);
20731                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
20732            }
20733        } catch (Exception e) {
20734            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
20735            mAttachInfo.mDragSurface.destroy();
20736            mAttachInfo.mDragSurface = null;
20737        }
20738
20739        return okay;
20740    }
20741
20742    /**
20743     * Cancels an ongoing drag and drop operation.
20744     * <p>
20745     * A {@link android.view.DragEvent} object with
20746     * {@link android.view.DragEvent#getAction()} value of
20747     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
20748     * {@link android.view.DragEvent#getResult()} value of {@code false}
20749     * will be sent to every
20750     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
20751     * even if they are not currently visible.
20752     * </p>
20753     * <p>
20754     * This method can be called on any View in the same window as the View on which
20755     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
20756     * was called.
20757     * </p>
20758     */
20759    public final void cancelDragAndDrop() {
20760        if (ViewDebug.DEBUG_DRAG) {
20761            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
20762        }
20763        if (mAttachInfo == null) {
20764            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
20765            return;
20766        }
20767        if (mAttachInfo.mDragToken != null) {
20768            try {
20769                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
20770            } catch (Exception e) {
20771                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
20772            }
20773            mAttachInfo.mDragToken = null;
20774        } else {
20775            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
20776        }
20777    }
20778
20779    /**
20780     * Updates the drag shadow for the ongoing drag and drop operation.
20781     *
20782     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20783     * new drag shadow.
20784     */
20785    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
20786        if (ViewDebug.DEBUG_DRAG) {
20787            Log.d(VIEW_LOG_TAG, "updateDragShadow");
20788        }
20789        if (mAttachInfo == null) {
20790            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
20791            return;
20792        }
20793        if (mAttachInfo.mDragToken != null) {
20794            try {
20795                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20796                try {
20797                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20798                    shadowBuilder.onDrawShadow(canvas);
20799                } finally {
20800                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20801                }
20802            } catch (Exception e) {
20803                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
20804            }
20805        } else {
20806            Log.e(VIEW_LOG_TAG, "No active drag");
20807        }
20808    }
20809
20810    /**
20811     * Starts a move from {startX, startY}, the amount of the movement will be the offset
20812     * between {startX, startY} and the new cursor positon.
20813     * @param startX horizontal coordinate where the move started.
20814     * @param startY vertical coordinate where the move started.
20815     * @return whether moving was started successfully.
20816     * @hide
20817     */
20818    public final boolean startMovingTask(float startX, float startY) {
20819        if (ViewDebug.DEBUG_POSITIONING) {
20820            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
20821        }
20822        try {
20823            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
20824        } catch (RemoteException e) {
20825            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
20826        }
20827        return false;
20828    }
20829
20830    /**
20831     * Handles drag events sent by the system following a call to
20832     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
20833     * startDragAndDrop()}.
20834     *<p>
20835     * When the system calls this method, it passes a
20836     * {@link android.view.DragEvent} object. A call to
20837     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
20838     * in DragEvent. The method uses these to determine what is happening in the drag and drop
20839     * operation.
20840     * @param event The {@link android.view.DragEvent} sent by the system.
20841     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
20842     * in DragEvent, indicating the type of drag event represented by this object.
20843     * @return {@code true} if the method was successful, otherwise {@code false}.
20844     * <p>
20845     *  The method should return {@code true} in response to an action type of
20846     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
20847     *  operation.
20848     * </p>
20849     * <p>
20850     *  The method should also return {@code true} in response to an action type of
20851     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
20852     *  {@code false} if it didn't.
20853     * </p>
20854     */
20855    public boolean onDragEvent(DragEvent event) {
20856        return false;
20857    }
20858
20859    /**
20860     * Detects if this View is enabled and has a drag event listener.
20861     * If both are true, then it calls the drag event listener with the
20862     * {@link android.view.DragEvent} it received. If the drag event listener returns
20863     * {@code true}, then dispatchDragEvent() returns {@code true}.
20864     * <p>
20865     * For all other cases, the method calls the
20866     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
20867     * method and returns its result.
20868     * </p>
20869     * <p>
20870     * This ensures that a drag event is always consumed, even if the View does not have a drag
20871     * event listener. However, if the View has a listener and the listener returns true, then
20872     * onDragEvent() is not called.
20873     * </p>
20874     */
20875    public boolean dispatchDragEvent(DragEvent event) {
20876        event.mEventHandlerWasCalled = true;
20877        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
20878            event.mAction == DragEvent.ACTION_DROP) {
20879            // About to deliver an event with coordinates to this view. Notify that now this view
20880            // has drag focus. This will send exit/enter events as needed.
20881            getViewRootImpl().setDragFocus(this, event);
20882        }
20883        return callDragEventHandler(event);
20884    }
20885
20886    final boolean callDragEventHandler(DragEvent event) {
20887        ListenerInfo li = mListenerInfo;
20888        //noinspection SimplifiableIfStatement
20889        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
20890                && li.mOnDragListener.onDrag(this, event)) {
20891            return true;
20892        }
20893        return onDragEvent(event);
20894    }
20895
20896    boolean canAcceptDrag() {
20897        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
20898    }
20899
20900    /**
20901     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
20902     * it is ever exposed at all.
20903     * @hide
20904     */
20905    public void onCloseSystemDialogs(String reason) {
20906    }
20907
20908    /**
20909     * Given a Drawable whose bounds have been set to draw into this view,
20910     * update a Region being computed for
20911     * {@link #gatherTransparentRegion(android.graphics.Region)} so
20912     * that any non-transparent parts of the Drawable are removed from the
20913     * given transparent region.
20914     *
20915     * @param dr The Drawable whose transparency is to be applied to the region.
20916     * @param region A Region holding the current transparency information,
20917     * where any parts of the region that are set are considered to be
20918     * transparent.  On return, this region will be modified to have the
20919     * transparency information reduced by the corresponding parts of the
20920     * Drawable that are not transparent.
20921     * {@hide}
20922     */
20923    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
20924        if (DBG) {
20925            Log.i("View", "Getting transparent region for: " + this);
20926        }
20927        final Region r = dr.getTransparentRegion();
20928        final Rect db = dr.getBounds();
20929        final AttachInfo attachInfo = mAttachInfo;
20930        if (r != null && attachInfo != null) {
20931            final int w = getRight()-getLeft();
20932            final int h = getBottom()-getTop();
20933            if (db.left > 0) {
20934                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
20935                r.op(0, 0, db.left, h, Region.Op.UNION);
20936            }
20937            if (db.right < w) {
20938                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
20939                r.op(db.right, 0, w, h, Region.Op.UNION);
20940            }
20941            if (db.top > 0) {
20942                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
20943                r.op(0, 0, w, db.top, Region.Op.UNION);
20944            }
20945            if (db.bottom < h) {
20946                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
20947                r.op(0, db.bottom, w, h, Region.Op.UNION);
20948            }
20949            final int[] location = attachInfo.mTransparentLocation;
20950            getLocationInWindow(location);
20951            r.translate(location[0], location[1]);
20952            region.op(r, Region.Op.INTERSECT);
20953        } else {
20954            region.op(db, Region.Op.DIFFERENCE);
20955        }
20956    }
20957
20958    private void checkForLongClick(int delayOffset, float x, float y) {
20959        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
20960            mHasPerformedLongPress = false;
20961
20962            if (mPendingCheckForLongPress == null) {
20963                mPendingCheckForLongPress = new CheckForLongPress();
20964            }
20965            mPendingCheckForLongPress.setAnchor(x, y);
20966            mPendingCheckForLongPress.rememberWindowAttachCount();
20967            postDelayed(mPendingCheckForLongPress,
20968                    ViewConfiguration.getLongPressTimeout() - delayOffset);
20969        }
20970    }
20971
20972    /**
20973     * Inflate a view from an XML resource.  This convenience method wraps the {@link
20974     * LayoutInflater} class, which provides a full range of options for view inflation.
20975     *
20976     * @param context The Context object for your activity or application.
20977     * @param resource The resource ID to inflate
20978     * @param root A view group that will be the parent.  Used to properly inflate the
20979     * layout_* parameters.
20980     * @see LayoutInflater
20981     */
20982    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
20983        LayoutInflater factory = LayoutInflater.from(context);
20984        return factory.inflate(resource, root);
20985    }
20986
20987    /**
20988     * Scroll the view with standard behavior for scrolling beyond the normal
20989     * content boundaries. Views that call this method should override
20990     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
20991     * results of an over-scroll operation.
20992     *
20993     * Views can use this method to handle any touch or fling-based scrolling.
20994     *
20995     * @param deltaX Change in X in pixels
20996     * @param deltaY Change in Y in pixels
20997     * @param scrollX Current X scroll value in pixels before applying deltaX
20998     * @param scrollY Current Y scroll value in pixels before applying deltaY
20999     * @param scrollRangeX Maximum content scroll range along the X axis
21000     * @param scrollRangeY Maximum content scroll range along the Y axis
21001     * @param maxOverScrollX Number of pixels to overscroll by in either direction
21002     *          along the X axis.
21003     * @param maxOverScrollY Number of pixels to overscroll by in either direction
21004     *          along the Y axis.
21005     * @param isTouchEvent true if this scroll operation is the result of a touch event.
21006     * @return true if scrolling was clamped to an over-scroll boundary along either
21007     *          axis, false otherwise.
21008     */
21009    @SuppressWarnings({"UnusedParameters"})
21010    protected boolean overScrollBy(int deltaX, int deltaY,
21011            int scrollX, int scrollY,
21012            int scrollRangeX, int scrollRangeY,
21013            int maxOverScrollX, int maxOverScrollY,
21014            boolean isTouchEvent) {
21015        final int overScrollMode = mOverScrollMode;
21016        final boolean canScrollHorizontal =
21017                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21018        final boolean canScrollVertical =
21019                computeVerticalScrollRange() > computeVerticalScrollExtent();
21020        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21021                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21022        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21023                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21024
21025        int newScrollX = scrollX + deltaX;
21026        if (!overScrollHorizontal) {
21027            maxOverScrollX = 0;
21028        }
21029
21030        int newScrollY = scrollY + deltaY;
21031        if (!overScrollVertical) {
21032            maxOverScrollY = 0;
21033        }
21034
21035        // Clamp values if at the limits and record
21036        final int left = -maxOverScrollX;
21037        final int right = maxOverScrollX + scrollRangeX;
21038        final int top = -maxOverScrollY;
21039        final int bottom = maxOverScrollY + scrollRangeY;
21040
21041        boolean clampedX = false;
21042        if (newScrollX > right) {
21043            newScrollX = right;
21044            clampedX = true;
21045        } else if (newScrollX < left) {
21046            newScrollX = left;
21047            clampedX = true;
21048        }
21049
21050        boolean clampedY = false;
21051        if (newScrollY > bottom) {
21052            newScrollY = bottom;
21053            clampedY = true;
21054        } else if (newScrollY < top) {
21055            newScrollY = top;
21056            clampedY = true;
21057        }
21058
21059        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
21060
21061        return clampedX || clampedY;
21062    }
21063
21064    /**
21065     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
21066     * respond to the results of an over-scroll operation.
21067     *
21068     * @param scrollX New X scroll value in pixels
21069     * @param scrollY New Y scroll value in pixels
21070     * @param clampedX True if scrollX was clamped to an over-scroll boundary
21071     * @param clampedY True if scrollY was clamped to an over-scroll boundary
21072     */
21073    protected void onOverScrolled(int scrollX, int scrollY,
21074            boolean clampedX, boolean clampedY) {
21075        // Intentionally empty.
21076    }
21077
21078    /**
21079     * Returns the over-scroll mode for this view. The result will be
21080     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21081     * (allow over-scrolling only if the view content is larger than the container),
21082     * or {@link #OVER_SCROLL_NEVER}.
21083     *
21084     * @return This view's over-scroll mode.
21085     */
21086    public int getOverScrollMode() {
21087        return mOverScrollMode;
21088    }
21089
21090    /**
21091     * Set the over-scroll mode for this view. Valid over-scroll modes are
21092     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21093     * (allow over-scrolling only if the view content is larger than the container),
21094     * or {@link #OVER_SCROLL_NEVER}.
21095     *
21096     * Setting the over-scroll mode of a view will have an effect only if the
21097     * view is capable of scrolling.
21098     *
21099     * @param overScrollMode The new over-scroll mode for this view.
21100     */
21101    public void setOverScrollMode(int overScrollMode) {
21102        if (overScrollMode != OVER_SCROLL_ALWAYS &&
21103                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
21104                overScrollMode != OVER_SCROLL_NEVER) {
21105            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
21106        }
21107        mOverScrollMode = overScrollMode;
21108    }
21109
21110    /**
21111     * Enable or disable nested scrolling for this view.
21112     *
21113     * <p>If this property is set to true the view will be permitted to initiate nested
21114     * scrolling operations with a compatible parent view in the current hierarchy. If this
21115     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
21116     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
21117     * the nested scroll.</p>
21118     *
21119     * @param enabled true to enable nested scrolling, false to disable
21120     *
21121     * @see #isNestedScrollingEnabled()
21122     */
21123    public void setNestedScrollingEnabled(boolean enabled) {
21124        if (enabled) {
21125            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
21126        } else {
21127            stopNestedScroll();
21128            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
21129        }
21130    }
21131
21132    /**
21133     * Returns true if nested scrolling is enabled for this view.
21134     *
21135     * <p>If nested scrolling is enabled and this View class implementation supports it,
21136     * this view will act as a nested scrolling child view when applicable, forwarding data
21137     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21138     * parent.</p>
21139     *
21140     * @return true if nested scrolling is enabled
21141     *
21142     * @see #setNestedScrollingEnabled(boolean)
21143     */
21144    public boolean isNestedScrollingEnabled() {
21145        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21146                PFLAG3_NESTED_SCROLLING_ENABLED;
21147    }
21148
21149    /**
21150     * Begin a nestable scroll operation along the given axes.
21151     *
21152     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21153     *
21154     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21155     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21156     * In the case of touch scrolling the nested scroll will be terminated automatically in
21157     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21158     * In the event of programmatic scrolling the caller must explicitly call
21159     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21160     *
21161     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21162     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21163     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21164     *
21165     * <p>At each incremental step of the scroll the caller should invoke
21166     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21167     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21168     * parent at least partially consumed the scroll and the caller should adjust the amount it
21169     * scrolls by.</p>
21170     *
21171     * <p>After applying the remainder of the scroll delta the caller should invoke
21172     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21173     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21174     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21175     * </p>
21176     *
21177     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21178     *             {@link #SCROLL_AXIS_VERTICAL}.
21179     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21180     *         the current gesture.
21181     *
21182     * @see #stopNestedScroll()
21183     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21184     * @see #dispatchNestedScroll(int, int, int, int, int[])
21185     */
21186    public boolean startNestedScroll(int axes) {
21187        if (hasNestedScrollingParent()) {
21188            // Already in progress
21189            return true;
21190        }
21191        if (isNestedScrollingEnabled()) {
21192            ViewParent p = getParent();
21193            View child = this;
21194            while (p != null) {
21195                try {
21196                    if (p.onStartNestedScroll(child, this, axes)) {
21197                        mNestedScrollingParent = p;
21198                        p.onNestedScrollAccepted(child, this, axes);
21199                        return true;
21200                    }
21201                } catch (AbstractMethodError e) {
21202                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21203                            "method onStartNestedScroll", e);
21204                    // Allow the search upward to continue
21205                }
21206                if (p instanceof View) {
21207                    child = (View) p;
21208                }
21209                p = p.getParent();
21210            }
21211        }
21212        return false;
21213    }
21214
21215    /**
21216     * Stop a nested scroll in progress.
21217     *
21218     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21219     *
21220     * @see #startNestedScroll(int)
21221     */
21222    public void stopNestedScroll() {
21223        if (mNestedScrollingParent != null) {
21224            mNestedScrollingParent.onStopNestedScroll(this);
21225            mNestedScrollingParent = null;
21226        }
21227    }
21228
21229    /**
21230     * Returns true if this view has a nested scrolling parent.
21231     *
21232     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21233     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21234     *
21235     * @return whether this view has a nested scrolling parent
21236     */
21237    public boolean hasNestedScrollingParent() {
21238        return mNestedScrollingParent != null;
21239    }
21240
21241    /**
21242     * Dispatch one step of a nested scroll in progress.
21243     *
21244     * <p>Implementations of views that support nested scrolling should call this to report
21245     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21246     * is not currently in progress or nested scrolling is not
21247     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21248     *
21249     * <p>Compatible View implementations should also call
21250     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21251     * consuming a component of the scroll event themselves.</p>
21252     *
21253     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21254     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21255     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21256     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21257     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21258     *                       in local view coordinates of this view from before this operation
21259     *                       to after it completes. View implementations may use this to adjust
21260     *                       expected input coordinate tracking.
21261     * @return true if the event was dispatched, false if it could not be dispatched.
21262     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21263     */
21264    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21265            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21266        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21267            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21268                int startX = 0;
21269                int startY = 0;
21270                if (offsetInWindow != null) {
21271                    getLocationInWindow(offsetInWindow);
21272                    startX = offsetInWindow[0];
21273                    startY = offsetInWindow[1];
21274                }
21275
21276                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21277                        dxUnconsumed, dyUnconsumed);
21278
21279                if (offsetInWindow != null) {
21280                    getLocationInWindow(offsetInWindow);
21281                    offsetInWindow[0] -= startX;
21282                    offsetInWindow[1] -= startY;
21283                }
21284                return true;
21285            } else if (offsetInWindow != null) {
21286                // No motion, no dispatch. Keep offsetInWindow up to date.
21287                offsetInWindow[0] = 0;
21288                offsetInWindow[1] = 0;
21289            }
21290        }
21291        return false;
21292    }
21293
21294    /**
21295     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21296     *
21297     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21298     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21299     * scrolling operation to consume some or all of the scroll operation before the child view
21300     * consumes it.</p>
21301     *
21302     * @param dx Horizontal scroll distance in pixels
21303     * @param dy Vertical scroll distance in pixels
21304     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21305     *                 and consumed[1] the consumed dy.
21306     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21307     *                       in local view coordinates of this view from before this operation
21308     *                       to after it completes. View implementations may use this to adjust
21309     *                       expected input coordinate tracking.
21310     * @return true if the parent consumed some or all of the scroll delta
21311     * @see #dispatchNestedScroll(int, int, int, int, int[])
21312     */
21313    public boolean dispatchNestedPreScroll(int dx, int dy,
21314            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21315        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21316            if (dx != 0 || dy != 0) {
21317                int startX = 0;
21318                int startY = 0;
21319                if (offsetInWindow != null) {
21320                    getLocationInWindow(offsetInWindow);
21321                    startX = offsetInWindow[0];
21322                    startY = offsetInWindow[1];
21323                }
21324
21325                if (consumed == null) {
21326                    if (mTempNestedScrollConsumed == null) {
21327                        mTempNestedScrollConsumed = new int[2];
21328                    }
21329                    consumed = mTempNestedScrollConsumed;
21330                }
21331                consumed[0] = 0;
21332                consumed[1] = 0;
21333                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21334
21335                if (offsetInWindow != null) {
21336                    getLocationInWindow(offsetInWindow);
21337                    offsetInWindow[0] -= startX;
21338                    offsetInWindow[1] -= startY;
21339                }
21340                return consumed[0] != 0 || consumed[1] != 0;
21341            } else if (offsetInWindow != null) {
21342                offsetInWindow[0] = 0;
21343                offsetInWindow[1] = 0;
21344            }
21345        }
21346        return false;
21347    }
21348
21349    /**
21350     * Dispatch a fling to a nested scrolling parent.
21351     *
21352     * <p>This method should be used to indicate that a nested scrolling child has detected
21353     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21354     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21355     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21356     * along a scrollable axis.</p>
21357     *
21358     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21359     * its own content, it can use this method to delegate the fling to its nested scrolling
21360     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21361     *
21362     * @param velocityX Horizontal fling velocity in pixels per second
21363     * @param velocityY Vertical fling velocity in pixels per second
21364     * @param consumed true if the child consumed the fling, false otherwise
21365     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21366     */
21367    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21368        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21369            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21370        }
21371        return false;
21372    }
21373
21374    /**
21375     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21376     *
21377     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21378     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21379     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21380     * before the child view consumes it. If this method returns <code>true</code>, a nested
21381     * parent view consumed the fling and this view should not scroll as a result.</p>
21382     *
21383     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21384     * the fling at a time. If a parent view consumed the fling this method will return false.
21385     * Custom view implementations should account for this in two ways:</p>
21386     *
21387     * <ul>
21388     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21389     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21390     *     position regardless.</li>
21391     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21392     *     even to settle back to a valid idle position.</li>
21393     * </ul>
21394     *
21395     * <p>Views should also not offer fling velocities to nested parent views along an axis
21396     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21397     * should not offer a horizontal fling velocity to its parents since scrolling along that
21398     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21399     *
21400     * @param velocityX Horizontal fling velocity in pixels per second
21401     * @param velocityY Vertical fling velocity in pixels per second
21402     * @return true if a nested scrolling parent consumed the fling
21403     */
21404    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21405        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21406            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21407        }
21408        return false;
21409    }
21410
21411    /**
21412     * Gets a scale factor that determines the distance the view should scroll
21413     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21414     * @return The vertical scroll scale factor.
21415     * @hide
21416     */
21417    protected float getVerticalScrollFactor() {
21418        if (mVerticalScrollFactor == 0) {
21419            TypedValue outValue = new TypedValue();
21420            if (!mContext.getTheme().resolveAttribute(
21421                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21422                throw new IllegalStateException(
21423                        "Expected theme to define listPreferredItemHeight.");
21424            }
21425            mVerticalScrollFactor = outValue.getDimension(
21426                    mContext.getResources().getDisplayMetrics());
21427        }
21428        return mVerticalScrollFactor;
21429    }
21430
21431    /**
21432     * Gets a scale factor that determines the distance the view should scroll
21433     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21434     * @return The horizontal scroll scale factor.
21435     * @hide
21436     */
21437    protected float getHorizontalScrollFactor() {
21438        // TODO: Should use something else.
21439        return getVerticalScrollFactor();
21440    }
21441
21442    /**
21443     * Return the value specifying the text direction or policy that was set with
21444     * {@link #setTextDirection(int)}.
21445     *
21446     * @return the defined text direction. It can be one of:
21447     *
21448     * {@link #TEXT_DIRECTION_INHERIT},
21449     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21450     * {@link #TEXT_DIRECTION_ANY_RTL},
21451     * {@link #TEXT_DIRECTION_LTR},
21452     * {@link #TEXT_DIRECTION_RTL},
21453     * {@link #TEXT_DIRECTION_LOCALE},
21454     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21455     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21456     *
21457     * @attr ref android.R.styleable#View_textDirection
21458     *
21459     * @hide
21460     */
21461    @ViewDebug.ExportedProperty(category = "text", mapping = {
21462            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21463            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21464            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21465            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21466            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21467            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21468            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21469            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21470    })
21471    public int getRawTextDirection() {
21472        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21473    }
21474
21475    /**
21476     * Set the text direction.
21477     *
21478     * @param textDirection the direction to set. Should be one of:
21479     *
21480     * {@link #TEXT_DIRECTION_INHERIT},
21481     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21482     * {@link #TEXT_DIRECTION_ANY_RTL},
21483     * {@link #TEXT_DIRECTION_LTR},
21484     * {@link #TEXT_DIRECTION_RTL},
21485     * {@link #TEXT_DIRECTION_LOCALE}
21486     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21487     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21488     *
21489     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21490     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21491     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21492     *
21493     * @attr ref android.R.styleable#View_textDirection
21494     */
21495    public void setTextDirection(int textDirection) {
21496        if (getRawTextDirection() != textDirection) {
21497            // Reset the current text direction and the resolved one
21498            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21499            resetResolvedTextDirection();
21500            // Set the new text direction
21501            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21502            // Do resolution
21503            resolveTextDirection();
21504            // Notify change
21505            onRtlPropertiesChanged(getLayoutDirection());
21506            // Refresh
21507            requestLayout();
21508            invalidate(true);
21509        }
21510    }
21511
21512    /**
21513     * Return the resolved text direction.
21514     *
21515     * @return the resolved text direction. Returns one of:
21516     *
21517     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21518     * {@link #TEXT_DIRECTION_ANY_RTL},
21519     * {@link #TEXT_DIRECTION_LTR},
21520     * {@link #TEXT_DIRECTION_RTL},
21521     * {@link #TEXT_DIRECTION_LOCALE},
21522     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21523     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21524     *
21525     * @attr ref android.R.styleable#View_textDirection
21526     */
21527    @ViewDebug.ExportedProperty(category = "text", mapping = {
21528            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21529            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21530            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21531            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21532            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21533            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21534            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21535            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21536    })
21537    public int getTextDirection() {
21538        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21539    }
21540
21541    /**
21542     * Resolve the text direction.
21543     *
21544     * @return true if resolution has been done, false otherwise.
21545     *
21546     * @hide
21547     */
21548    public boolean resolveTextDirection() {
21549        // Reset any previous text direction resolution
21550        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21551
21552        if (hasRtlSupport()) {
21553            // Set resolved text direction flag depending on text direction flag
21554            final int textDirection = getRawTextDirection();
21555            switch(textDirection) {
21556                case TEXT_DIRECTION_INHERIT:
21557                    if (!canResolveTextDirection()) {
21558                        // We cannot do the resolution if there is no parent, so use the default one
21559                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21560                        // Resolution will need to happen again later
21561                        return false;
21562                    }
21563
21564                    // Parent has not yet resolved, so we still return the default
21565                    try {
21566                        if (!mParent.isTextDirectionResolved()) {
21567                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21568                            // Resolution will need to happen again later
21569                            return false;
21570                        }
21571                    } catch (AbstractMethodError e) {
21572                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21573                                " does not fully implement ViewParent", e);
21574                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
21575                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21576                        return true;
21577                    }
21578
21579                    // Set current resolved direction to the same value as the parent's one
21580                    int parentResolvedDirection;
21581                    try {
21582                        parentResolvedDirection = mParent.getTextDirection();
21583                    } catch (AbstractMethodError e) {
21584                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21585                                " does not fully implement ViewParent", e);
21586                        parentResolvedDirection = TEXT_DIRECTION_LTR;
21587                    }
21588                    switch (parentResolvedDirection) {
21589                        case TEXT_DIRECTION_FIRST_STRONG:
21590                        case TEXT_DIRECTION_ANY_RTL:
21591                        case TEXT_DIRECTION_LTR:
21592                        case TEXT_DIRECTION_RTL:
21593                        case TEXT_DIRECTION_LOCALE:
21594                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
21595                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
21596                            mPrivateFlags2 |=
21597                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21598                            break;
21599                        default:
21600                            // Default resolved direction is "first strong" heuristic
21601                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21602                    }
21603                    break;
21604                case TEXT_DIRECTION_FIRST_STRONG:
21605                case TEXT_DIRECTION_ANY_RTL:
21606                case TEXT_DIRECTION_LTR:
21607                case TEXT_DIRECTION_RTL:
21608                case TEXT_DIRECTION_LOCALE:
21609                case TEXT_DIRECTION_FIRST_STRONG_LTR:
21610                case TEXT_DIRECTION_FIRST_STRONG_RTL:
21611                    // Resolved direction is the same as text direction
21612                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21613                    break;
21614                default:
21615                    // Default resolved direction is "first strong" heuristic
21616                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21617            }
21618        } else {
21619            // Default resolved direction is "first strong" heuristic
21620            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21621        }
21622
21623        // Set to resolved
21624        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
21625        return true;
21626    }
21627
21628    /**
21629     * Check if text direction resolution can be done.
21630     *
21631     * @return true if text direction resolution can be done otherwise return false.
21632     */
21633    public boolean canResolveTextDirection() {
21634        switch (getRawTextDirection()) {
21635            case TEXT_DIRECTION_INHERIT:
21636                if (mParent != null) {
21637                    try {
21638                        return mParent.canResolveTextDirection();
21639                    } catch (AbstractMethodError e) {
21640                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21641                                " does not fully implement ViewParent", e);
21642                    }
21643                }
21644                return false;
21645
21646            default:
21647                return true;
21648        }
21649    }
21650
21651    /**
21652     * Reset resolved text direction. Text direction will be resolved during a call to
21653     * {@link #onMeasure(int, int)}.
21654     *
21655     * @hide
21656     */
21657    public void resetResolvedTextDirection() {
21658        // Reset any previous text direction resolution
21659        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21660        // Set to default value
21661        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21662    }
21663
21664    /**
21665     * @return true if text direction is inherited.
21666     *
21667     * @hide
21668     */
21669    public boolean isTextDirectionInherited() {
21670        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
21671    }
21672
21673    /**
21674     * @return true if text direction is resolved.
21675     */
21676    public boolean isTextDirectionResolved() {
21677        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
21678    }
21679
21680    /**
21681     * Return the value specifying the text alignment or policy that was set with
21682     * {@link #setTextAlignment(int)}.
21683     *
21684     * @return the defined text alignment. It can be one of:
21685     *
21686     * {@link #TEXT_ALIGNMENT_INHERIT},
21687     * {@link #TEXT_ALIGNMENT_GRAVITY},
21688     * {@link #TEXT_ALIGNMENT_CENTER},
21689     * {@link #TEXT_ALIGNMENT_TEXT_START},
21690     * {@link #TEXT_ALIGNMENT_TEXT_END},
21691     * {@link #TEXT_ALIGNMENT_VIEW_START},
21692     * {@link #TEXT_ALIGNMENT_VIEW_END}
21693     *
21694     * @attr ref android.R.styleable#View_textAlignment
21695     *
21696     * @hide
21697     */
21698    @ViewDebug.ExportedProperty(category = "text", mapping = {
21699            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21700            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21701            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21702            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21703            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21704            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21705            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21706    })
21707    @TextAlignment
21708    public int getRawTextAlignment() {
21709        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
21710    }
21711
21712    /**
21713     * Set the text alignment.
21714     *
21715     * @param textAlignment The text alignment to set. Should be one of
21716     *
21717     * {@link #TEXT_ALIGNMENT_INHERIT},
21718     * {@link #TEXT_ALIGNMENT_GRAVITY},
21719     * {@link #TEXT_ALIGNMENT_CENTER},
21720     * {@link #TEXT_ALIGNMENT_TEXT_START},
21721     * {@link #TEXT_ALIGNMENT_TEXT_END},
21722     * {@link #TEXT_ALIGNMENT_VIEW_START},
21723     * {@link #TEXT_ALIGNMENT_VIEW_END}
21724     *
21725     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
21726     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
21727     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
21728     *
21729     * @attr ref android.R.styleable#View_textAlignment
21730     */
21731    public void setTextAlignment(@TextAlignment int textAlignment) {
21732        if (textAlignment != getRawTextAlignment()) {
21733            // Reset the current and resolved text alignment
21734            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
21735            resetResolvedTextAlignment();
21736            // Set the new text alignment
21737            mPrivateFlags2 |=
21738                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
21739            // Do resolution
21740            resolveTextAlignment();
21741            // Notify change
21742            onRtlPropertiesChanged(getLayoutDirection());
21743            // Refresh
21744            requestLayout();
21745            invalidate(true);
21746        }
21747    }
21748
21749    /**
21750     * Return the resolved text alignment.
21751     *
21752     * @return the resolved text alignment. Returns one of:
21753     *
21754     * {@link #TEXT_ALIGNMENT_GRAVITY},
21755     * {@link #TEXT_ALIGNMENT_CENTER},
21756     * {@link #TEXT_ALIGNMENT_TEXT_START},
21757     * {@link #TEXT_ALIGNMENT_TEXT_END},
21758     * {@link #TEXT_ALIGNMENT_VIEW_START},
21759     * {@link #TEXT_ALIGNMENT_VIEW_END}
21760     *
21761     * @attr ref android.R.styleable#View_textAlignment
21762     */
21763    @ViewDebug.ExportedProperty(category = "text", mapping = {
21764            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21765            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21766            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21767            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21768            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21769            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21770            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21771    })
21772    @TextAlignment
21773    public int getTextAlignment() {
21774        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
21775                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
21776    }
21777
21778    /**
21779     * Resolve the text alignment.
21780     *
21781     * @return true if resolution has been done, false otherwise.
21782     *
21783     * @hide
21784     */
21785    public boolean resolveTextAlignment() {
21786        // Reset any previous text alignment resolution
21787        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21788
21789        if (hasRtlSupport()) {
21790            // Set resolved text alignment flag depending on text alignment flag
21791            final int textAlignment = getRawTextAlignment();
21792            switch (textAlignment) {
21793                case TEXT_ALIGNMENT_INHERIT:
21794                    // Check if we can resolve the text alignment
21795                    if (!canResolveTextAlignment()) {
21796                        // We cannot do the resolution if there is no parent so use the default
21797                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21798                        // Resolution will need to happen again later
21799                        return false;
21800                    }
21801
21802                    // Parent has not yet resolved, so we still return the default
21803                    try {
21804                        if (!mParent.isTextAlignmentResolved()) {
21805                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21806                            // Resolution will need to happen again later
21807                            return false;
21808                        }
21809                    } catch (AbstractMethodError e) {
21810                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21811                                " does not fully implement ViewParent", e);
21812                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
21813                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21814                        return true;
21815                    }
21816
21817                    int parentResolvedTextAlignment;
21818                    try {
21819                        parentResolvedTextAlignment = mParent.getTextAlignment();
21820                    } catch (AbstractMethodError e) {
21821                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21822                                " does not fully implement ViewParent", e);
21823                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
21824                    }
21825                    switch (parentResolvedTextAlignment) {
21826                        case TEXT_ALIGNMENT_GRAVITY:
21827                        case TEXT_ALIGNMENT_TEXT_START:
21828                        case TEXT_ALIGNMENT_TEXT_END:
21829                        case TEXT_ALIGNMENT_CENTER:
21830                        case TEXT_ALIGNMENT_VIEW_START:
21831                        case TEXT_ALIGNMENT_VIEW_END:
21832                            // Resolved text alignment is the same as the parent resolved
21833                            // text alignment
21834                            mPrivateFlags2 |=
21835                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21836                            break;
21837                        default:
21838                            // Use default resolved text alignment
21839                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21840                    }
21841                    break;
21842                case TEXT_ALIGNMENT_GRAVITY:
21843                case TEXT_ALIGNMENT_TEXT_START:
21844                case TEXT_ALIGNMENT_TEXT_END:
21845                case TEXT_ALIGNMENT_CENTER:
21846                case TEXT_ALIGNMENT_VIEW_START:
21847                case TEXT_ALIGNMENT_VIEW_END:
21848                    // Resolved text alignment is the same as text alignment
21849                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21850                    break;
21851                default:
21852                    // Use default resolved text alignment
21853                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21854            }
21855        } else {
21856            // Use default resolved text alignment
21857            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21858        }
21859
21860        // Set the resolved
21861        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21862        return true;
21863    }
21864
21865    /**
21866     * Check if text alignment resolution can be done.
21867     *
21868     * @return true if text alignment resolution can be done otherwise return false.
21869     */
21870    public boolean canResolveTextAlignment() {
21871        switch (getRawTextAlignment()) {
21872            case TEXT_DIRECTION_INHERIT:
21873                if (mParent != null) {
21874                    try {
21875                        return mParent.canResolveTextAlignment();
21876                    } catch (AbstractMethodError e) {
21877                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21878                                " does not fully implement ViewParent", e);
21879                    }
21880                }
21881                return false;
21882
21883            default:
21884                return true;
21885        }
21886    }
21887
21888    /**
21889     * Reset resolved text alignment. Text alignment will be resolved during a call to
21890     * {@link #onMeasure(int, int)}.
21891     *
21892     * @hide
21893     */
21894    public void resetResolvedTextAlignment() {
21895        // Reset any previous text alignment resolution
21896        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21897        // Set to default
21898        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21899    }
21900
21901    /**
21902     * @return true if text alignment is inherited.
21903     *
21904     * @hide
21905     */
21906    public boolean isTextAlignmentInherited() {
21907        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
21908    }
21909
21910    /**
21911     * @return true if text alignment is resolved.
21912     */
21913    public boolean isTextAlignmentResolved() {
21914        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21915    }
21916
21917    /**
21918     * Generate a value suitable for use in {@link #setId(int)}.
21919     * This value will not collide with ID values generated at build time by aapt for R.id.
21920     *
21921     * @return a generated ID value
21922     */
21923    public static int generateViewId() {
21924        for (;;) {
21925            final int result = sNextGeneratedId.get();
21926            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
21927            int newValue = result + 1;
21928            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
21929            if (sNextGeneratedId.compareAndSet(result, newValue)) {
21930                return result;
21931            }
21932        }
21933    }
21934
21935    /**
21936     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
21937     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
21938     *                           a normal View or a ViewGroup with
21939     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
21940     * @hide
21941     */
21942    public void captureTransitioningViews(List<View> transitioningViews) {
21943        if (getVisibility() == View.VISIBLE) {
21944            transitioningViews.add(this);
21945        }
21946    }
21947
21948    /**
21949     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
21950     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
21951     * @hide
21952     */
21953    public void findNamedViews(Map<String, View> namedElements) {
21954        if (getVisibility() == VISIBLE || mGhostView != null) {
21955            String transitionName = getTransitionName();
21956            if (transitionName != null) {
21957                namedElements.put(transitionName, this);
21958            }
21959        }
21960    }
21961
21962    /**
21963     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
21964     * The default implementation does not care the location or event types, but some subclasses
21965     * may use it (such as WebViews).
21966     * @param event The MotionEvent from a mouse
21967     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
21968     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
21969     * @see PointerIcon
21970     */
21971    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
21972        final float x = event.getX(pointerIndex);
21973        final float y = event.getY(pointerIndex);
21974        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
21975            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
21976        }
21977        return mPointerIcon;
21978    }
21979
21980    /**
21981     * Set the pointer icon for the current view.
21982     * Passing {@code null} will restore the pointer icon to its default value.
21983     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
21984     */
21985    public void setPointerIcon(PointerIcon pointerIcon) {
21986        mPointerIcon = pointerIcon;
21987        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
21988            return;
21989        }
21990        try {
21991            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
21992        } catch (RemoteException e) {
21993        }
21994    }
21995
21996    /**
21997     * Gets the pointer icon for the current view.
21998     */
21999    public PointerIcon getPointerIcon() {
22000        return mPointerIcon;
22001    }
22002
22003    //
22004    // Properties
22005    //
22006    /**
22007     * A Property wrapper around the <code>alpha</code> functionality handled by the
22008     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
22009     */
22010    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
22011        @Override
22012        public void setValue(View object, float value) {
22013            object.setAlpha(value);
22014        }
22015
22016        @Override
22017        public Float get(View object) {
22018            return object.getAlpha();
22019        }
22020    };
22021
22022    /**
22023     * A Property wrapper around the <code>translationX</code> functionality handled by the
22024     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
22025     */
22026    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
22027        @Override
22028        public void setValue(View object, float value) {
22029            object.setTranslationX(value);
22030        }
22031
22032                @Override
22033        public Float get(View object) {
22034            return object.getTranslationX();
22035        }
22036    };
22037
22038    /**
22039     * A Property wrapper around the <code>translationY</code> functionality handled by the
22040     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
22041     */
22042    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
22043        @Override
22044        public void setValue(View object, float value) {
22045            object.setTranslationY(value);
22046        }
22047
22048        @Override
22049        public Float get(View object) {
22050            return object.getTranslationY();
22051        }
22052    };
22053
22054    /**
22055     * A Property wrapper around the <code>translationZ</code> functionality handled by the
22056     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
22057     */
22058    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
22059        @Override
22060        public void setValue(View object, float value) {
22061            object.setTranslationZ(value);
22062        }
22063
22064        @Override
22065        public Float get(View object) {
22066            return object.getTranslationZ();
22067        }
22068    };
22069
22070    /**
22071     * A Property wrapper around the <code>x</code> functionality handled by the
22072     * {@link View#setX(float)} and {@link View#getX()} methods.
22073     */
22074    public static final Property<View, Float> X = new FloatProperty<View>("x") {
22075        @Override
22076        public void setValue(View object, float value) {
22077            object.setX(value);
22078        }
22079
22080        @Override
22081        public Float get(View object) {
22082            return object.getX();
22083        }
22084    };
22085
22086    /**
22087     * A Property wrapper around the <code>y</code> functionality handled by the
22088     * {@link View#setY(float)} and {@link View#getY()} methods.
22089     */
22090    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
22091        @Override
22092        public void setValue(View object, float value) {
22093            object.setY(value);
22094        }
22095
22096        @Override
22097        public Float get(View object) {
22098            return object.getY();
22099        }
22100    };
22101
22102    /**
22103     * A Property wrapper around the <code>z</code> functionality handled by the
22104     * {@link View#setZ(float)} and {@link View#getZ()} methods.
22105     */
22106    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
22107        @Override
22108        public void setValue(View object, float value) {
22109            object.setZ(value);
22110        }
22111
22112        @Override
22113        public Float get(View object) {
22114            return object.getZ();
22115        }
22116    };
22117
22118    /**
22119     * A Property wrapper around the <code>rotation</code> functionality handled by the
22120     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
22121     */
22122    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
22123        @Override
22124        public void setValue(View object, float value) {
22125            object.setRotation(value);
22126        }
22127
22128        @Override
22129        public Float get(View object) {
22130            return object.getRotation();
22131        }
22132    };
22133
22134    /**
22135     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22136     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22137     */
22138    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22139        @Override
22140        public void setValue(View object, float value) {
22141            object.setRotationX(value);
22142        }
22143
22144        @Override
22145        public Float get(View object) {
22146            return object.getRotationX();
22147        }
22148    };
22149
22150    /**
22151     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22152     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22153     */
22154    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22155        @Override
22156        public void setValue(View object, float value) {
22157            object.setRotationY(value);
22158        }
22159
22160        @Override
22161        public Float get(View object) {
22162            return object.getRotationY();
22163        }
22164    };
22165
22166    /**
22167     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22168     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22169     */
22170    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22171        @Override
22172        public void setValue(View object, float value) {
22173            object.setScaleX(value);
22174        }
22175
22176        @Override
22177        public Float get(View object) {
22178            return object.getScaleX();
22179        }
22180    };
22181
22182    /**
22183     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22184     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22185     */
22186    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22187        @Override
22188        public void setValue(View object, float value) {
22189            object.setScaleY(value);
22190        }
22191
22192        @Override
22193        public Float get(View object) {
22194            return object.getScaleY();
22195        }
22196    };
22197
22198    /**
22199     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22200     * Each MeasureSpec represents a requirement for either the width or the height.
22201     * A MeasureSpec is comprised of a size and a mode. There are three possible
22202     * modes:
22203     * <dl>
22204     * <dt>UNSPECIFIED</dt>
22205     * <dd>
22206     * The parent has not imposed any constraint on the child. It can be whatever size
22207     * it wants.
22208     * </dd>
22209     *
22210     * <dt>EXACTLY</dt>
22211     * <dd>
22212     * The parent has determined an exact size for the child. The child is going to be
22213     * given those bounds regardless of how big it wants to be.
22214     * </dd>
22215     *
22216     * <dt>AT_MOST</dt>
22217     * <dd>
22218     * The child can be as large as it wants up to the specified size.
22219     * </dd>
22220     * </dl>
22221     *
22222     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22223     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22224     */
22225    public static class MeasureSpec {
22226        private static final int MODE_SHIFT = 30;
22227        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22228
22229        /** @hide */
22230        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22231        @Retention(RetentionPolicy.SOURCE)
22232        public @interface MeasureSpecMode {}
22233
22234        /**
22235         * Measure specification mode: The parent has not imposed any constraint
22236         * on the child. It can be whatever size it wants.
22237         */
22238        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22239
22240        /**
22241         * Measure specification mode: The parent has determined an exact size
22242         * for the child. The child is going to be given those bounds regardless
22243         * of how big it wants to be.
22244         */
22245        public static final int EXACTLY     = 1 << MODE_SHIFT;
22246
22247        /**
22248         * Measure specification mode: The child can be as large as it wants up
22249         * to the specified size.
22250         */
22251        public static final int AT_MOST     = 2 << MODE_SHIFT;
22252
22253        /**
22254         * Creates a measure specification based on the supplied size and mode.
22255         *
22256         * The mode must always be one of the following:
22257         * <ul>
22258         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22259         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22260         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22261         * </ul>
22262         *
22263         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22264         * implementation was such that the order of arguments did not matter
22265         * and overflow in either value could impact the resulting MeasureSpec.
22266         * {@link android.widget.RelativeLayout} was affected by this bug.
22267         * Apps targeting API levels greater than 17 will get the fixed, more strict
22268         * behavior.</p>
22269         *
22270         * @param size the size of the measure specification
22271         * @param mode the mode of the measure specification
22272         * @return the measure specification based on size and mode
22273         */
22274        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22275                                          @MeasureSpecMode int mode) {
22276            if (sUseBrokenMakeMeasureSpec) {
22277                return size + mode;
22278            } else {
22279                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22280            }
22281        }
22282
22283        /**
22284         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22285         * will automatically get a size of 0. Older apps expect this.
22286         *
22287         * @hide internal use only for compatibility with system widgets and older apps
22288         */
22289        public static int makeSafeMeasureSpec(int size, int mode) {
22290            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22291                return 0;
22292            }
22293            return makeMeasureSpec(size, mode);
22294        }
22295
22296        /**
22297         * Extracts the mode from the supplied measure specification.
22298         *
22299         * @param measureSpec the measure specification to extract the mode from
22300         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22301         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22302         *         {@link android.view.View.MeasureSpec#EXACTLY}
22303         */
22304        @MeasureSpecMode
22305        public static int getMode(int measureSpec) {
22306            //noinspection ResourceType
22307            return (measureSpec & MODE_MASK);
22308        }
22309
22310        /**
22311         * Extracts the size from the supplied measure specification.
22312         *
22313         * @param measureSpec the measure specification to extract the size from
22314         * @return the size in pixels defined in the supplied measure specification
22315         */
22316        public static int getSize(int measureSpec) {
22317            return (measureSpec & ~MODE_MASK);
22318        }
22319
22320        static int adjust(int measureSpec, int delta) {
22321            final int mode = getMode(measureSpec);
22322            int size = getSize(measureSpec);
22323            if (mode == UNSPECIFIED) {
22324                // No need to adjust size for UNSPECIFIED mode.
22325                return makeMeasureSpec(size, UNSPECIFIED);
22326            }
22327            size += delta;
22328            if (size < 0) {
22329                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22330                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22331                size = 0;
22332            }
22333            return makeMeasureSpec(size, mode);
22334        }
22335
22336        /**
22337         * Returns a String representation of the specified measure
22338         * specification.
22339         *
22340         * @param measureSpec the measure specification to convert to a String
22341         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22342         */
22343        public static String toString(int measureSpec) {
22344            int mode = getMode(measureSpec);
22345            int size = getSize(measureSpec);
22346
22347            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22348
22349            if (mode == UNSPECIFIED)
22350                sb.append("UNSPECIFIED ");
22351            else if (mode == EXACTLY)
22352                sb.append("EXACTLY ");
22353            else if (mode == AT_MOST)
22354                sb.append("AT_MOST ");
22355            else
22356                sb.append(mode).append(" ");
22357
22358            sb.append(size);
22359            return sb.toString();
22360        }
22361    }
22362
22363    private final class CheckForLongPress implements Runnable {
22364        private int mOriginalWindowAttachCount;
22365        private float mX;
22366        private float mY;
22367
22368        @Override
22369        public void run() {
22370            if (isPressed() && (mParent != null)
22371                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22372                if (performLongClick(mX, mY)) {
22373                    mHasPerformedLongPress = true;
22374                }
22375            }
22376        }
22377
22378        public void setAnchor(float x, float y) {
22379            mX = x;
22380            mY = y;
22381        }
22382
22383        public void rememberWindowAttachCount() {
22384            mOriginalWindowAttachCount = mWindowAttachCount;
22385        }
22386    }
22387
22388    private final class CheckForTap implements Runnable {
22389        public float x;
22390        public float y;
22391
22392        @Override
22393        public void run() {
22394            mPrivateFlags &= ~PFLAG_PREPRESSED;
22395            setPressed(true, x, y);
22396            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22397        }
22398    }
22399
22400    private final class PerformClick implements Runnable {
22401        @Override
22402        public void run() {
22403            performClick();
22404        }
22405    }
22406
22407    /**
22408     * This method returns a ViewPropertyAnimator object, which can be used to animate
22409     * specific properties on this View.
22410     *
22411     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22412     */
22413    public ViewPropertyAnimator animate() {
22414        if (mAnimator == null) {
22415            mAnimator = new ViewPropertyAnimator(this);
22416        }
22417        return mAnimator;
22418    }
22419
22420    /**
22421     * Sets the name of the View to be used to identify Views in Transitions.
22422     * Names should be unique in the View hierarchy.
22423     *
22424     * @param transitionName The name of the View to uniquely identify it for Transitions.
22425     */
22426    public final void setTransitionName(String transitionName) {
22427        mTransitionName = transitionName;
22428    }
22429
22430    /**
22431     * Returns the name of the View to be used to identify Views in Transitions.
22432     * Names should be unique in the View hierarchy.
22433     *
22434     * <p>This returns null if the View has not been given a name.</p>
22435     *
22436     * @return The name used of the View to be used to identify Views in Transitions or null
22437     * if no name has been given.
22438     */
22439    @ViewDebug.ExportedProperty
22440    public String getTransitionName() {
22441        return mTransitionName;
22442    }
22443
22444    /**
22445     * @hide
22446     */
22447    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22448        // Do nothing.
22449    }
22450
22451    /**
22452     * Interface definition for a callback to be invoked when a hardware key event is
22453     * dispatched to this view. The callback will be invoked before the key event is
22454     * given to the view. This is only useful for hardware keyboards; a software input
22455     * method has no obligation to trigger this listener.
22456     */
22457    public interface OnKeyListener {
22458        /**
22459         * Called when a hardware key is dispatched to a view. This allows listeners to
22460         * get a chance to respond before the target view.
22461         * <p>Key presses in software keyboards will generally NOT trigger this method,
22462         * although some may elect to do so in some situations. Do not assume a
22463         * software input method has to be key-based; even if it is, it may use key presses
22464         * in a different way than you expect, so there is no way to reliably catch soft
22465         * input key presses.
22466         *
22467         * @param v The view the key has been dispatched to.
22468         * @param keyCode The code for the physical key that was pressed
22469         * @param event The KeyEvent object containing full information about
22470         *        the event.
22471         * @return True if the listener has consumed the event, false otherwise.
22472         */
22473        boolean onKey(View v, int keyCode, KeyEvent event);
22474    }
22475
22476    /**
22477     * Interface definition for a callback to be invoked when a touch event is
22478     * dispatched to this view. The callback will be invoked before the touch
22479     * event is given to the view.
22480     */
22481    public interface OnTouchListener {
22482        /**
22483         * Called when a touch event is dispatched to a view. This allows listeners to
22484         * get a chance to respond before the target view.
22485         *
22486         * @param v The view the touch event has been dispatched to.
22487         * @param event The MotionEvent object containing full information about
22488         *        the event.
22489         * @return True if the listener has consumed the event, false otherwise.
22490         */
22491        boolean onTouch(View v, MotionEvent event);
22492    }
22493
22494    /**
22495     * Interface definition for a callback to be invoked when a hover event is
22496     * dispatched to this view. The callback will be invoked before the hover
22497     * event is given to the view.
22498     */
22499    public interface OnHoverListener {
22500        /**
22501         * Called when a hover event is dispatched to a view. This allows listeners to
22502         * get a chance to respond before the target view.
22503         *
22504         * @param v The view the hover event has been dispatched to.
22505         * @param event The MotionEvent object containing full information about
22506         *        the event.
22507         * @return True if the listener has consumed the event, false otherwise.
22508         */
22509        boolean onHover(View v, MotionEvent event);
22510    }
22511
22512    /**
22513     * Interface definition for a callback to be invoked when a generic motion event is
22514     * dispatched to this view. The callback will be invoked before the generic motion
22515     * event is given to the view.
22516     */
22517    public interface OnGenericMotionListener {
22518        /**
22519         * Called when a generic motion event is dispatched to a view. This allows listeners to
22520         * get a chance to respond before the target view.
22521         *
22522         * @param v The view the generic motion event has been dispatched to.
22523         * @param event The MotionEvent object containing full information about
22524         *        the event.
22525         * @return True if the listener has consumed the event, false otherwise.
22526         */
22527        boolean onGenericMotion(View v, MotionEvent event);
22528    }
22529
22530    /**
22531     * Interface definition for a callback to be invoked when a view has been clicked and held.
22532     */
22533    public interface OnLongClickListener {
22534        /**
22535         * Called when a view has been clicked and held.
22536         *
22537         * @param v The view that was clicked and held.
22538         *
22539         * @return true if the callback consumed the long click, false otherwise.
22540         */
22541        boolean onLongClick(View v);
22542    }
22543
22544    /**
22545     * Interface definition for a callback to be invoked when a drag is being dispatched
22546     * to this view.  The callback will be invoked before the hosting view's own
22547     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22548     * onDrag(event) behavior, it should return 'false' from this callback.
22549     *
22550     * <div class="special reference">
22551     * <h3>Developer Guides</h3>
22552     * <p>For a guide to implementing drag and drop features, read the
22553     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22554     * </div>
22555     */
22556    public interface OnDragListener {
22557        /**
22558         * Called when a drag event is dispatched to a view. This allows listeners
22559         * to get a chance to override base View behavior.
22560         *
22561         * @param v The View that received the drag event.
22562         * @param event The {@link android.view.DragEvent} object for the drag event.
22563         * @return {@code true} if the drag event was handled successfully, or {@code false}
22564         * if the drag event was not handled. Note that {@code false} will trigger the View
22565         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
22566         */
22567        boolean onDrag(View v, DragEvent event);
22568    }
22569
22570    /**
22571     * Interface definition for a callback to be invoked when the focus state of
22572     * a view changed.
22573     */
22574    public interface OnFocusChangeListener {
22575        /**
22576         * Called when the focus state of a view has changed.
22577         *
22578         * @param v The view whose state has changed.
22579         * @param hasFocus The new focus state of v.
22580         */
22581        void onFocusChange(View v, boolean hasFocus);
22582    }
22583
22584    /**
22585     * Interface definition for a callback to be invoked when a view is clicked.
22586     */
22587    public interface OnClickListener {
22588        /**
22589         * Called when a view has been clicked.
22590         *
22591         * @param v The view that was clicked.
22592         */
22593        void onClick(View v);
22594    }
22595
22596    /**
22597     * Interface definition for a callback to be invoked when a view is context clicked.
22598     */
22599    public interface OnContextClickListener {
22600        /**
22601         * Called when a view is context clicked.
22602         *
22603         * @param v The view that has been context clicked.
22604         * @return true if the callback consumed the context click, false otherwise.
22605         */
22606        boolean onContextClick(View v);
22607    }
22608
22609    /**
22610     * Interface definition for a callback to be invoked when the context menu
22611     * for this view is being built.
22612     */
22613    public interface OnCreateContextMenuListener {
22614        /**
22615         * Called when the context menu for this view is being built. It is not
22616         * safe to hold onto the menu after this method returns.
22617         *
22618         * @param menu The context menu that is being built
22619         * @param v The view for which the context menu is being built
22620         * @param menuInfo Extra information about the item for which the
22621         *            context menu should be shown. This information will vary
22622         *            depending on the class of v.
22623         */
22624        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
22625    }
22626
22627    /**
22628     * Interface definition for a callback to be invoked when the status bar changes
22629     * visibility.  This reports <strong>global</strong> changes to the system UI
22630     * state, not what the application is requesting.
22631     *
22632     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
22633     */
22634    public interface OnSystemUiVisibilityChangeListener {
22635        /**
22636         * Called when the status bar changes visibility because of a call to
22637         * {@link View#setSystemUiVisibility(int)}.
22638         *
22639         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22640         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
22641         * This tells you the <strong>global</strong> state of these UI visibility
22642         * flags, not what your app is currently applying.
22643         */
22644        public void onSystemUiVisibilityChange(int visibility);
22645    }
22646
22647    /**
22648     * Interface definition for a callback to be invoked when this view is attached
22649     * or detached from its window.
22650     */
22651    public interface OnAttachStateChangeListener {
22652        /**
22653         * Called when the view is attached to a window.
22654         * @param v The view that was attached
22655         */
22656        public void onViewAttachedToWindow(View v);
22657        /**
22658         * Called when the view is detached from a window.
22659         * @param v The view that was detached
22660         */
22661        public void onViewDetachedFromWindow(View v);
22662    }
22663
22664    /**
22665     * Listener for applying window insets on a view in a custom way.
22666     *
22667     * <p>Apps may choose to implement this interface if they want to apply custom policy
22668     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
22669     * is set, its
22670     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
22671     * method will be called instead of the View's own
22672     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
22673     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
22674     * the View's normal behavior as part of its own.</p>
22675     */
22676    public interface OnApplyWindowInsetsListener {
22677        /**
22678         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
22679         * on a View, this listener method will be called instead of the view's own
22680         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
22681         *
22682         * @param v The view applying window insets
22683         * @param insets The insets to apply
22684         * @return The insets supplied, minus any insets that were consumed
22685         */
22686        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
22687    }
22688
22689    private final class UnsetPressedState implements Runnable {
22690        @Override
22691        public void run() {
22692            setPressed(false);
22693        }
22694    }
22695
22696    /**
22697     * Base class for derived classes that want to save and restore their own
22698     * state in {@link android.view.View#onSaveInstanceState()}.
22699     */
22700    public static class BaseSavedState extends AbsSavedState {
22701        String mStartActivityRequestWhoSaved;
22702
22703        /**
22704         * Constructor used when reading from a parcel. Reads the state of the superclass.
22705         *
22706         * @param source parcel to read from
22707         */
22708        public BaseSavedState(Parcel source) {
22709            this(source, null);
22710        }
22711
22712        /**
22713         * Constructor used when reading from a parcel using a given class loader.
22714         * Reads the state of the superclass.
22715         *
22716         * @param source parcel to read from
22717         * @param loader ClassLoader to use for reading
22718         */
22719        public BaseSavedState(Parcel source, ClassLoader loader) {
22720            super(source, loader);
22721            mStartActivityRequestWhoSaved = source.readString();
22722        }
22723
22724        /**
22725         * Constructor called by derived classes when creating their SavedState objects
22726         *
22727         * @param superState The state of the superclass of this view
22728         */
22729        public BaseSavedState(Parcelable superState) {
22730            super(superState);
22731        }
22732
22733        @Override
22734        public void writeToParcel(Parcel out, int flags) {
22735            super.writeToParcel(out, flags);
22736            out.writeString(mStartActivityRequestWhoSaved);
22737        }
22738
22739        public static final Parcelable.Creator<BaseSavedState> CREATOR
22740                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
22741            @Override
22742            public BaseSavedState createFromParcel(Parcel in) {
22743                return new BaseSavedState(in);
22744            }
22745
22746            @Override
22747            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
22748                return new BaseSavedState(in, loader);
22749            }
22750
22751            @Override
22752            public BaseSavedState[] newArray(int size) {
22753                return new BaseSavedState[size];
22754            }
22755        };
22756    }
22757
22758    /**
22759     * A set of information given to a view when it is attached to its parent
22760     * window.
22761     */
22762    final static class AttachInfo {
22763        interface Callbacks {
22764            void playSoundEffect(int effectId);
22765            boolean performHapticFeedback(int effectId, boolean always);
22766        }
22767
22768        /**
22769         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
22770         * to a Handler. This class contains the target (View) to invalidate and
22771         * the coordinates of the dirty rectangle.
22772         *
22773         * For performance purposes, this class also implements a pool of up to
22774         * POOL_LIMIT objects that get reused. This reduces memory allocations
22775         * whenever possible.
22776         */
22777        static class InvalidateInfo {
22778            private static final int POOL_LIMIT = 10;
22779
22780            private static final SynchronizedPool<InvalidateInfo> sPool =
22781                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
22782
22783            View target;
22784
22785            int left;
22786            int top;
22787            int right;
22788            int bottom;
22789
22790            public static InvalidateInfo obtain() {
22791                InvalidateInfo instance = sPool.acquire();
22792                return (instance != null) ? instance : new InvalidateInfo();
22793            }
22794
22795            public void recycle() {
22796                target = null;
22797                sPool.release(this);
22798            }
22799        }
22800
22801        final IWindowSession mSession;
22802
22803        final IWindow mWindow;
22804
22805        final IBinder mWindowToken;
22806
22807        final Display mDisplay;
22808
22809        final Callbacks mRootCallbacks;
22810
22811        IWindowId mIWindowId;
22812        WindowId mWindowId;
22813
22814        /**
22815         * The top view of the hierarchy.
22816         */
22817        View mRootView;
22818
22819        IBinder mPanelParentWindowToken;
22820
22821        boolean mHardwareAccelerated;
22822        boolean mHardwareAccelerationRequested;
22823        ThreadedRenderer mHardwareRenderer;
22824        List<RenderNode> mPendingAnimatingRenderNodes;
22825
22826        /**
22827         * The state of the display to which the window is attached, as reported
22828         * by {@link Display#getState()}.  Note that the display state constants
22829         * declared by {@link Display} do not exactly line up with the screen state
22830         * constants declared by {@link View} (there are more display states than
22831         * screen states).
22832         */
22833        int mDisplayState = Display.STATE_UNKNOWN;
22834
22835        /**
22836         * Scale factor used by the compatibility mode
22837         */
22838        float mApplicationScale;
22839
22840        /**
22841         * Indicates whether the application is in compatibility mode
22842         */
22843        boolean mScalingRequired;
22844
22845        /**
22846         * Left position of this view's window
22847         */
22848        int mWindowLeft;
22849
22850        /**
22851         * Top position of this view's window
22852         */
22853        int mWindowTop;
22854
22855        /**
22856         * Indicates whether views need to use 32-bit drawing caches
22857         */
22858        boolean mUse32BitDrawingCache;
22859
22860        /**
22861         * For windows that are full-screen but using insets to layout inside
22862         * of the screen areas, these are the current insets to appear inside
22863         * the overscan area of the display.
22864         */
22865        final Rect mOverscanInsets = new Rect();
22866
22867        /**
22868         * For windows that are full-screen but using insets to layout inside
22869         * of the screen decorations, these are the current insets for the
22870         * content of the window.
22871         */
22872        final Rect mContentInsets = new Rect();
22873
22874        /**
22875         * For windows that are full-screen but using insets to layout inside
22876         * of the screen decorations, these are the current insets for the
22877         * actual visible parts of the window.
22878         */
22879        final Rect mVisibleInsets = new Rect();
22880
22881        /**
22882         * For windows that are full-screen but using insets to layout inside
22883         * of the screen decorations, these are the current insets for the
22884         * stable system windows.
22885         */
22886        final Rect mStableInsets = new Rect();
22887
22888        /**
22889         * For windows that include areas that are not covered by real surface these are the outsets
22890         * for real surface.
22891         */
22892        final Rect mOutsets = new Rect();
22893
22894        /**
22895         * In multi-window we force show the navigation bar. Because we don't want that the surface
22896         * size changes in this mode, we instead have a flag whether the navigation bar size should
22897         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
22898         */
22899        boolean mAlwaysConsumeNavBar;
22900
22901        /**
22902         * The internal insets given by this window.  This value is
22903         * supplied by the client (through
22904         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
22905         * be given to the window manager when changed to be used in laying
22906         * out windows behind it.
22907         */
22908        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
22909                = new ViewTreeObserver.InternalInsetsInfo();
22910
22911        /**
22912         * Set to true when mGivenInternalInsets is non-empty.
22913         */
22914        boolean mHasNonEmptyGivenInternalInsets;
22915
22916        /**
22917         * All views in the window's hierarchy that serve as scroll containers,
22918         * used to determine if the window can be resized or must be panned
22919         * to adjust for a soft input area.
22920         */
22921        final ArrayList<View> mScrollContainers = new ArrayList<View>();
22922
22923        final KeyEvent.DispatcherState mKeyDispatchState
22924                = new KeyEvent.DispatcherState();
22925
22926        /**
22927         * Indicates whether the view's window currently has the focus.
22928         */
22929        boolean mHasWindowFocus;
22930
22931        /**
22932         * The current visibility of the window.
22933         */
22934        int mWindowVisibility;
22935
22936        /**
22937         * Indicates the time at which drawing started to occur.
22938         */
22939        long mDrawingTime;
22940
22941        /**
22942         * Indicates whether or not ignoring the DIRTY_MASK flags.
22943         */
22944        boolean mIgnoreDirtyState;
22945
22946        /**
22947         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
22948         * to avoid clearing that flag prematurely.
22949         */
22950        boolean mSetIgnoreDirtyState = false;
22951
22952        /**
22953         * Indicates whether the view's window is currently in touch mode.
22954         */
22955        boolean mInTouchMode;
22956
22957        /**
22958         * Indicates whether the view has requested unbuffered input dispatching for the current
22959         * event stream.
22960         */
22961        boolean mUnbufferedDispatchRequested;
22962
22963        /**
22964         * Indicates that ViewAncestor should trigger a global layout change
22965         * the next time it performs a traversal
22966         */
22967        boolean mRecomputeGlobalAttributes;
22968
22969        /**
22970         * Always report new attributes at next traversal.
22971         */
22972        boolean mForceReportNewAttributes;
22973
22974        /**
22975         * Set during a traveral if any views want to keep the screen on.
22976         */
22977        boolean mKeepScreenOn;
22978
22979        /**
22980         * Set during a traveral if the light center needs to be updated.
22981         */
22982        boolean mNeedsUpdateLightCenter;
22983
22984        /**
22985         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
22986         */
22987        int mSystemUiVisibility;
22988
22989        /**
22990         * Hack to force certain system UI visibility flags to be cleared.
22991         */
22992        int mDisabledSystemUiVisibility;
22993
22994        /**
22995         * Last global system UI visibility reported by the window manager.
22996         */
22997        int mGlobalSystemUiVisibility = -1;
22998
22999        /**
23000         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
23001         * attached.
23002         */
23003        boolean mHasSystemUiListeners;
23004
23005        /**
23006         * Set if the window has requested to extend into the overscan region
23007         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
23008         */
23009        boolean mOverscanRequested;
23010
23011        /**
23012         * Set if the visibility of any views has changed.
23013         */
23014        boolean mViewVisibilityChanged;
23015
23016        /**
23017         * Set to true if a view has been scrolled.
23018         */
23019        boolean mViewScrollChanged;
23020
23021        /**
23022         * Set to true if high contrast mode enabled
23023         */
23024        boolean mHighContrastText;
23025
23026        /**
23027         * Set to true if a pointer event is currently being handled.
23028         */
23029        boolean mHandlingPointerEvent;
23030
23031        /**
23032         * Global to the view hierarchy used as a temporary for dealing with
23033         * x/y points in the transparent region computations.
23034         */
23035        final int[] mTransparentLocation = new int[2];
23036
23037        /**
23038         * Global to the view hierarchy used as a temporary for dealing with
23039         * x/y points in the ViewGroup.invalidateChild implementation.
23040         */
23041        final int[] mInvalidateChildLocation = new int[2];
23042
23043        /**
23044         * Global to the view hierarchy used as a temporary for dealing with
23045         * computing absolute on-screen location.
23046         */
23047        final int[] mTmpLocation = new int[2];
23048
23049        /**
23050         * Global to the view hierarchy used as a temporary for dealing with
23051         * x/y location when view is transformed.
23052         */
23053        final float[] mTmpTransformLocation = new float[2];
23054
23055        /**
23056         * The view tree observer used to dispatch global events like
23057         * layout, pre-draw, touch mode change, etc.
23058         */
23059        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
23060
23061        /**
23062         * A Canvas used by the view hierarchy to perform bitmap caching.
23063         */
23064        Canvas mCanvas;
23065
23066        /**
23067         * The view root impl.
23068         */
23069        final ViewRootImpl mViewRootImpl;
23070
23071        /**
23072         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
23073         * handler can be used to pump events in the UI events queue.
23074         */
23075        final Handler mHandler;
23076
23077        /**
23078         * Temporary for use in computing invalidate rectangles while
23079         * calling up the hierarchy.
23080         */
23081        final Rect mTmpInvalRect = new Rect();
23082
23083        /**
23084         * Temporary for use in computing hit areas with transformed views
23085         */
23086        final RectF mTmpTransformRect = new RectF();
23087
23088        /**
23089         * Temporary for use in computing hit areas with transformed views
23090         */
23091        final RectF mTmpTransformRect1 = new RectF();
23092
23093        /**
23094         * Temporary list of rectanges.
23095         */
23096        final List<RectF> mTmpRectList = new ArrayList<>();
23097
23098        /**
23099         * Temporary for use in transforming invalidation rect
23100         */
23101        final Matrix mTmpMatrix = new Matrix();
23102
23103        /**
23104         * Temporary for use in transforming invalidation rect
23105         */
23106        final Transformation mTmpTransformation = new Transformation();
23107
23108        /**
23109         * Temporary for use in querying outlines from OutlineProviders
23110         */
23111        final Outline mTmpOutline = new Outline();
23112
23113        /**
23114         * Temporary list for use in collecting focusable descendents of a view.
23115         */
23116        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
23117
23118        /**
23119         * The id of the window for accessibility purposes.
23120         */
23121        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
23122
23123        /**
23124         * Flags related to accessibility processing.
23125         *
23126         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
23127         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
23128         */
23129        int mAccessibilityFetchFlags;
23130
23131        /**
23132         * The drawable for highlighting accessibility focus.
23133         */
23134        Drawable mAccessibilityFocusDrawable;
23135
23136        /**
23137         * Show where the margins, bounds and layout bounds are for each view.
23138         */
23139        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23140
23141        /**
23142         * Point used to compute visible regions.
23143         */
23144        final Point mPoint = new Point();
23145
23146        /**
23147         * Used to track which View originated a requestLayout() call, used when
23148         * requestLayout() is called during layout.
23149         */
23150        View mViewRequestingLayout;
23151
23152        /**
23153         * Used to track views that need (at least) a partial relayout at their current size
23154         * during the next traversal.
23155         */
23156        List<View> mPartialLayoutViews = new ArrayList<>();
23157
23158        /**
23159         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23160         * modification. Lazily assigned during ViewRootImpl layout.
23161         */
23162        List<View> mEmptyPartialLayoutViews;
23163
23164        /**
23165         * Used to track the identity of the current drag operation.
23166         */
23167        IBinder mDragToken;
23168
23169        /**
23170         * The drag shadow surface for the current drag operation.
23171         */
23172        public Surface mDragSurface;
23173
23174        /**
23175         * Creates a new set of attachment information with the specified
23176         * events handler and thread.
23177         *
23178         * @param handler the events handler the view must use
23179         */
23180        AttachInfo(IWindowSession session, IWindow window, Display display,
23181                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
23182            mSession = session;
23183            mWindow = window;
23184            mWindowToken = window.asBinder();
23185            mDisplay = display;
23186            mViewRootImpl = viewRootImpl;
23187            mHandler = handler;
23188            mRootCallbacks = effectPlayer;
23189        }
23190    }
23191
23192    /**
23193     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23194     * is supported. This avoids keeping too many unused fields in most
23195     * instances of View.</p>
23196     */
23197    private static class ScrollabilityCache implements Runnable {
23198
23199        /**
23200         * Scrollbars are not visible
23201         */
23202        public static final int OFF = 0;
23203
23204        /**
23205         * Scrollbars are visible
23206         */
23207        public static final int ON = 1;
23208
23209        /**
23210         * Scrollbars are fading away
23211         */
23212        public static final int FADING = 2;
23213
23214        public boolean fadeScrollBars;
23215
23216        public int fadingEdgeLength;
23217        public int scrollBarDefaultDelayBeforeFade;
23218        public int scrollBarFadeDuration;
23219
23220        public int scrollBarSize;
23221        public ScrollBarDrawable scrollBar;
23222        public float[] interpolatorValues;
23223        public View host;
23224
23225        public final Paint paint;
23226        public final Matrix matrix;
23227        public Shader shader;
23228
23229        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23230
23231        private static final float[] OPAQUE = { 255 };
23232        private static final float[] TRANSPARENT = { 0.0f };
23233
23234        /**
23235         * When fading should start. This time moves into the future every time
23236         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23237         */
23238        public long fadeStartTime;
23239
23240
23241        /**
23242         * The current state of the scrollbars: ON, OFF, or FADING
23243         */
23244        public int state = OFF;
23245
23246        private int mLastColor;
23247
23248        public final Rect mScrollBarBounds = new Rect();
23249
23250        public static final int NOT_DRAGGING = 0;
23251        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23252        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23253        public int mScrollBarDraggingState = NOT_DRAGGING;
23254
23255        public float mScrollBarDraggingPos = 0;
23256
23257        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23258            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23259            scrollBarSize = configuration.getScaledScrollBarSize();
23260            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23261            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23262
23263            paint = new Paint();
23264            matrix = new Matrix();
23265            // use use a height of 1, and then wack the matrix each time we
23266            // actually use it.
23267            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23268            paint.setShader(shader);
23269            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23270
23271            this.host = host;
23272        }
23273
23274        public void setFadeColor(int color) {
23275            if (color != mLastColor) {
23276                mLastColor = color;
23277
23278                if (color != 0) {
23279                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23280                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23281                    paint.setShader(shader);
23282                    // Restore the default transfer mode (src_over)
23283                    paint.setXfermode(null);
23284                } else {
23285                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23286                    paint.setShader(shader);
23287                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23288                }
23289            }
23290        }
23291
23292        public void run() {
23293            long now = AnimationUtils.currentAnimationTimeMillis();
23294            if (now >= fadeStartTime) {
23295
23296                // the animation fades the scrollbars out by changing
23297                // the opacity (alpha) from fully opaque to fully
23298                // transparent
23299                int nextFrame = (int) now;
23300                int framesCount = 0;
23301
23302                Interpolator interpolator = scrollBarInterpolator;
23303
23304                // Start opaque
23305                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23306
23307                // End transparent
23308                nextFrame += scrollBarFadeDuration;
23309                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23310
23311                state = FADING;
23312
23313                // Kick off the fade animation
23314                host.invalidate(true);
23315            }
23316        }
23317    }
23318
23319    /**
23320     * Resuable callback for sending
23321     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23322     */
23323    private class SendViewScrolledAccessibilityEvent implements Runnable {
23324        public volatile boolean mIsPending;
23325
23326        public void run() {
23327            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23328            mIsPending = false;
23329        }
23330    }
23331
23332    /**
23333     * <p>
23334     * This class represents a delegate that can be registered in a {@link View}
23335     * to enhance accessibility support via composition rather via inheritance.
23336     * It is specifically targeted to widget developers that extend basic View
23337     * classes i.e. classes in package android.view, that would like their
23338     * applications to be backwards compatible.
23339     * </p>
23340     * <div class="special reference">
23341     * <h3>Developer Guides</h3>
23342     * <p>For more information about making applications accessible, read the
23343     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23344     * developer guide.</p>
23345     * </div>
23346     * <p>
23347     * A scenario in which a developer would like to use an accessibility delegate
23348     * is overriding a method introduced in a later API version then the minimal API
23349     * version supported by the application. For example, the method
23350     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23351     * in API version 4 when the accessibility APIs were first introduced. If a
23352     * developer would like his application to run on API version 4 devices (assuming
23353     * all other APIs used by the application are version 4 or lower) and take advantage
23354     * of this method, instead of overriding the method which would break the application's
23355     * backwards compatibility, he can override the corresponding method in this
23356     * delegate and register the delegate in the target View if the API version of
23357     * the system is high enough i.e. the API version is same or higher to the API
23358     * version that introduced
23359     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23360     * </p>
23361     * <p>
23362     * Here is an example implementation:
23363     * </p>
23364     * <code><pre><p>
23365     * if (Build.VERSION.SDK_INT >= 14) {
23366     *     // If the API version is equal of higher than the version in
23367     *     // which onInitializeAccessibilityNodeInfo was introduced we
23368     *     // register a delegate with a customized implementation.
23369     *     View view = findViewById(R.id.view_id);
23370     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23371     *         public void onInitializeAccessibilityNodeInfo(View host,
23372     *                 AccessibilityNodeInfo info) {
23373     *             // Let the default implementation populate the info.
23374     *             super.onInitializeAccessibilityNodeInfo(host, info);
23375     *             // Set some other information.
23376     *             info.setEnabled(host.isEnabled());
23377     *         }
23378     *     });
23379     * }
23380     * </code></pre></p>
23381     * <p>
23382     * This delegate contains methods that correspond to the accessibility methods
23383     * in View. If a delegate has been specified the implementation in View hands
23384     * off handling to the corresponding method in this delegate. The default
23385     * implementation the delegate methods behaves exactly as the corresponding
23386     * method in View for the case of no accessibility delegate been set. Hence,
23387     * to customize the behavior of a View method, clients can override only the
23388     * corresponding delegate method without altering the behavior of the rest
23389     * accessibility related methods of the host view.
23390     * </p>
23391     * <p>
23392     * <strong>Note:</strong> On platform versions prior to
23393     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23394     * views in the {@code android.widget.*} package are called <i>before</i>
23395     * host methods. This prevents certain properties such as class name from
23396     * being modified by overriding
23397     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23398     * as any changes will be overwritten by the host class.
23399     * <p>
23400     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23401     * methods are called <i>after</i> host methods, which all properties to be
23402     * modified without being overwritten by the host class.
23403     */
23404    public static class AccessibilityDelegate {
23405
23406        /**
23407         * Sends an accessibility event of the given type. If accessibility is not
23408         * enabled this method has no effect.
23409         * <p>
23410         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23411         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23412         * been set.
23413         * </p>
23414         *
23415         * @param host The View hosting the delegate.
23416         * @param eventType The type of the event to send.
23417         *
23418         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23419         */
23420        public void sendAccessibilityEvent(View host, int eventType) {
23421            host.sendAccessibilityEventInternal(eventType);
23422        }
23423
23424        /**
23425         * Performs the specified accessibility action on the view. For
23426         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23427         * <p>
23428         * The default implementation behaves as
23429         * {@link View#performAccessibilityAction(int, Bundle)
23430         *  View#performAccessibilityAction(int, Bundle)} for the case of
23431         *  no accessibility delegate been set.
23432         * </p>
23433         *
23434         * @param action The action to perform.
23435         * @return Whether the action was performed.
23436         *
23437         * @see View#performAccessibilityAction(int, Bundle)
23438         *      View#performAccessibilityAction(int, Bundle)
23439         */
23440        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23441            return host.performAccessibilityActionInternal(action, args);
23442        }
23443
23444        /**
23445         * Sends an accessibility event. This method behaves exactly as
23446         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23447         * empty {@link AccessibilityEvent} and does not perform a check whether
23448         * accessibility is enabled.
23449         * <p>
23450         * The default implementation behaves as
23451         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23452         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23453         * the case of no accessibility delegate been set.
23454         * </p>
23455         *
23456         * @param host The View hosting the delegate.
23457         * @param event The event to send.
23458         *
23459         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23460         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23461         */
23462        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23463            host.sendAccessibilityEventUncheckedInternal(event);
23464        }
23465
23466        /**
23467         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23468         * to its children for adding their text content to the event.
23469         * <p>
23470         * The default implementation behaves as
23471         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23472         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23473         * the case of no accessibility delegate been set.
23474         * </p>
23475         *
23476         * @param host The View hosting the delegate.
23477         * @param event The event.
23478         * @return True if the event population was completed.
23479         *
23480         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23481         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23482         */
23483        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23484            return host.dispatchPopulateAccessibilityEventInternal(event);
23485        }
23486
23487        /**
23488         * Gives a chance to the host View to populate the accessibility event with its
23489         * text content.
23490         * <p>
23491         * The default implementation behaves as
23492         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23493         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23494         * the case of no accessibility delegate been set.
23495         * </p>
23496         *
23497         * @param host The View hosting the delegate.
23498         * @param event The accessibility event which to populate.
23499         *
23500         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23501         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23502         */
23503        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23504            host.onPopulateAccessibilityEventInternal(event);
23505        }
23506
23507        /**
23508         * Initializes an {@link AccessibilityEvent} with information about the
23509         * the host View which is the event source.
23510         * <p>
23511         * The default implementation behaves as
23512         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23513         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23514         * the case of no accessibility delegate been set.
23515         * </p>
23516         *
23517         * @param host The View hosting the delegate.
23518         * @param event The event to initialize.
23519         *
23520         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23521         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23522         */
23523        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23524            host.onInitializeAccessibilityEventInternal(event);
23525        }
23526
23527        /**
23528         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23529         * <p>
23530         * The default implementation behaves as
23531         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23532         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23533         * the case of no accessibility delegate been set.
23534         * </p>
23535         *
23536         * @param host The View hosting the delegate.
23537         * @param info The instance to initialize.
23538         *
23539         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23540         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23541         */
23542        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23543            host.onInitializeAccessibilityNodeInfoInternal(info);
23544        }
23545
23546        /**
23547         * Called when a child of the host View has requested sending an
23548         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23549         * to augment the event.
23550         * <p>
23551         * The default implementation behaves as
23552         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23553         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
23554         * the case of no accessibility delegate been set.
23555         * </p>
23556         *
23557         * @param host The View hosting the delegate.
23558         * @param child The child which requests sending the event.
23559         * @param event The event to be sent.
23560         * @return True if the event should be sent
23561         *
23562         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23563         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23564         */
23565        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
23566                AccessibilityEvent event) {
23567            return host.onRequestSendAccessibilityEventInternal(child, event);
23568        }
23569
23570        /**
23571         * Gets the provider for managing a virtual view hierarchy rooted at this View
23572         * and reported to {@link android.accessibilityservice.AccessibilityService}s
23573         * that explore the window content.
23574         * <p>
23575         * The default implementation behaves as
23576         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
23577         * the case of no accessibility delegate been set.
23578         * </p>
23579         *
23580         * @return The provider.
23581         *
23582         * @see AccessibilityNodeProvider
23583         */
23584        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
23585            return null;
23586        }
23587
23588        /**
23589         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
23590         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
23591         * This method is responsible for obtaining an accessibility node info from a
23592         * pool of reusable instances and calling
23593         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
23594         * view to initialize the former.
23595         * <p>
23596         * <strong>Note:</strong> The client is responsible for recycling the obtained
23597         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
23598         * creation.
23599         * </p>
23600         * <p>
23601         * The default implementation behaves as
23602         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
23603         * the case of no accessibility delegate been set.
23604         * </p>
23605         * @return A populated {@link AccessibilityNodeInfo}.
23606         *
23607         * @see AccessibilityNodeInfo
23608         *
23609         * @hide
23610         */
23611        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
23612            return host.createAccessibilityNodeInfoInternal();
23613        }
23614    }
23615
23616    private class MatchIdPredicate implements Predicate<View> {
23617        public int mId;
23618
23619        @Override
23620        public boolean apply(View view) {
23621            return (view.mID == mId);
23622        }
23623    }
23624
23625    private class MatchLabelForPredicate implements Predicate<View> {
23626        private int mLabeledId;
23627
23628        @Override
23629        public boolean apply(View view) {
23630            return (view.mLabelForId == mLabeledId);
23631        }
23632    }
23633
23634    private class SendViewStateChangedAccessibilityEvent implements Runnable {
23635        private int mChangeTypes = 0;
23636        private boolean mPosted;
23637        private boolean mPostedWithDelay;
23638        private long mLastEventTimeMillis;
23639
23640        @Override
23641        public void run() {
23642            mPosted = false;
23643            mPostedWithDelay = false;
23644            mLastEventTimeMillis = SystemClock.uptimeMillis();
23645            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
23646                final AccessibilityEvent event = AccessibilityEvent.obtain();
23647                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
23648                event.setContentChangeTypes(mChangeTypes);
23649                sendAccessibilityEventUnchecked(event);
23650            }
23651            mChangeTypes = 0;
23652        }
23653
23654        public void runOrPost(int changeType) {
23655            mChangeTypes |= changeType;
23656
23657            // If this is a live region or the child of a live region, collect
23658            // all events from this frame and send them on the next frame.
23659            if (inLiveRegion()) {
23660                // If we're already posted with a delay, remove that.
23661                if (mPostedWithDelay) {
23662                    removeCallbacks(this);
23663                    mPostedWithDelay = false;
23664                }
23665                // Only post if we're not already posted.
23666                if (!mPosted) {
23667                    post(this);
23668                    mPosted = true;
23669                }
23670                return;
23671            }
23672
23673            if (mPosted) {
23674                return;
23675            }
23676
23677            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
23678            final long minEventIntevalMillis =
23679                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
23680            if (timeSinceLastMillis >= minEventIntevalMillis) {
23681                removeCallbacks(this);
23682                run();
23683            } else {
23684                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
23685                mPostedWithDelay = true;
23686            }
23687        }
23688    }
23689
23690    private boolean inLiveRegion() {
23691        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23692            return true;
23693        }
23694
23695        ViewParent parent = getParent();
23696        while (parent instanceof View) {
23697            if (((View) parent).getAccessibilityLiveRegion()
23698                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23699                return true;
23700            }
23701            parent = parent.getParent();
23702        }
23703
23704        return false;
23705    }
23706
23707    /**
23708     * Dump all private flags in readable format, useful for documentation and
23709     * sanity checking.
23710     */
23711    private static void dumpFlags() {
23712        final HashMap<String, String> found = Maps.newHashMap();
23713        try {
23714            for (Field field : View.class.getDeclaredFields()) {
23715                final int modifiers = field.getModifiers();
23716                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
23717                    if (field.getType().equals(int.class)) {
23718                        final int value = field.getInt(null);
23719                        dumpFlag(found, field.getName(), value);
23720                    } else if (field.getType().equals(int[].class)) {
23721                        final int[] values = (int[]) field.get(null);
23722                        for (int i = 0; i < values.length; i++) {
23723                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
23724                        }
23725                    }
23726                }
23727            }
23728        } catch (IllegalAccessException e) {
23729            throw new RuntimeException(e);
23730        }
23731
23732        final ArrayList<String> keys = Lists.newArrayList();
23733        keys.addAll(found.keySet());
23734        Collections.sort(keys);
23735        for (String key : keys) {
23736            Log.d(VIEW_LOG_TAG, found.get(key));
23737        }
23738    }
23739
23740    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
23741        // Sort flags by prefix, then by bits, always keeping unique keys
23742        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
23743        final int prefix = name.indexOf('_');
23744        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
23745        final String output = bits + " " + name;
23746        found.put(key, output);
23747    }
23748
23749    /** {@hide} */
23750    public void encode(@NonNull ViewHierarchyEncoder stream) {
23751        stream.beginObject(this);
23752        encodeProperties(stream);
23753        stream.endObject();
23754    }
23755
23756    /** {@hide} */
23757    @CallSuper
23758    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
23759        Object resolveId = ViewDebug.resolveId(getContext(), mID);
23760        if (resolveId instanceof String) {
23761            stream.addProperty("id", (String) resolveId);
23762        } else {
23763            stream.addProperty("id", mID);
23764        }
23765
23766        stream.addProperty("misc:transformation.alpha",
23767                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
23768        stream.addProperty("misc:transitionName", getTransitionName());
23769
23770        // layout
23771        stream.addProperty("layout:left", mLeft);
23772        stream.addProperty("layout:right", mRight);
23773        stream.addProperty("layout:top", mTop);
23774        stream.addProperty("layout:bottom", mBottom);
23775        stream.addProperty("layout:width", getWidth());
23776        stream.addProperty("layout:height", getHeight());
23777        stream.addProperty("layout:layoutDirection", getLayoutDirection());
23778        stream.addProperty("layout:layoutRtl", isLayoutRtl());
23779        stream.addProperty("layout:hasTransientState", hasTransientState());
23780        stream.addProperty("layout:baseline", getBaseline());
23781
23782        // layout params
23783        ViewGroup.LayoutParams layoutParams = getLayoutParams();
23784        if (layoutParams != null) {
23785            stream.addPropertyKey("layoutParams");
23786            layoutParams.encode(stream);
23787        }
23788
23789        // scrolling
23790        stream.addProperty("scrolling:scrollX", mScrollX);
23791        stream.addProperty("scrolling:scrollY", mScrollY);
23792
23793        // padding
23794        stream.addProperty("padding:paddingLeft", mPaddingLeft);
23795        stream.addProperty("padding:paddingRight", mPaddingRight);
23796        stream.addProperty("padding:paddingTop", mPaddingTop);
23797        stream.addProperty("padding:paddingBottom", mPaddingBottom);
23798        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
23799        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
23800        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
23801        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
23802        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
23803
23804        // measurement
23805        stream.addProperty("measurement:minHeight", mMinHeight);
23806        stream.addProperty("measurement:minWidth", mMinWidth);
23807        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
23808        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
23809
23810        // drawing
23811        stream.addProperty("drawing:elevation", getElevation());
23812        stream.addProperty("drawing:translationX", getTranslationX());
23813        stream.addProperty("drawing:translationY", getTranslationY());
23814        stream.addProperty("drawing:translationZ", getTranslationZ());
23815        stream.addProperty("drawing:rotation", getRotation());
23816        stream.addProperty("drawing:rotationX", getRotationX());
23817        stream.addProperty("drawing:rotationY", getRotationY());
23818        stream.addProperty("drawing:scaleX", getScaleX());
23819        stream.addProperty("drawing:scaleY", getScaleY());
23820        stream.addProperty("drawing:pivotX", getPivotX());
23821        stream.addProperty("drawing:pivotY", getPivotY());
23822        stream.addProperty("drawing:opaque", isOpaque());
23823        stream.addProperty("drawing:alpha", getAlpha());
23824        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
23825        stream.addProperty("drawing:shadow", hasShadow());
23826        stream.addProperty("drawing:solidColor", getSolidColor());
23827        stream.addProperty("drawing:layerType", mLayerType);
23828        stream.addProperty("drawing:willNotDraw", willNotDraw());
23829        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
23830        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
23831        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
23832        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
23833
23834        // focus
23835        stream.addProperty("focus:hasFocus", hasFocus());
23836        stream.addProperty("focus:isFocused", isFocused());
23837        stream.addProperty("focus:isFocusable", isFocusable());
23838        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
23839
23840        stream.addProperty("misc:clickable", isClickable());
23841        stream.addProperty("misc:pressed", isPressed());
23842        stream.addProperty("misc:selected", isSelected());
23843        stream.addProperty("misc:touchMode", isInTouchMode());
23844        stream.addProperty("misc:hovered", isHovered());
23845        stream.addProperty("misc:activated", isActivated());
23846
23847        stream.addProperty("misc:visibility", getVisibility());
23848        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
23849        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
23850
23851        stream.addProperty("misc:enabled", isEnabled());
23852        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
23853        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
23854
23855        // theme attributes
23856        Resources.Theme theme = getContext().getTheme();
23857        if (theme != null) {
23858            stream.addPropertyKey("theme");
23859            theme.encode(stream);
23860        }
23861
23862        // view attribute information
23863        int n = mAttributes != null ? mAttributes.length : 0;
23864        stream.addProperty("meta:__attrCount__", n/2);
23865        for (int i = 0; i < n; i += 2) {
23866            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
23867        }
23868
23869        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
23870
23871        // text
23872        stream.addProperty("text:textDirection", getTextDirection());
23873        stream.addProperty("text:textAlignment", getTextAlignment());
23874
23875        // accessibility
23876        CharSequence contentDescription = getContentDescription();
23877        stream.addProperty("accessibility:contentDescription",
23878                contentDescription == null ? "" : contentDescription.toString());
23879        stream.addProperty("accessibility:labelFor", getLabelFor());
23880        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
23881    }
23882
23883    /**
23884     * Determine if this view is rendered on a round wearable device and is the main view
23885     * on the screen.
23886     */
23887    private boolean shouldDrawRoundScrollbar() {
23888        if (!mResources.getConfiguration().isScreenRound()) {
23889            return false;
23890        }
23891
23892        final View rootView = getRootView();
23893        final WindowInsets insets = getRootWindowInsets();
23894
23895        int height = getHeight();
23896        int width = getWidth();
23897        int displayHeight = rootView.getHeight();
23898        int displayWidth = rootView.getWidth();
23899
23900        if (height != displayHeight || width != displayWidth) {
23901            return false;
23902        }
23903
23904        getLocationOnScreen(mAttachInfo.mTmpLocation);
23905        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
23906                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
23907    }
23908}
23909