View.java revision e27c677f332a2eb96dd2c3970d6fb71752273a8f
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.Color;
44import android.graphics.Insets;
45import android.graphics.Interpolator;
46import android.graphics.LinearGradient;
47import android.graphics.Matrix;
48import android.graphics.Outline;
49import android.graphics.Paint;
50import android.graphics.PixelFormat;
51import android.graphics.Point;
52import android.graphics.PorterDuff;
53import android.graphics.PorterDuffXfermode;
54import android.graphics.Rect;
55import android.graphics.RectF;
56import android.graphics.Region;
57import android.graphics.Shader;
58import android.graphics.drawable.ColorDrawable;
59import android.graphics.drawable.Drawable;
60import android.hardware.display.DisplayManagerGlobal;
61import android.os.Build.VERSION_CODES;
62import android.os.Bundle;
63import android.os.Handler;
64import android.os.IBinder;
65import android.os.Parcel;
66import android.os.Parcelable;
67import android.os.RemoteException;
68import android.os.SystemClock;
69import android.os.SystemProperties;
70import android.os.Trace;
71import android.text.TextUtils;
72import android.util.AttributeSet;
73import android.util.FloatProperty;
74import android.util.LayoutDirection;
75import android.util.Log;
76import android.util.LongSparseLongArray;
77import android.util.Pools.SynchronizedPool;
78import android.util.Property;
79import android.util.SparseArray;
80import android.util.StateSet;
81import android.util.SuperNotCalledException;
82import android.util.TypedValue;
83import android.view.ContextMenu.ContextMenuInfo;
84import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
85import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
86import android.view.AccessibilityIterators.TextSegmentIterator;
87import android.view.AccessibilityIterators.WordTextSegmentIterator;
88import android.view.accessibility.AccessibilityEvent;
89import android.view.accessibility.AccessibilityEventSource;
90import android.view.accessibility.AccessibilityManager;
91import android.view.accessibility.AccessibilityNodeInfo;
92import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
93import android.view.accessibility.AccessibilityNodeProvider;
94import android.view.animation.Animation;
95import android.view.animation.AnimationUtils;
96import android.view.animation.Transformation;
97import android.view.inputmethod.EditorInfo;
98import android.view.inputmethod.InputConnection;
99import android.view.inputmethod.InputMethodManager;
100import android.widget.Checkable;
101import android.widget.FrameLayout;
102import android.widget.ScrollBarDrawable;
103import static android.os.Build.VERSION_CODES.*;
104import static java.lang.Math.max;
105
106import com.android.internal.R;
107import com.android.internal.util.Predicate;
108import com.android.internal.view.menu.MenuBuilder;
109import com.android.internal.widget.ScrollBarUtils;
110import com.google.android.collect.Lists;
111import com.google.android.collect.Maps;
112
113import java.lang.NullPointerException;
114import java.lang.annotation.Retention;
115import java.lang.annotation.RetentionPolicy;
116import java.lang.ref.WeakReference;
117import java.lang.reflect.Field;
118import java.lang.reflect.InvocationTargetException;
119import java.lang.reflect.Method;
120import java.lang.reflect.Modifier;
121import java.util.ArrayList;
122import java.util.Arrays;
123import java.util.Collections;
124import java.util.HashMap;
125import java.util.List;
126import java.util.Locale;
127import java.util.Map;
128import java.util.concurrent.CopyOnWriteArrayList;
129import java.util.concurrent.atomic.AtomicInteger;
130
131/**
132 * <p>
133 * This class represents the basic building block for user interface components. A View
134 * occupies a rectangular area on the screen and is responsible for drawing and
135 * event handling. View is the base class for <em>widgets</em>, which are
136 * used to create interactive UI components (buttons, text fields, etc.). The
137 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
138 * are invisible containers that hold other Views (or other ViewGroups) and define
139 * their layout properties.
140 * </p>
141 *
142 * <div class="special reference">
143 * <h3>Developer Guides</h3>
144 * <p>For information about using this class to develop your application's user interface,
145 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
146 * </div>
147 *
148 * <a name="Using"></a>
149 * <h3>Using Views</h3>
150 * <p>
151 * All of the views in a window are arranged in a single tree. You can add views
152 * either from code or by specifying a tree of views in one or more XML layout
153 * files. There are many specialized subclasses of views that act as controls or
154 * are capable of displaying text, images, or other content.
155 * </p>
156 * <p>
157 * Once you have created a tree of views, there are typically a few types of
158 * common operations you may wish to perform:
159 * <ul>
160 * <li><strong>Set properties:</strong> for example setting the text of a
161 * {@link android.widget.TextView}. The available properties and the methods
162 * that set them will vary among the different subclasses of views. Note that
163 * properties that are known at build time can be set in the XML layout
164 * files.</li>
165 * <li><strong>Set focus:</strong> The framework will handle moving focus in
166 * response to user input. To force focus to a specific view, call
167 * {@link #requestFocus}.</li>
168 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
169 * that will be notified when something interesting happens to the view. For
170 * example, all views will let you set a listener to be notified when the view
171 * gains or loses focus. You can register such a listener using
172 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
173 * Other view subclasses offer more specialized listeners. For example, a Button
174 * exposes a listener to notify clients when the button is clicked.</li>
175 * <li><strong>Set visibility:</strong> You can hide or show views using
176 * {@link #setVisibility(int)}.</li>
177 * </ul>
178 * </p>
179 * <p><em>
180 * Note: The Android framework is responsible for measuring, laying out and
181 * drawing views. You should not call methods that perform these actions on
182 * views yourself unless you are actually implementing a
183 * {@link android.view.ViewGroup}.
184 * </em></p>
185 *
186 * <a name="Lifecycle"></a>
187 * <h3>Implementing a Custom View</h3>
188 *
189 * <p>
190 * To implement a custom view, you will usually begin by providing overrides for
191 * some of the standard methods that the framework calls on all views. You do
192 * not need to override all of these methods. In fact, you can start by just
193 * overriding {@link #onDraw(android.graphics.Canvas)}.
194 * <table border="2" width="85%" align="center" cellpadding="5">
195 *     <thead>
196 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
197 *     </thead>
198 *
199 *     <tbody>
200 *     <tr>
201 *         <td rowspan="2">Creation</td>
202 *         <td>Constructors</td>
203 *         <td>There is a form of the constructor that are called when the view
204 *         is created from code and a form that is called when the view is
205 *         inflated from a layout file. The second form should parse and apply
206 *         any attributes defined in the layout file.
207 *         </td>
208 *     </tr>
209 *     <tr>
210 *         <td><code>{@link #onFinishInflate()}</code></td>
211 *         <td>Called after a view and all of its children has been inflated
212 *         from XML.</td>
213 *     </tr>
214 *
215 *     <tr>
216 *         <td rowspan="3">Layout</td>
217 *         <td><code>{@link #onMeasure(int, int)}</code></td>
218 *         <td>Called to determine the size requirements for this view and all
219 *         of its children.
220 *         </td>
221 *     </tr>
222 *     <tr>
223 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
224 *         <td>Called when this view should assign a size and position to all
225 *         of its children.
226 *         </td>
227 *     </tr>
228 *     <tr>
229 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
230 *         <td>Called when the size of this view has changed.
231 *         </td>
232 *     </tr>
233 *
234 *     <tr>
235 *         <td>Drawing</td>
236 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
237 *         <td>Called when the view should render its content.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td rowspan="4">Event processing</td>
243 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
244 *         <td>Called when a new hardware key event occurs.
245 *         </td>
246 *     </tr>
247 *     <tr>
248 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
249 *         <td>Called when a hardware key up event occurs.
250 *         </td>
251 *     </tr>
252 *     <tr>
253 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
254 *         <td>Called when a trackball motion event occurs.
255 *         </td>
256 *     </tr>
257 *     <tr>
258 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
259 *         <td>Called when a touch screen motion event occurs.
260 *         </td>
261 *     </tr>
262 *
263 *     <tr>
264 *         <td rowspan="2">Focus</td>
265 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
266 *         <td>Called when the view gains or loses focus.
267 *         </td>
268 *     </tr>
269 *
270 *     <tr>
271 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
272 *         <td>Called when the window containing the view gains or loses focus.
273 *         </td>
274 *     </tr>
275 *
276 *     <tr>
277 *         <td rowspan="3">Attaching</td>
278 *         <td><code>{@link #onAttachedToWindow()}</code></td>
279 *         <td>Called when the view is attached to a window.
280 *         </td>
281 *     </tr>
282 *
283 *     <tr>
284 *         <td><code>{@link #onDetachedFromWindow}</code></td>
285 *         <td>Called when the view is detached from its window.
286 *         </td>
287 *     </tr>
288 *
289 *     <tr>
290 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
291 *         <td>Called when the visibility of the window containing the view
292 *         has changed.
293 *         </td>
294 *     </tr>
295 *     </tbody>
296 *
297 * </table>
298 * </p>
299 *
300 * <a name="IDs"></a>
301 * <h3>IDs</h3>
302 * Views may have an integer id associated with them. These ids are typically
303 * assigned in the layout XML files, and are used to find specific views within
304 * the view tree. A common pattern is to:
305 * <ul>
306 * <li>Define a Button in the layout file and assign it a unique ID.
307 * <pre>
308 * &lt;Button
309 *     android:id="@+id/my_button"
310 *     android:layout_width="wrap_content"
311 *     android:layout_height="wrap_content"
312 *     android:text="@string/my_button_text"/&gt;
313 * </pre></li>
314 * <li>From the onCreate method of an Activity, find the Button
315 * <pre class="prettyprint">
316 *      Button myButton = (Button) findViewById(R.id.my_button);
317 * </pre></li>
318 * </ul>
319 * <p>
320 * View IDs need not be unique throughout the tree, but it is good practice to
321 * ensure that they are at least unique within the part of the tree you are
322 * searching.
323 * </p>
324 *
325 * <a name="Position"></a>
326 * <h3>Position</h3>
327 * <p>
328 * The geometry of a view is that of a rectangle. A view has a location,
329 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
330 * two dimensions, expressed as a width and a height. The unit for location
331 * and dimensions is the pixel.
332 * </p>
333 *
334 * <p>
335 * It is possible to retrieve the location of a view by invoking the methods
336 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
337 * coordinate of the rectangle representing the view. The latter returns the
338 * top, or Y, coordinate of the rectangle representing the view. These methods
339 * both return the location of the view relative to its parent. For instance,
340 * when getLeft() returns 20, that means the view is located 20 pixels to the
341 * right of the left edge of its direct parent.
342 * </p>
343 *
344 * <p>
345 * In addition, several convenience methods are offered to avoid unnecessary
346 * computations, namely {@link #getRight()} and {@link #getBottom()}.
347 * These methods return the coordinates of the right and bottom edges of the
348 * rectangle representing the view. For instance, calling {@link #getRight()}
349 * is similar to the following computation: <code>getLeft() + getWidth()</code>
350 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
351 * </p>
352 *
353 * <a name="SizePaddingMargins"></a>
354 * <h3>Size, padding and margins</h3>
355 * <p>
356 * The size of a view is expressed with a width and a height. A view actually
357 * possess two pairs of width and height values.
358 * </p>
359 *
360 * <p>
361 * The first pair is known as <em>measured width</em> and
362 * <em>measured height</em>. These dimensions define how big a view wants to be
363 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
364 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
365 * and {@link #getMeasuredHeight()}.
366 * </p>
367 *
368 * <p>
369 * The second pair is simply known as <em>width</em> and <em>height</em>, or
370 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
371 * dimensions define the actual size of the view on screen, at drawing time and
372 * after layout. These values may, but do not have to, be different from the
373 * measured width and height. The width and height can be obtained by calling
374 * {@link #getWidth()} and {@link #getHeight()}.
375 * </p>
376 *
377 * <p>
378 * To measure its dimensions, a view takes into account its padding. The padding
379 * is expressed in pixels for the left, top, right and bottom parts of the view.
380 * Padding can be used to offset the content of the view by a specific amount of
381 * pixels. For instance, a left padding of 2 will push the view's content by
382 * 2 pixels to the right of the left edge. Padding can be set using the
383 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
384 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
385 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
386 * {@link #getPaddingEnd()}.
387 * </p>
388 *
389 * <p>
390 * Even though a view can define a padding, it does not provide any support for
391 * margins. However, view groups provide such a support. Refer to
392 * {@link android.view.ViewGroup} and
393 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
394 * </p>
395 *
396 * <a name="Layout"></a>
397 * <h3>Layout</h3>
398 * <p>
399 * Layout is a two pass process: a measure pass and a layout pass. The measuring
400 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
401 * of the view tree. Each view pushes dimension specifications down the tree
402 * during the recursion. At the end of the measure pass, every view has stored
403 * its measurements. The second pass happens in
404 * {@link #layout(int,int,int,int)} and is also top-down. During
405 * this pass each parent is responsible for positioning all of its children
406 * using the sizes computed in the measure pass.
407 * </p>
408 *
409 * <p>
410 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
411 * {@link #getMeasuredHeight()} values must be set, along with those for all of
412 * that view's descendants. A view's measured width and measured height values
413 * must respect the constraints imposed by the view's parents. This guarantees
414 * that at the end of the measure pass, all parents accept all of their
415 * children's measurements. A parent view may call measure() more than once on
416 * its children. For example, the parent may measure each child once with
417 * unspecified dimensions to find out how big they want to be, then call
418 * measure() on them again with actual numbers if the sum of all the children's
419 * unconstrained sizes is too big or too small.
420 * </p>
421 *
422 * <p>
423 * The measure pass uses two classes to communicate dimensions. The
424 * {@link MeasureSpec} class is used by views to tell their parents how they
425 * want to be measured and positioned. The base LayoutParams class just
426 * describes how big the view wants to be for both width and height. For each
427 * dimension, it can specify one of:
428 * <ul>
429 * <li> an exact number
430 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
431 * (minus padding)
432 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
433 * enclose its content (plus padding).
434 * </ul>
435 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
436 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
437 * an X and Y value.
438 * </p>
439 *
440 * <p>
441 * MeasureSpecs are used to push requirements down the tree from parent to
442 * child. A MeasureSpec can be in one of three modes:
443 * <ul>
444 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
445 * of a child view. For example, a LinearLayout may call measure() on its child
446 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
447 * tall the child view wants to be given a width of 240 pixels.
448 * <li>EXACTLY: This is used by the parent to impose an exact size on the
449 * child. The child must use this size, and guarantee that all of its
450 * descendants will fit within this size.
451 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
452 * child. The child must guarantee that it and all of its descendants will fit
453 * within this size.
454 * </ul>
455 * </p>
456 *
457 * <p>
458 * To initiate a layout, call {@link #requestLayout}. This method is typically
459 * called by a view on itself when it believes that is can no longer fit within
460 * its current bounds.
461 * </p>
462 *
463 * <a name="Drawing"></a>
464 * <h3>Drawing</h3>
465 * <p>
466 * Drawing is handled by walking the tree and recording the drawing commands of
467 * any View that needs to update. After this, the drawing commands of the
468 * entire tree are issued to screen, clipped to the newly damaged area.
469 * </p>
470 *
471 * <p>
472 * The tree is largely recorded and drawn in order, with parents drawn before
473 * (i.e., behind) their children, with siblings drawn in the order they appear
474 * in the tree. If you set a background drawable for a View, then the View will
475 * draw it before calling back to its <code>onDraw()</code> method. The child
476 * drawing order can be overridden with
477 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
478 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
479 * </p>
480 *
481 * <p>
482 * To force a view to draw, call {@link #invalidate()}.
483 * </p>
484 *
485 * <a name="EventHandlingThreading"></a>
486 * <h3>Event Handling and Threading</h3>
487 * <p>
488 * The basic cycle of a view is as follows:
489 * <ol>
490 * <li>An event comes in and is dispatched to the appropriate view. The view
491 * handles the event and notifies any listeners.</li>
492 * <li>If in the course of processing the event, the view's bounds may need
493 * to be changed, the view will call {@link #requestLayout()}.</li>
494 * <li>Similarly, if in the course of processing the event the view's appearance
495 * may need to be changed, the view will call {@link #invalidate()}.</li>
496 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
497 * the framework will take care of measuring, laying out, and drawing the tree
498 * as appropriate.</li>
499 * </ol>
500 * </p>
501 *
502 * <p><em>Note: The entire view tree is single threaded. You must always be on
503 * the UI thread when calling any method on any view.</em>
504 * If you are doing work on other threads and want to update the state of a view
505 * from that thread, you should use a {@link Handler}.
506 * </p>
507 *
508 * <a name="FocusHandling"></a>
509 * <h3>Focus Handling</h3>
510 * <p>
511 * The framework will handle routine focus movement in response to user input.
512 * This includes changing the focus as views are removed or hidden, or as new
513 * views become available. Views indicate their willingness to take focus
514 * through the {@link #isFocusable} method. To change whether a view can take
515 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
516 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
517 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
518 * </p>
519 * <p>
520 * Focus movement is based on an algorithm which finds the nearest neighbor in a
521 * given direction. In rare cases, the default algorithm may not match the
522 * intended behavior of the developer. In these situations, you can provide
523 * explicit overrides by using these XML attributes in the layout file:
524 * <pre>
525 * nextFocusDown
526 * nextFocusLeft
527 * nextFocusRight
528 * nextFocusUp
529 * </pre>
530 * </p>
531 *
532 *
533 * <p>
534 * To get a particular view to take focus, call {@link #requestFocus()}.
535 * </p>
536 *
537 * <a name="TouchMode"></a>
538 * <h3>Touch Mode</h3>
539 * <p>
540 * When a user is navigating a user interface via directional keys such as a D-pad, it is
541 * necessary to give focus to actionable items such as buttons so the user can see
542 * what will take input.  If the device has touch capabilities, however, and the user
543 * begins interacting with the interface by touching it, it is no longer necessary to
544 * always highlight, or give focus to, a particular view.  This motivates a mode
545 * for interaction named 'touch mode'.
546 * </p>
547 * <p>
548 * For a touch capable device, once the user touches the screen, the device
549 * will enter touch mode.  From this point onward, only views for which
550 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
551 * Other views that are touchable, like buttons, will not take focus when touched; they will
552 * only fire the on click listeners.
553 * </p>
554 * <p>
555 * Any time a user hits a directional key, such as a D-pad direction, the view device will
556 * exit touch mode, and find a view to take focus, so that the user may resume interacting
557 * with the user interface without touching the screen again.
558 * </p>
559 * <p>
560 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
561 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
562 * </p>
563 *
564 * <a name="Scrolling"></a>
565 * <h3>Scrolling</h3>
566 * <p>
567 * The framework provides basic support for views that wish to internally
568 * scroll their content. This includes keeping track of the X and Y scroll
569 * offset as well as mechanisms for drawing scrollbars. See
570 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
571 * {@link #awakenScrollBars()} for more details.
572 * </p>
573 *
574 * <a name="Tags"></a>
575 * <h3>Tags</h3>
576 * <p>
577 * Unlike IDs, tags are not used to identify views. Tags are essentially an
578 * extra piece of information that can be associated with a view. They are most
579 * often used as a convenience to store data related to views in the views
580 * themselves rather than by putting them in a separate structure.
581 * </p>
582 * <p>
583 * Tags may be specified with character sequence values in layout XML as either
584 * a single tag using the {@link android.R.styleable#View_tag android:tag}
585 * attribute or multiple tags using the {@code <tag>} child element:
586 * <pre>
587 *     &ltView ...
588 *           android:tag="@string/mytag_value" /&gt;
589 *     &ltView ...&gt;
590 *         &lttag android:id="@+id/mytag"
591 *              android:value="@string/mytag_value" /&gt;
592 *     &lt/View>
593 * </pre>
594 * </p>
595 * <p>
596 * Tags may also be specified with arbitrary objects from code using
597 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
598 * </p>
599 *
600 * <a name="Themes"></a>
601 * <h3>Themes</h3>
602 * <p>
603 * By default, Views are created using the theme of the Context object supplied
604 * to their constructor; however, a different theme may be specified by using
605 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
606 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
607 * code.
608 * </p>
609 * <p>
610 * When the {@link android.R.styleable#View_theme android:theme} attribute is
611 * used in XML, the specified theme is applied on top of the inflation
612 * context's theme (see {@link LayoutInflater}) and used for the view itself as
613 * well as any child elements.
614 * </p>
615 * <p>
616 * In the following example, both views will be created using the Material dark
617 * color scheme; however, because an overlay theme is used which only defines a
618 * subset of attributes, the value of
619 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
620 * the inflation context's theme (e.g. the Activity theme) will be preserved.
621 * <pre>
622 *     &ltLinearLayout
623 *             ...
624 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
625 *         &ltView ...&gt;
626 *     &lt/LinearLayout&gt;
627 * </pre>
628 * </p>
629 *
630 * <a name="Properties"></a>
631 * <h3>Properties</h3>
632 * <p>
633 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
634 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
635 * available both in the {@link Property} form as well as in similarly-named setter/getter
636 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
637 * be used to set persistent state associated with these rendering-related properties on the view.
638 * The properties and methods can also be used in conjunction with
639 * {@link android.animation.Animator Animator}-based animations, described more in the
640 * <a href="#Animation">Animation</a> section.
641 * </p>
642 *
643 * <a name="Animation"></a>
644 * <h3>Animation</h3>
645 * <p>
646 * Starting with Android 3.0, the preferred way of animating views is to use the
647 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
648 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
649 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
650 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
651 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
652 * makes animating these View properties particularly easy and efficient.
653 * </p>
654 * <p>
655 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
656 * You can attach an {@link Animation} object to a view using
657 * {@link #setAnimation(Animation)} or
658 * {@link #startAnimation(Animation)}. The animation can alter the scale,
659 * rotation, translation and alpha of a view over time. If the animation is
660 * attached to a view that has children, the animation will affect the entire
661 * subtree rooted by that node. When an animation is started, the framework will
662 * take care of redrawing the appropriate views until the animation completes.
663 * </p>
664 *
665 * <a name="Security"></a>
666 * <h3>Security</h3>
667 * <p>
668 * Sometimes it is essential that an application be able to verify that an action
669 * is being performed with the full knowledge and consent of the user, such as
670 * granting a permission request, making a purchase or clicking on an advertisement.
671 * Unfortunately, a malicious application could try to spoof the user into
672 * performing these actions, unaware, by concealing the intended purpose of the view.
673 * As a remedy, the framework offers a touch filtering mechanism that can be used to
674 * improve the security of views that provide access to sensitive functionality.
675 * </p><p>
676 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
677 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
678 * will discard touches that are received whenever the view's window is obscured by
679 * another visible window.  As a result, the view will not receive touches whenever a
680 * toast, dialog or other window appears above the view's window.
681 * </p><p>
682 * For more fine-grained control over security, consider overriding the
683 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
684 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
685 * </p>
686 *
687 * @attr ref android.R.styleable#View_alpha
688 * @attr ref android.R.styleable#View_background
689 * @attr ref android.R.styleable#View_clickable
690 * @attr ref android.R.styleable#View_contentDescription
691 * @attr ref android.R.styleable#View_drawingCacheQuality
692 * @attr ref android.R.styleable#View_duplicateParentState
693 * @attr ref android.R.styleable#View_id
694 * @attr ref android.R.styleable#View_requiresFadingEdge
695 * @attr ref android.R.styleable#View_fadeScrollbars
696 * @attr ref android.R.styleable#View_fadingEdgeLength
697 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
698 * @attr ref android.R.styleable#View_fitsSystemWindows
699 * @attr ref android.R.styleable#View_isScrollContainer
700 * @attr ref android.R.styleable#View_focusable
701 * @attr ref android.R.styleable#View_focusableInTouchMode
702 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
703 * @attr ref android.R.styleable#View_keepScreenOn
704 * @attr ref android.R.styleable#View_layerType
705 * @attr ref android.R.styleable#View_layoutDirection
706 * @attr ref android.R.styleable#View_longClickable
707 * @attr ref android.R.styleable#View_minHeight
708 * @attr ref android.R.styleable#View_minWidth
709 * @attr ref android.R.styleable#View_nextFocusDown
710 * @attr ref android.R.styleable#View_nextFocusLeft
711 * @attr ref android.R.styleable#View_nextFocusRight
712 * @attr ref android.R.styleable#View_nextFocusUp
713 * @attr ref android.R.styleable#View_onClick
714 * @attr ref android.R.styleable#View_padding
715 * @attr ref android.R.styleable#View_paddingBottom
716 * @attr ref android.R.styleable#View_paddingLeft
717 * @attr ref android.R.styleable#View_paddingRight
718 * @attr ref android.R.styleable#View_paddingTop
719 * @attr ref android.R.styleable#View_paddingStart
720 * @attr ref android.R.styleable#View_paddingEnd
721 * @attr ref android.R.styleable#View_saveEnabled
722 * @attr ref android.R.styleable#View_rotation
723 * @attr ref android.R.styleable#View_rotationX
724 * @attr ref android.R.styleable#View_rotationY
725 * @attr ref android.R.styleable#View_scaleX
726 * @attr ref android.R.styleable#View_scaleY
727 * @attr ref android.R.styleable#View_scrollX
728 * @attr ref android.R.styleable#View_scrollY
729 * @attr ref android.R.styleable#View_scrollbarSize
730 * @attr ref android.R.styleable#View_scrollbarStyle
731 * @attr ref android.R.styleable#View_scrollbars
732 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
733 * @attr ref android.R.styleable#View_scrollbarFadeDuration
734 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
735 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
736 * @attr ref android.R.styleable#View_scrollbarThumbVertical
737 * @attr ref android.R.styleable#View_scrollbarTrackVertical
738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
739 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
740 * @attr ref android.R.styleable#View_stateListAnimator
741 * @attr ref android.R.styleable#View_transitionName
742 * @attr ref android.R.styleable#View_soundEffectsEnabled
743 * @attr ref android.R.styleable#View_tag
744 * @attr ref android.R.styleable#View_textAlignment
745 * @attr ref android.R.styleable#View_textDirection
746 * @attr ref android.R.styleable#View_transformPivotX
747 * @attr ref android.R.styleable#View_transformPivotY
748 * @attr ref android.R.styleable#View_translationX
749 * @attr ref android.R.styleable#View_translationY
750 * @attr ref android.R.styleable#View_translationZ
751 * @attr ref android.R.styleable#View_visibility
752 * @attr ref android.R.styleable#View_theme
753 *
754 * @see android.view.ViewGroup
755 */
756@UiThread
757public class View implements Drawable.Callback, KeyEvent.Callback,
758        AccessibilityEventSource {
759    private static final boolean DBG = false;
760
761    /**
762     * The logging tag used by this class with android.util.Log.
763     */
764    protected static final String VIEW_LOG_TAG = "View";
765
766    /**
767     * When set to true, apps will draw debugging information about their layouts.
768     *
769     * @hide
770     */
771    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
772
773    /**
774     * When set to true, this view will save its attribute data.
775     *
776     * @hide
777     */
778    public static boolean mDebugViewAttributes = false;
779
780    /**
781     * Used to mark a View that has no ID.
782     */
783    public static final int NO_ID = -1;
784
785    /**
786     * Signals that compatibility booleans have been initialized according to
787     * target SDK versions.
788     */
789    private static boolean sCompatibilityDone = false;
790
791    /**
792     * Use the old (broken) way of building MeasureSpecs.
793     */
794    private static boolean sUseBrokenMakeMeasureSpec = false;
795
796    /**
797     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
798     */
799    static boolean sUseZeroUnspecifiedMeasureSpec = false;
800
801    /**
802     * Ignore any optimizations using the measure cache.
803     */
804    private static boolean sIgnoreMeasureCache = false;
805
806    /**
807     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
808     */
809    private static boolean sAlwaysRemeasureExactly = false;
810
811    /**
812     * Relax constraints around whether setLayoutParams() must be called after
813     * modifying the layout params.
814     */
815    private static boolean sLayoutParamsAlwaysChanged = false;
816
817    /**
818     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
819     * without throwing
820     */
821    static boolean sTextureViewIgnoresDrawableSetters = false;
822
823    /**
824     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
825     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
826     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
827     * check is implemented for backwards compatibility.
828     *
829     * {@hide}
830     */
831    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
832
833
834    /**
835     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
836     * calling setFlags.
837     */
838    private static final int NOT_FOCUSABLE = 0x00000000;
839
840    /**
841     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
842     * setFlags.
843     */
844    private static final int FOCUSABLE = 0x00000001;
845
846    /**
847     * Mask for use with setFlags indicating bits used for focus.
848     */
849    private static final int FOCUSABLE_MASK = 0x00000001;
850
851    /**
852     * This view will adjust its padding to fit sytem windows (e.g. status bar)
853     */
854    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
855
856    /** @hide */
857    @IntDef({VISIBLE, INVISIBLE, GONE})
858    @Retention(RetentionPolicy.SOURCE)
859    public @interface Visibility {}
860
861    /**
862     * This view is visible.
863     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
864     * android:visibility}.
865     */
866    public static final int VISIBLE = 0x00000000;
867
868    /**
869     * This view is invisible, but it still takes up space for layout purposes.
870     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
871     * android:visibility}.
872     */
873    public static final int INVISIBLE = 0x00000004;
874
875    /**
876     * This view is invisible, and it doesn't take any space for layout
877     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
878     * android:visibility}.
879     */
880    public static final int GONE = 0x00000008;
881
882    /**
883     * Mask for use with setFlags indicating bits used for visibility.
884     * {@hide}
885     */
886    static final int VISIBILITY_MASK = 0x0000000C;
887
888    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
889
890    /**
891     * This view is enabled. Interpretation varies by subclass.
892     * Use with ENABLED_MASK when calling setFlags.
893     * {@hide}
894     */
895    static final int ENABLED = 0x00000000;
896
897    /**
898     * This view is disabled. Interpretation varies by subclass.
899     * Use with ENABLED_MASK when calling setFlags.
900     * {@hide}
901     */
902    static final int DISABLED = 0x00000020;
903
904   /**
905    * Mask for use with setFlags indicating bits used for indicating whether
906    * this view is enabled
907    * {@hide}
908    */
909    static final int ENABLED_MASK = 0x00000020;
910
911    /**
912     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
913     * called and further optimizations will be performed. It is okay to have
914     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
915     * {@hide}
916     */
917    static final int WILL_NOT_DRAW = 0x00000080;
918
919    /**
920     * Mask for use with setFlags indicating bits used for indicating whether
921     * this view is will draw
922     * {@hide}
923     */
924    static final int DRAW_MASK = 0x00000080;
925
926    /**
927     * <p>This view doesn't show scrollbars.</p>
928     * {@hide}
929     */
930    static final int SCROLLBARS_NONE = 0x00000000;
931
932    /**
933     * <p>This view shows horizontal scrollbars.</p>
934     * {@hide}
935     */
936    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
937
938    /**
939     * <p>This view shows vertical scrollbars.</p>
940     * {@hide}
941     */
942    static final int SCROLLBARS_VERTICAL = 0x00000200;
943
944    /**
945     * <p>Mask for use with setFlags indicating bits used for indicating which
946     * scrollbars are enabled.</p>
947     * {@hide}
948     */
949    static final int SCROLLBARS_MASK = 0x00000300;
950
951    /**
952     * Indicates that the view should filter touches when its window is obscured.
953     * Refer to the class comments for more information about this security feature.
954     * {@hide}
955     */
956    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
957
958    /**
959     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
960     * that they are optional and should be skipped if the window has
961     * requested system UI flags that ignore those insets for layout.
962     */
963    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
964
965    /**
966     * <p>This view doesn't show fading edges.</p>
967     * {@hide}
968     */
969    static final int FADING_EDGE_NONE = 0x00000000;
970
971    /**
972     * <p>This view shows horizontal fading edges.</p>
973     * {@hide}
974     */
975    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
976
977    /**
978     * <p>This view shows vertical fading edges.</p>
979     * {@hide}
980     */
981    static final int FADING_EDGE_VERTICAL = 0x00002000;
982
983    /**
984     * <p>Mask for use with setFlags indicating bits used for indicating which
985     * fading edges are enabled.</p>
986     * {@hide}
987     */
988    static final int FADING_EDGE_MASK = 0x00003000;
989
990    /**
991     * <p>Indicates this view can be clicked. When clickable, a View reacts
992     * to clicks by notifying the OnClickListener.<p>
993     * {@hide}
994     */
995    static final int CLICKABLE = 0x00004000;
996
997    /**
998     * <p>Indicates this view is caching its drawing into a bitmap.</p>
999     * {@hide}
1000     */
1001    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1002
1003    /**
1004     * <p>Indicates that no icicle should be saved for this view.<p>
1005     * {@hide}
1006     */
1007    static final int SAVE_DISABLED = 0x000010000;
1008
1009    /**
1010     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1011     * property.</p>
1012     * {@hide}
1013     */
1014    static final int SAVE_DISABLED_MASK = 0x000010000;
1015
1016    /**
1017     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1018     * {@hide}
1019     */
1020    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1021
1022    /**
1023     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1024     * {@hide}
1025     */
1026    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1027
1028    /** @hide */
1029    @Retention(RetentionPolicy.SOURCE)
1030    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1031    public @interface DrawingCacheQuality {}
1032
1033    /**
1034     * <p>Enables low quality mode for the drawing cache.</p>
1035     */
1036    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1037
1038    /**
1039     * <p>Enables high quality mode for the drawing cache.</p>
1040     */
1041    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1042
1043    /**
1044     * <p>Enables automatic quality mode for the drawing cache.</p>
1045     */
1046    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1047
1048    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1049            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1050    };
1051
1052    /**
1053     * <p>Mask for use with setFlags indicating bits used for the cache
1054     * quality property.</p>
1055     * {@hide}
1056     */
1057    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1058
1059    /**
1060     * <p>
1061     * Indicates this view can be long clicked. When long clickable, a View
1062     * reacts to long clicks by notifying the OnLongClickListener or showing a
1063     * context menu.
1064     * </p>
1065     * {@hide}
1066     */
1067    static final int LONG_CLICKABLE = 0x00200000;
1068
1069    /**
1070     * <p>Indicates that this view gets its drawable states from its direct parent
1071     * and ignores its original internal states.</p>
1072     *
1073     * @hide
1074     */
1075    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1076
1077    /**
1078     * <p>
1079     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1080     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1081     * OnContextClickListener.
1082     * </p>
1083     * {@hide}
1084     */
1085    static final int CONTEXT_CLICKABLE = 0x00800000;
1086
1087
1088    /** @hide */
1089    @IntDef({
1090        SCROLLBARS_INSIDE_OVERLAY,
1091        SCROLLBARS_INSIDE_INSET,
1092        SCROLLBARS_OUTSIDE_OVERLAY,
1093        SCROLLBARS_OUTSIDE_INSET
1094    })
1095    @Retention(RetentionPolicy.SOURCE)
1096    public @interface ScrollBarStyle {}
1097
1098    /**
1099     * The scrollbar style to display the scrollbars inside the content area,
1100     * without increasing the padding. The scrollbars will be overlaid with
1101     * translucency on the view's content.
1102     */
1103    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1104
1105    /**
1106     * The scrollbar style to display the scrollbars inside the padded area,
1107     * increasing the padding of the view. The scrollbars will not overlap the
1108     * content area of the view.
1109     */
1110    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1111
1112    /**
1113     * The scrollbar style to display the scrollbars at the edge of the view,
1114     * without increasing the padding. The scrollbars will be overlaid with
1115     * translucency.
1116     */
1117    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1118
1119    /**
1120     * The scrollbar style to display the scrollbars at the edge of the view,
1121     * increasing the padding of the view. The scrollbars will only overlap the
1122     * background, if any.
1123     */
1124    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1125
1126    /**
1127     * Mask to check if the scrollbar style is overlay or inset.
1128     * {@hide}
1129     */
1130    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1131
1132    /**
1133     * Mask to check if the scrollbar style is inside or outside.
1134     * {@hide}
1135     */
1136    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1137
1138    /**
1139     * Mask for scrollbar style.
1140     * {@hide}
1141     */
1142    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1143
1144    /**
1145     * View flag indicating that the screen should remain on while the
1146     * window containing this view is visible to the user.  This effectively
1147     * takes care of automatically setting the WindowManager's
1148     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1149     */
1150    public static final int KEEP_SCREEN_ON = 0x04000000;
1151
1152    /**
1153     * View flag indicating whether this view should have sound effects enabled
1154     * for events such as clicking and touching.
1155     */
1156    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1157
1158    /**
1159     * View flag indicating whether this view should have haptic feedback
1160     * enabled for events such as long presses.
1161     */
1162    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1163
1164    /**
1165     * <p>Indicates that the view hierarchy should stop saving state when
1166     * it reaches this view.  If state saving is initiated immediately at
1167     * the view, it will be allowed.
1168     * {@hide}
1169     */
1170    static final int PARENT_SAVE_DISABLED = 0x20000000;
1171
1172    /**
1173     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1174     * {@hide}
1175     */
1176    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1177
1178    /** @hide */
1179    @IntDef(flag = true,
1180            value = {
1181                FOCUSABLES_ALL,
1182                FOCUSABLES_TOUCH_MODE
1183            })
1184    @Retention(RetentionPolicy.SOURCE)
1185    public @interface FocusableMode {}
1186
1187    /**
1188     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1189     * should add all focusable Views regardless if they are focusable in touch mode.
1190     */
1191    public static final int FOCUSABLES_ALL = 0x00000000;
1192
1193    /**
1194     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1195     * should add only Views focusable in touch mode.
1196     */
1197    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1198
1199    /** @hide */
1200    @IntDef({
1201            FOCUS_BACKWARD,
1202            FOCUS_FORWARD,
1203            FOCUS_LEFT,
1204            FOCUS_UP,
1205            FOCUS_RIGHT,
1206            FOCUS_DOWN
1207    })
1208    @Retention(RetentionPolicy.SOURCE)
1209    public @interface FocusDirection {}
1210
1211    /** @hide */
1212    @IntDef({
1213            FOCUS_LEFT,
1214            FOCUS_UP,
1215            FOCUS_RIGHT,
1216            FOCUS_DOWN
1217    })
1218    @Retention(RetentionPolicy.SOURCE)
1219    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1220
1221    /**
1222     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1223     * item.
1224     */
1225    public static final int FOCUS_BACKWARD = 0x00000001;
1226
1227    /**
1228     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1229     * item.
1230     */
1231    public static final int FOCUS_FORWARD = 0x00000002;
1232
1233    /**
1234     * Use with {@link #focusSearch(int)}. Move focus to the left.
1235     */
1236    public static final int FOCUS_LEFT = 0x00000011;
1237
1238    /**
1239     * Use with {@link #focusSearch(int)}. Move focus up.
1240     */
1241    public static final int FOCUS_UP = 0x00000021;
1242
1243    /**
1244     * Use with {@link #focusSearch(int)}. Move focus to the right.
1245     */
1246    public static final int FOCUS_RIGHT = 0x00000042;
1247
1248    /**
1249     * Use with {@link #focusSearch(int)}. Move focus down.
1250     */
1251    public static final int FOCUS_DOWN = 0x00000082;
1252
1253    /**
1254     * Bits of {@link #getMeasuredWidthAndState()} and
1255     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1256     */
1257    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1258
1259    /**
1260     * Bits of {@link #getMeasuredWidthAndState()} and
1261     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1262     */
1263    public static final int MEASURED_STATE_MASK = 0xff000000;
1264
1265    /**
1266     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1267     * for functions that combine both width and height into a single int,
1268     * such as {@link #getMeasuredState()} and the childState argument of
1269     * {@link #resolveSizeAndState(int, int, int)}.
1270     */
1271    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1272
1273    /**
1274     * Bit of {@link #getMeasuredWidthAndState()} and
1275     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1276     * is smaller that the space the view would like to have.
1277     */
1278    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1279
1280    /**
1281     * Base View state sets
1282     */
1283    // Singles
1284    /**
1285     * Indicates the view has no states set. States are used with
1286     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1287     * view depending on its state.
1288     *
1289     * @see android.graphics.drawable.Drawable
1290     * @see #getDrawableState()
1291     */
1292    protected static final int[] EMPTY_STATE_SET;
1293    /**
1294     * Indicates the view is enabled. States are used with
1295     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1296     * view depending on its state.
1297     *
1298     * @see android.graphics.drawable.Drawable
1299     * @see #getDrawableState()
1300     */
1301    protected static final int[] ENABLED_STATE_SET;
1302    /**
1303     * Indicates the view is focused. States are used with
1304     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1305     * view depending on its state.
1306     *
1307     * @see android.graphics.drawable.Drawable
1308     * @see #getDrawableState()
1309     */
1310    protected static final int[] FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is selected. States are used with
1313     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1314     * view depending on its state.
1315     *
1316     * @see android.graphics.drawable.Drawable
1317     * @see #getDrawableState()
1318     */
1319    protected static final int[] SELECTED_STATE_SET;
1320    /**
1321     * Indicates the view is pressed. States are used with
1322     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1323     * view depending on its state.
1324     *
1325     * @see android.graphics.drawable.Drawable
1326     * @see #getDrawableState()
1327     */
1328    protected static final int[] PRESSED_STATE_SET;
1329    /**
1330     * Indicates the view's window has focus. States are used with
1331     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1332     * view depending on its state.
1333     *
1334     * @see android.graphics.drawable.Drawable
1335     * @see #getDrawableState()
1336     */
1337    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1338    // Doubles
1339    /**
1340     * Indicates the view is enabled and has the focus.
1341     *
1342     * @see #ENABLED_STATE_SET
1343     * @see #FOCUSED_STATE_SET
1344     */
1345    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1346    /**
1347     * Indicates the view is enabled and selected.
1348     *
1349     * @see #ENABLED_STATE_SET
1350     * @see #SELECTED_STATE_SET
1351     */
1352    protected static final int[] ENABLED_SELECTED_STATE_SET;
1353    /**
1354     * Indicates the view is enabled and that its window has focus.
1355     *
1356     * @see #ENABLED_STATE_SET
1357     * @see #WINDOW_FOCUSED_STATE_SET
1358     */
1359    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1360    /**
1361     * Indicates the view is focused and selected.
1362     *
1363     * @see #FOCUSED_STATE_SET
1364     * @see #SELECTED_STATE_SET
1365     */
1366    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1367    /**
1368     * Indicates the view has the focus and that its window has the focus.
1369     *
1370     * @see #FOCUSED_STATE_SET
1371     * @see #WINDOW_FOCUSED_STATE_SET
1372     */
1373    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1374    /**
1375     * Indicates the view is selected and that its window has the focus.
1376     *
1377     * @see #SELECTED_STATE_SET
1378     * @see #WINDOW_FOCUSED_STATE_SET
1379     */
1380    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1381    // Triples
1382    /**
1383     * Indicates the view is enabled, focused and selected.
1384     *
1385     * @see #ENABLED_STATE_SET
1386     * @see #FOCUSED_STATE_SET
1387     * @see #SELECTED_STATE_SET
1388     */
1389    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1390    /**
1391     * Indicates the view is enabled, focused and its window has the focus.
1392     *
1393     * @see #ENABLED_STATE_SET
1394     * @see #FOCUSED_STATE_SET
1395     * @see #WINDOW_FOCUSED_STATE_SET
1396     */
1397    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1398    /**
1399     * Indicates the view is enabled, selected and its window has the focus.
1400     *
1401     * @see #ENABLED_STATE_SET
1402     * @see #SELECTED_STATE_SET
1403     * @see #WINDOW_FOCUSED_STATE_SET
1404     */
1405    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1406    /**
1407     * Indicates the view is focused, selected and its window has the focus.
1408     *
1409     * @see #FOCUSED_STATE_SET
1410     * @see #SELECTED_STATE_SET
1411     * @see #WINDOW_FOCUSED_STATE_SET
1412     */
1413    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1414    /**
1415     * Indicates the view is enabled, focused, selected and its window
1416     * has the focus.
1417     *
1418     * @see #ENABLED_STATE_SET
1419     * @see #FOCUSED_STATE_SET
1420     * @see #SELECTED_STATE_SET
1421     * @see #WINDOW_FOCUSED_STATE_SET
1422     */
1423    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1424    /**
1425     * Indicates the view is pressed and its window has the focus.
1426     *
1427     * @see #PRESSED_STATE_SET
1428     * @see #WINDOW_FOCUSED_STATE_SET
1429     */
1430    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1431    /**
1432     * Indicates the view is pressed and selected.
1433     *
1434     * @see #PRESSED_STATE_SET
1435     * @see #SELECTED_STATE_SET
1436     */
1437    protected static final int[] PRESSED_SELECTED_STATE_SET;
1438    /**
1439     * Indicates the view is pressed, selected and its window has the focus.
1440     *
1441     * @see #PRESSED_STATE_SET
1442     * @see #SELECTED_STATE_SET
1443     * @see #WINDOW_FOCUSED_STATE_SET
1444     */
1445    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1446    /**
1447     * Indicates the view is pressed and focused.
1448     *
1449     * @see #PRESSED_STATE_SET
1450     * @see #FOCUSED_STATE_SET
1451     */
1452    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1453    /**
1454     * Indicates the view is pressed, focused and its window has the focus.
1455     *
1456     * @see #PRESSED_STATE_SET
1457     * @see #FOCUSED_STATE_SET
1458     * @see #WINDOW_FOCUSED_STATE_SET
1459     */
1460    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1461    /**
1462     * Indicates the view is pressed, focused and selected.
1463     *
1464     * @see #PRESSED_STATE_SET
1465     * @see #SELECTED_STATE_SET
1466     * @see #FOCUSED_STATE_SET
1467     */
1468    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1469    /**
1470     * Indicates the view is pressed, focused, selected and its window has the focus.
1471     *
1472     * @see #PRESSED_STATE_SET
1473     * @see #FOCUSED_STATE_SET
1474     * @see #SELECTED_STATE_SET
1475     * @see #WINDOW_FOCUSED_STATE_SET
1476     */
1477    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1478    /**
1479     * Indicates the view is pressed and enabled.
1480     *
1481     * @see #PRESSED_STATE_SET
1482     * @see #ENABLED_STATE_SET
1483     */
1484    protected static final int[] PRESSED_ENABLED_STATE_SET;
1485    /**
1486     * Indicates the view is pressed, enabled and its window has the focus.
1487     *
1488     * @see #PRESSED_STATE_SET
1489     * @see #ENABLED_STATE_SET
1490     * @see #WINDOW_FOCUSED_STATE_SET
1491     */
1492    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1493    /**
1494     * Indicates the view is pressed, enabled and selected.
1495     *
1496     * @see #PRESSED_STATE_SET
1497     * @see #ENABLED_STATE_SET
1498     * @see #SELECTED_STATE_SET
1499     */
1500    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1501    /**
1502     * Indicates the view is pressed, enabled, selected and its window has the
1503     * focus.
1504     *
1505     * @see #PRESSED_STATE_SET
1506     * @see #ENABLED_STATE_SET
1507     * @see #SELECTED_STATE_SET
1508     * @see #WINDOW_FOCUSED_STATE_SET
1509     */
1510    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1511    /**
1512     * Indicates the view is pressed, enabled and focused.
1513     *
1514     * @see #PRESSED_STATE_SET
1515     * @see #ENABLED_STATE_SET
1516     * @see #FOCUSED_STATE_SET
1517     */
1518    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1519    /**
1520     * Indicates the view is pressed, enabled, focused and its window has the
1521     * focus.
1522     *
1523     * @see #PRESSED_STATE_SET
1524     * @see #ENABLED_STATE_SET
1525     * @see #FOCUSED_STATE_SET
1526     * @see #WINDOW_FOCUSED_STATE_SET
1527     */
1528    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1529    /**
1530     * Indicates the view is pressed, enabled, focused and selected.
1531     *
1532     * @see #PRESSED_STATE_SET
1533     * @see #ENABLED_STATE_SET
1534     * @see #SELECTED_STATE_SET
1535     * @see #FOCUSED_STATE_SET
1536     */
1537    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1538    /**
1539     * Indicates the view is pressed, enabled, focused, selected and its window
1540     * has the focus.
1541     *
1542     * @see #PRESSED_STATE_SET
1543     * @see #ENABLED_STATE_SET
1544     * @see #SELECTED_STATE_SET
1545     * @see #FOCUSED_STATE_SET
1546     * @see #WINDOW_FOCUSED_STATE_SET
1547     */
1548    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1549
1550    static {
1551        EMPTY_STATE_SET = StateSet.get(0);
1552
1553        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1554
1555        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1556        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1557                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1558
1559        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1560        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1561                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1562        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1563                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1564        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1565                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1566                        | StateSet.VIEW_STATE_FOCUSED);
1567
1568        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1569        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1570                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1571        ENABLED_SELECTED_STATE_SET = StateSet.get(
1572                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1573        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1574                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1575                        | StateSet.VIEW_STATE_ENABLED);
1576        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1577                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1578        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1579                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1580                        | StateSet.VIEW_STATE_ENABLED);
1581        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1582                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1583                        | StateSet.VIEW_STATE_ENABLED);
1584        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1585                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1586                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1587
1588        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1589        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1590                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1591        PRESSED_SELECTED_STATE_SET = StateSet.get(
1592                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1593        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1594                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1595                        | StateSet.VIEW_STATE_PRESSED);
1596        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1597                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1598        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1599                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1600                        | StateSet.VIEW_STATE_PRESSED);
1601        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1602                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1603                        | StateSet.VIEW_STATE_PRESSED);
1604        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1605                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1606                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1607        PRESSED_ENABLED_STATE_SET = StateSet.get(
1608                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1609        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1610                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1611                        | StateSet.VIEW_STATE_PRESSED);
1612        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1613                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1614                        | StateSet.VIEW_STATE_PRESSED);
1615        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1616                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1617                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1618        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1619                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1620                        | StateSet.VIEW_STATE_PRESSED);
1621        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1622                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1623                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1624        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1625                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1626                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1627        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1628                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1629                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1630                        | StateSet.VIEW_STATE_PRESSED);
1631    }
1632
1633    /**
1634     * Accessibility event types that are dispatched for text population.
1635     */
1636    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1637            AccessibilityEvent.TYPE_VIEW_CLICKED
1638            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1639            | AccessibilityEvent.TYPE_VIEW_SELECTED
1640            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1641            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1642            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1643            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1644            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1645            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1646            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1647            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1648
1649    /**
1650     * Temporary Rect currently for use in setBackground().  This will probably
1651     * be extended in the future to hold our own class with more than just
1652     * a Rect. :)
1653     */
1654    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1655
1656    /**
1657     * Map used to store views' tags.
1658     */
1659    private SparseArray<Object> mKeyedTags;
1660
1661    /**
1662     * The next available accessibility id.
1663     */
1664    private static int sNextAccessibilityViewId;
1665
1666    /**
1667     * The animation currently associated with this view.
1668     * @hide
1669     */
1670    protected Animation mCurrentAnimation = null;
1671
1672    /**
1673     * Width as measured during measure pass.
1674     * {@hide}
1675     */
1676    @ViewDebug.ExportedProperty(category = "measurement")
1677    int mMeasuredWidth;
1678
1679    /**
1680     * Height as measured during measure pass.
1681     * {@hide}
1682     */
1683    @ViewDebug.ExportedProperty(category = "measurement")
1684    int mMeasuredHeight;
1685
1686    /**
1687     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1688     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1689     * its display list. This flag, used only when hw accelerated, allows us to clear the
1690     * flag while retaining this information until it's needed (at getDisplayList() time and
1691     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1692     *
1693     * {@hide}
1694     */
1695    boolean mRecreateDisplayList = false;
1696
1697    /**
1698     * The view's identifier.
1699     * {@hide}
1700     *
1701     * @see #setId(int)
1702     * @see #getId()
1703     */
1704    @IdRes
1705    @ViewDebug.ExportedProperty(resolveId = true)
1706    int mID = NO_ID;
1707
1708    /**
1709     * The stable ID of this view for accessibility purposes.
1710     */
1711    int mAccessibilityViewId = NO_ID;
1712
1713    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1714
1715    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1716
1717    /**
1718     * The view's tag.
1719     * {@hide}
1720     *
1721     * @see #setTag(Object)
1722     * @see #getTag()
1723     */
1724    protected Object mTag = null;
1725
1726    // for mPrivateFlags:
1727    /** {@hide} */
1728    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1729    /** {@hide} */
1730    static final int PFLAG_FOCUSED                     = 0x00000002;
1731    /** {@hide} */
1732    static final int PFLAG_SELECTED                    = 0x00000004;
1733    /** {@hide} */
1734    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1735    /** {@hide} */
1736    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1737    /** {@hide} */
1738    static final int PFLAG_DRAWN                       = 0x00000020;
1739    /**
1740     * When this flag is set, this view is running an animation on behalf of its
1741     * children and should therefore not cancel invalidate requests, even if they
1742     * lie outside of this view's bounds.
1743     *
1744     * {@hide}
1745     */
1746    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1747    /** {@hide} */
1748    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1749    /** {@hide} */
1750    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1751    /** {@hide} */
1752    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1753    /** {@hide} */
1754    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1755    /** {@hide} */
1756    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1757    /** {@hide} */
1758    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1759
1760    private static final int PFLAG_PRESSED             = 0x00004000;
1761
1762    /** {@hide} */
1763    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1764    /**
1765     * Flag used to indicate that this view should be drawn once more (and only once
1766     * more) after its animation has completed.
1767     * {@hide}
1768     */
1769    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1770
1771    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1772
1773    /**
1774     * Indicates that the View returned true when onSetAlpha() was called and that
1775     * the alpha must be restored.
1776     * {@hide}
1777     */
1778    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1779
1780    /**
1781     * Set by {@link #setScrollContainer(boolean)}.
1782     */
1783    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1784
1785    /**
1786     * Set by {@link #setScrollContainer(boolean)}.
1787     */
1788    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1789
1790    /**
1791     * View flag indicating whether this view was invalidated (fully or partially.)
1792     *
1793     * @hide
1794     */
1795    static final int PFLAG_DIRTY                       = 0x00200000;
1796
1797    /**
1798     * View flag indicating whether this view was invalidated by an opaque
1799     * invalidate request.
1800     *
1801     * @hide
1802     */
1803    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1804
1805    /**
1806     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1807     *
1808     * @hide
1809     */
1810    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1811
1812    /**
1813     * Indicates whether the background is opaque.
1814     *
1815     * @hide
1816     */
1817    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1818
1819    /**
1820     * Indicates whether the scrollbars are opaque.
1821     *
1822     * @hide
1823     */
1824    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1825
1826    /**
1827     * Indicates whether the view is opaque.
1828     *
1829     * @hide
1830     */
1831    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1832
1833    /**
1834     * Indicates a prepressed state;
1835     * the short time between ACTION_DOWN and recognizing
1836     * a 'real' press. Prepressed is used to recognize quick taps
1837     * even when they are shorter than ViewConfiguration.getTapTimeout().
1838     *
1839     * @hide
1840     */
1841    private static final int PFLAG_PREPRESSED          = 0x02000000;
1842
1843    /**
1844     * Indicates whether the view is temporarily detached.
1845     *
1846     * @hide
1847     */
1848    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1849
1850    /**
1851     * Indicates that we should awaken scroll bars once attached
1852     *
1853     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1854     * during window attachment and it is no longer needed. Feel free to repurpose it.
1855     *
1856     * @hide
1857     */
1858    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1859
1860    /**
1861     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1862     * @hide
1863     */
1864    private static final int PFLAG_HOVERED             = 0x10000000;
1865
1866    /**
1867     * no longer needed, should be reused
1868     */
1869    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1870
1871    /** {@hide} */
1872    static final int PFLAG_ACTIVATED                   = 0x40000000;
1873
1874    /**
1875     * Indicates that this view was specifically invalidated, not just dirtied because some
1876     * child view was invalidated. The flag is used to determine when we need to recreate
1877     * a view's display list (as opposed to just returning a reference to its existing
1878     * display list).
1879     *
1880     * @hide
1881     */
1882    static final int PFLAG_INVALIDATED                 = 0x80000000;
1883
1884    /**
1885     * Masks for mPrivateFlags2, as generated by dumpFlags():
1886     *
1887     * |-------|-------|-------|-------|
1888     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1889     *                                1  PFLAG2_DRAG_HOVERED
1890     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1891     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1892     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1893     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1894     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1895     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1896     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1897     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1898     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1899     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1900     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1901     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1902     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1903     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1904     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1905     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1906     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1907     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1908     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1909     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1910     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1911     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1912     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1913     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1914     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1915     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1916     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1917     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1918     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1919     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1920     *    1                              PFLAG2_PADDING_RESOLVED
1921     *   1                               PFLAG2_DRAWABLE_RESOLVED
1922     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1923     * |-------|-------|-------|-------|
1924     */
1925
1926    /**
1927     * Indicates that this view has reported that it can accept the current drag's content.
1928     * Cleared when the drag operation concludes.
1929     * @hide
1930     */
1931    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1932
1933    /**
1934     * Indicates that this view is currently directly under the drag location in a
1935     * drag-and-drop operation involving content that it can accept.  Cleared when
1936     * the drag exits the view, or when the drag operation concludes.
1937     * @hide
1938     */
1939    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1940
1941    /** @hide */
1942    @IntDef({
1943        LAYOUT_DIRECTION_LTR,
1944        LAYOUT_DIRECTION_RTL,
1945        LAYOUT_DIRECTION_INHERIT,
1946        LAYOUT_DIRECTION_LOCALE
1947    })
1948    @Retention(RetentionPolicy.SOURCE)
1949    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1950    public @interface LayoutDir {}
1951
1952    /** @hide */
1953    @IntDef({
1954        LAYOUT_DIRECTION_LTR,
1955        LAYOUT_DIRECTION_RTL
1956    })
1957    @Retention(RetentionPolicy.SOURCE)
1958    public @interface ResolvedLayoutDir {}
1959
1960    /**
1961     * A flag to indicate that the layout direction of this view has not been defined yet.
1962     * @hide
1963     */
1964    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
1965
1966    /**
1967     * Horizontal layout direction of this view is from Left to Right.
1968     * Use with {@link #setLayoutDirection}.
1969     */
1970    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1971
1972    /**
1973     * Horizontal layout direction of this view is from Right to Left.
1974     * Use with {@link #setLayoutDirection}.
1975     */
1976    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1977
1978    /**
1979     * Horizontal layout direction of this view is inherited from its parent.
1980     * Use with {@link #setLayoutDirection}.
1981     */
1982    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1983
1984    /**
1985     * Horizontal layout direction of this view is from deduced from the default language
1986     * script for the locale. Use with {@link #setLayoutDirection}.
1987     */
1988    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1989
1990    /**
1991     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1992     * @hide
1993     */
1994    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1995
1996    /**
1997     * Mask for use with private flags indicating bits used for horizontal layout direction.
1998     * @hide
1999     */
2000    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2001
2002    /**
2003     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2004     * right-to-left direction.
2005     * @hide
2006     */
2007    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2008
2009    /**
2010     * Indicates whether the view horizontal layout direction has been resolved.
2011     * @hide
2012     */
2013    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2014
2015    /**
2016     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2017     * @hide
2018     */
2019    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2020            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2021
2022    /*
2023     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2024     * flag value.
2025     * @hide
2026     */
2027    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2028            LAYOUT_DIRECTION_LTR,
2029            LAYOUT_DIRECTION_RTL,
2030            LAYOUT_DIRECTION_INHERIT,
2031            LAYOUT_DIRECTION_LOCALE
2032    };
2033
2034    /**
2035     * Default horizontal layout direction.
2036     */
2037    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2038
2039    /**
2040     * Default horizontal layout direction.
2041     * @hide
2042     */
2043    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2044
2045    /**
2046     * Text direction is inherited through {@link ViewGroup}
2047     */
2048    public static final int TEXT_DIRECTION_INHERIT = 0;
2049
2050    /**
2051     * Text direction is using "first strong algorithm". The first strong directional character
2052     * determines the paragraph direction. If there is no strong directional character, the
2053     * paragraph direction is the view's resolved layout direction.
2054     */
2055    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2056
2057    /**
2058     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2059     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2060     * If there are neither, the paragraph direction is the view's resolved layout direction.
2061     */
2062    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2063
2064    /**
2065     * Text direction is forced to LTR.
2066     */
2067    public static final int TEXT_DIRECTION_LTR = 3;
2068
2069    /**
2070     * Text direction is forced to RTL.
2071     */
2072    public static final int TEXT_DIRECTION_RTL = 4;
2073
2074    /**
2075     * Text direction is coming from the system Locale.
2076     */
2077    public static final int TEXT_DIRECTION_LOCALE = 5;
2078
2079    /**
2080     * Text direction is using "first strong algorithm". The first strong directional character
2081     * determines the paragraph direction. If there is no strong directional character, the
2082     * paragraph direction is LTR.
2083     */
2084    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2085
2086    /**
2087     * Text direction is using "first strong algorithm". The first strong directional character
2088     * determines the paragraph direction. If there is no strong directional character, the
2089     * paragraph direction is RTL.
2090     */
2091    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2092
2093    /**
2094     * Default text direction is inherited
2095     */
2096    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2097
2098    /**
2099     * Default resolved text direction
2100     * @hide
2101     */
2102    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2103
2104    /**
2105     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2106     * @hide
2107     */
2108    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2109
2110    /**
2111     * Mask for use with private flags indicating bits used for text direction.
2112     * @hide
2113     */
2114    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2115            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2116
2117    /**
2118     * Array of text direction flags for mapping attribute "textDirection" to correct
2119     * flag value.
2120     * @hide
2121     */
2122    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2123            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2124            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2125            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2126            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2127            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2128            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2129            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2130            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2131    };
2132
2133    /**
2134     * Indicates whether the view text direction has been resolved.
2135     * @hide
2136     */
2137    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2138            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2139
2140    /**
2141     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2142     * @hide
2143     */
2144    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2145
2146    /**
2147     * Mask for use with private flags indicating bits used for resolved text direction.
2148     * @hide
2149     */
2150    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2151            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2152
2153    /**
2154     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2155     * @hide
2156     */
2157    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2158            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2159
2160    /** @hide */
2161    @IntDef({
2162        TEXT_ALIGNMENT_INHERIT,
2163        TEXT_ALIGNMENT_GRAVITY,
2164        TEXT_ALIGNMENT_CENTER,
2165        TEXT_ALIGNMENT_TEXT_START,
2166        TEXT_ALIGNMENT_TEXT_END,
2167        TEXT_ALIGNMENT_VIEW_START,
2168        TEXT_ALIGNMENT_VIEW_END
2169    })
2170    @Retention(RetentionPolicy.SOURCE)
2171    public @interface TextAlignment {}
2172
2173    /**
2174     * Default text alignment. The text alignment of this View is inherited from its parent.
2175     * Use with {@link #setTextAlignment(int)}
2176     */
2177    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2178
2179    /**
2180     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2181     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2182     *
2183     * Use with {@link #setTextAlignment(int)}
2184     */
2185    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2186
2187    /**
2188     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2189     *
2190     * Use with {@link #setTextAlignment(int)}
2191     */
2192    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2193
2194    /**
2195     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2196     *
2197     * Use with {@link #setTextAlignment(int)}
2198     */
2199    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2200
2201    /**
2202     * Center the paragraph, e.g. ALIGN_CENTER.
2203     *
2204     * Use with {@link #setTextAlignment(int)}
2205     */
2206    public static final int TEXT_ALIGNMENT_CENTER = 4;
2207
2208    /**
2209     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2210     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2211     *
2212     * Use with {@link #setTextAlignment(int)}
2213     */
2214    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2215
2216    /**
2217     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2218     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2219     *
2220     * Use with {@link #setTextAlignment(int)}
2221     */
2222    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2223
2224    /**
2225     * Default text alignment is inherited
2226     */
2227    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2228
2229    /**
2230     * Default resolved text alignment
2231     * @hide
2232     */
2233    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2234
2235    /**
2236      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2237      * @hide
2238      */
2239    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2240
2241    /**
2242      * Mask for use with private flags indicating bits used for text alignment.
2243      * @hide
2244      */
2245    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2246
2247    /**
2248     * Array of text direction flags for mapping attribute "textAlignment" to correct
2249     * flag value.
2250     * @hide
2251     */
2252    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2253            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2254            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2255            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2256            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2257            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2258            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2259            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2260    };
2261
2262    /**
2263     * Indicates whether the view text alignment has been resolved.
2264     * @hide
2265     */
2266    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2267
2268    /**
2269     * Bit shift to get the resolved text alignment.
2270     * @hide
2271     */
2272    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2273
2274    /**
2275     * Mask for use with private flags indicating bits used for text alignment.
2276     * @hide
2277     */
2278    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2279            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2280
2281    /**
2282     * Indicates whether if the view text alignment has been resolved to gravity
2283     */
2284    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2285            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2286
2287    // Accessiblity constants for mPrivateFlags2
2288
2289    /**
2290     * Shift for the bits in {@link #mPrivateFlags2} related to the
2291     * "importantForAccessibility" attribute.
2292     */
2293    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2294
2295    /**
2296     * Automatically determine whether a view is important for accessibility.
2297     */
2298    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2299
2300    /**
2301     * The view is important for accessibility.
2302     */
2303    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2304
2305    /**
2306     * The view is not important for accessibility.
2307     */
2308    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2309
2310    /**
2311     * The view is not important for accessibility, nor are any of its
2312     * descendant views.
2313     */
2314    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2315
2316    /**
2317     * The default whether the view is important for accessibility.
2318     */
2319    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2320
2321    /**
2322     * Mask for obtainig the bits which specify how to determine
2323     * whether a view is important for accessibility.
2324     */
2325    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2326        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2327        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2328        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2329
2330    /**
2331     * Shift for the bits in {@link #mPrivateFlags2} related to the
2332     * "accessibilityLiveRegion" attribute.
2333     */
2334    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2335
2336    /**
2337     * Live region mode specifying that accessibility services should not
2338     * automatically announce changes to this view. This is the default live
2339     * region mode for most views.
2340     * <p>
2341     * Use with {@link #setAccessibilityLiveRegion(int)}.
2342     */
2343    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2344
2345    /**
2346     * Live region mode specifying that accessibility services should announce
2347     * changes to this view.
2348     * <p>
2349     * Use with {@link #setAccessibilityLiveRegion(int)}.
2350     */
2351    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2352
2353    /**
2354     * Live region mode specifying that accessibility services should interrupt
2355     * ongoing speech to immediately announce changes to this view.
2356     * <p>
2357     * Use with {@link #setAccessibilityLiveRegion(int)}.
2358     */
2359    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2360
2361    /**
2362     * The default whether the view is important for accessibility.
2363     */
2364    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2365
2366    /**
2367     * Mask for obtaining the bits which specify a view's accessibility live
2368     * region mode.
2369     */
2370    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2371            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2372            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2373
2374    /**
2375     * Flag indicating whether a view has accessibility focus.
2376     */
2377    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2378
2379    /**
2380     * Flag whether the accessibility state of the subtree rooted at this view changed.
2381     */
2382    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2383
2384    /**
2385     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2386     * is used to check whether later changes to the view's transform should invalidate the
2387     * view to force the quickReject test to run again.
2388     */
2389    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2390
2391    /**
2392     * Flag indicating that start/end padding has been resolved into left/right padding
2393     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2394     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2395     * during measurement. In some special cases this is required such as when an adapter-based
2396     * view measures prospective children without attaching them to a window.
2397     */
2398    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2399
2400    /**
2401     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2402     */
2403    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2404
2405    /**
2406     * Indicates that the view is tracking some sort of transient state
2407     * that the app should not need to be aware of, but that the framework
2408     * should take special care to preserve.
2409     */
2410    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2411
2412    /**
2413     * Group of bits indicating that RTL properties resolution is done.
2414     */
2415    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2416            PFLAG2_TEXT_DIRECTION_RESOLVED |
2417            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2418            PFLAG2_PADDING_RESOLVED |
2419            PFLAG2_DRAWABLE_RESOLVED;
2420
2421    // There are a couple of flags left in mPrivateFlags2
2422
2423    /* End of masks for mPrivateFlags2 */
2424
2425    /**
2426     * Masks for mPrivateFlags3, as generated by dumpFlags():
2427     *
2428     * |-------|-------|-------|-------|
2429     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2430     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2431     *                               1   PFLAG3_IS_LAID_OUT
2432     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2433     *                             1     PFLAG3_CALLED_SUPER
2434     *                            1      PFLAG3_APPLYING_INSETS
2435     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2436     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2437     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2438     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2439     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2440     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2441     *                     1             PFLAG3_SCROLL_INDICATOR_START
2442     *                    1              PFLAG3_SCROLL_INDICATOR_END
2443     *                   1               PFLAG3_ASSIST_BLOCKED
2444     *                  1                PFLAG3_POINTER_ICON_NULL
2445     *                 1                 PFLAG3_POINTER_ICON_VALUE_START
2446     *           11111111                PFLAG3_POINTER_ICON_MASK
2447     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2448     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2449     *        1                          PFLAG3_TEMPORARY_DETACH
2450     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2451     * |-------|-------|-------|-------|
2452     */
2453
2454    /**
2455     * Flag indicating that view has a transform animation set on it. This is used to track whether
2456     * an animation is cleared between successive frames, in order to tell the associated
2457     * DisplayList to clear its animation matrix.
2458     */
2459    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2460
2461    /**
2462     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2463     * animation is cleared between successive frames, in order to tell the associated
2464     * DisplayList to restore its alpha value.
2465     */
2466    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2467
2468    /**
2469     * Flag indicating that the view has been through at least one layout since it
2470     * was last attached to a window.
2471     */
2472    static final int PFLAG3_IS_LAID_OUT = 0x4;
2473
2474    /**
2475     * Flag indicating that a call to measure() was skipped and should be done
2476     * instead when layout() is invoked.
2477     */
2478    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2479
2480    /**
2481     * Flag indicating that an overridden method correctly called down to
2482     * the superclass implementation as required by the API spec.
2483     */
2484    static final int PFLAG3_CALLED_SUPER = 0x10;
2485
2486    /**
2487     * Flag indicating that we're in the process of applying window insets.
2488     */
2489    static final int PFLAG3_APPLYING_INSETS = 0x20;
2490
2491    /**
2492     * Flag indicating that we're in the process of fitting system windows using the old method.
2493     */
2494    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2495
2496    /**
2497     * Flag indicating that nested scrolling is enabled for this view.
2498     * The view will optionally cooperate with views up its parent chain to allow for
2499     * integrated nested scrolling along the same axis.
2500     */
2501    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2502
2503    /**
2504     * Flag indicating that the bottom scroll indicator should be displayed
2505     * when this view can scroll up.
2506     */
2507    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2508
2509    /**
2510     * Flag indicating that the bottom scroll indicator should be displayed
2511     * when this view can scroll down.
2512     */
2513    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2514
2515    /**
2516     * Flag indicating that the left scroll indicator should be displayed
2517     * when this view can scroll left.
2518     */
2519    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2520
2521    /**
2522     * Flag indicating that the right scroll indicator should be displayed
2523     * when this view can scroll right.
2524     */
2525    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2526
2527    /**
2528     * Flag indicating that the start scroll indicator should be displayed
2529     * when this view can scroll in the start direction.
2530     */
2531    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2532
2533    /**
2534     * Flag indicating that the end scroll indicator should be displayed
2535     * when this view can scroll in the end direction.
2536     */
2537    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2538
2539    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2540
2541    static final int SCROLL_INDICATORS_NONE = 0x0000;
2542
2543    /**
2544     * Mask for use with setFlags indicating bits used for indicating which
2545     * scroll indicators are enabled.
2546     */
2547    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2548            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2549            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2550            | PFLAG3_SCROLL_INDICATOR_END;
2551
2552    /**
2553     * Left-shift required to translate between public scroll indicator flags
2554     * and internal PFLAGS3 flags. When used as a right-shift, translates
2555     * PFLAGS3 flags to public flags.
2556     */
2557    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2558
2559    /** @hide */
2560    @Retention(RetentionPolicy.SOURCE)
2561    @IntDef(flag = true,
2562            value = {
2563                    SCROLL_INDICATOR_TOP,
2564                    SCROLL_INDICATOR_BOTTOM,
2565                    SCROLL_INDICATOR_LEFT,
2566                    SCROLL_INDICATOR_RIGHT,
2567                    SCROLL_INDICATOR_START,
2568                    SCROLL_INDICATOR_END,
2569            })
2570    public @interface ScrollIndicators {}
2571
2572    /**
2573     * Scroll indicator direction for the top edge of the view.
2574     *
2575     * @see #setScrollIndicators(int)
2576     * @see #setScrollIndicators(int, int)
2577     * @see #getScrollIndicators()
2578     */
2579    public static final int SCROLL_INDICATOR_TOP =
2580            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2581
2582    /**
2583     * Scroll indicator direction for the bottom edge of the view.
2584     *
2585     * @see #setScrollIndicators(int)
2586     * @see #setScrollIndicators(int, int)
2587     * @see #getScrollIndicators()
2588     */
2589    public static final int SCROLL_INDICATOR_BOTTOM =
2590            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2591
2592    /**
2593     * Scroll indicator direction for the left edge of the view.
2594     *
2595     * @see #setScrollIndicators(int)
2596     * @see #setScrollIndicators(int, int)
2597     * @see #getScrollIndicators()
2598     */
2599    public static final int SCROLL_INDICATOR_LEFT =
2600            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2601
2602    /**
2603     * Scroll indicator direction for the right edge of the view.
2604     *
2605     * @see #setScrollIndicators(int)
2606     * @see #setScrollIndicators(int, int)
2607     * @see #getScrollIndicators()
2608     */
2609    public static final int SCROLL_INDICATOR_RIGHT =
2610            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2611
2612    /**
2613     * Scroll indicator direction for the starting edge of the view.
2614     * <p>
2615     * Resolved according to the view's layout direction, see
2616     * {@link #getLayoutDirection()} for more information.
2617     *
2618     * @see #setScrollIndicators(int)
2619     * @see #setScrollIndicators(int, int)
2620     * @see #getScrollIndicators()
2621     */
2622    public static final int SCROLL_INDICATOR_START =
2623            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2624
2625    /**
2626     * Scroll indicator direction for the ending edge of the view.
2627     * <p>
2628     * Resolved according to the view's layout direction, see
2629     * {@link #getLayoutDirection()} for more information.
2630     *
2631     * @see #setScrollIndicators(int)
2632     * @see #setScrollIndicators(int, int)
2633     * @see #getScrollIndicators()
2634     */
2635    public static final int SCROLL_INDICATOR_END =
2636            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2637
2638    /**
2639     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2640     * into this view.<p>
2641     */
2642    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2643
2644    /**
2645     * The mask for use with private flags indicating bits used for pointer icon shapes.
2646     */
2647    static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000;
2648
2649    /**
2650     * Left-shift used for pointer icon shape values in private flags.
2651     */
2652    static final int PFLAG3_POINTER_ICON_LSHIFT = 15;
2653
2654    /**
2655     * Value indicating no specific pointer icons.
2656     */
2657    private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT;
2658
2659    /**
2660     * Value indicating {@link PointerIcon.TYPE_NULL}.
2661     */
2662    private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT;
2663
2664    /**
2665     * The base value for other pointer icon shapes.
2666     */
2667    private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT;
2668
2669    /**
2670     * Whether this view has rendered elements that overlap (see {@link
2671     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2672     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2673     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2674     * determined by whatever {@link #hasOverlappingRendering()} returns.
2675     */
2676    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2677
2678    /**
2679     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2680     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2681     */
2682    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2683
2684    /**
2685     * Flag indicating that the view is temporarily detached from the parent view.
2686     *
2687     * @see #onStartTemporaryDetach()
2688     * @see #onFinishTemporaryDetach()
2689     */
2690    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2691
2692    /**
2693     * Flag indicating that the view does not wish to be revealed within its parent
2694     * hierarchy when it gains focus. Expressed in the negative since the historical
2695     * default behavior is to reveal on focus; this flag suppresses that behavior.
2696     *
2697     * @see #setRevealOnFocusHint(boolean)
2698     * @see #getRevealOnFocusHint()
2699     */
2700    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
2701
2702    /* End of masks for mPrivateFlags3 */
2703
2704    /**
2705     * Always allow a user to over-scroll this view, provided it is a
2706     * view that can scroll.
2707     *
2708     * @see #getOverScrollMode()
2709     * @see #setOverScrollMode(int)
2710     */
2711    public static final int OVER_SCROLL_ALWAYS = 0;
2712
2713    /**
2714     * Allow a user to over-scroll this view only if the content is large
2715     * enough to meaningfully scroll, provided it is a view that can scroll.
2716     *
2717     * @see #getOverScrollMode()
2718     * @see #setOverScrollMode(int)
2719     */
2720    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2721
2722    /**
2723     * Never allow a user to over-scroll this view.
2724     *
2725     * @see #getOverScrollMode()
2726     * @see #setOverScrollMode(int)
2727     */
2728    public static final int OVER_SCROLL_NEVER = 2;
2729
2730    /**
2731     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2732     * requested the system UI (status bar) to be visible (the default).
2733     *
2734     * @see #setSystemUiVisibility(int)
2735     */
2736    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2737
2738    /**
2739     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2740     * system UI to enter an unobtrusive "low profile" mode.
2741     *
2742     * <p>This is for use in games, book readers, video players, or any other
2743     * "immersive" application where the usual system chrome is deemed too distracting.
2744     *
2745     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2746     *
2747     * @see #setSystemUiVisibility(int)
2748     */
2749    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2750
2751    /**
2752     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2753     * system navigation be temporarily hidden.
2754     *
2755     * <p>This is an even less obtrusive state than that called for by
2756     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2757     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2758     * those to disappear. This is useful (in conjunction with the
2759     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2760     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2761     * window flags) for displaying content using every last pixel on the display.
2762     *
2763     * <p>There is a limitation: because navigation controls are so important, the least user
2764     * interaction will cause them to reappear immediately.  When this happens, both
2765     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2766     * so that both elements reappear at the same time.
2767     *
2768     * @see #setSystemUiVisibility(int)
2769     */
2770    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2771
2772    /**
2773     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2774     * into the normal fullscreen mode so that its content can take over the screen
2775     * while still allowing the user to interact with the application.
2776     *
2777     * <p>This has the same visual effect as
2778     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2779     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2780     * meaning that non-critical screen decorations (such as the status bar) will be
2781     * hidden while the user is in the View's window, focusing the experience on
2782     * that content.  Unlike the window flag, if you are using ActionBar in
2783     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2784     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2785     * hide the action bar.
2786     *
2787     * <p>This approach to going fullscreen is best used over the window flag when
2788     * it is a transient state -- that is, the application does this at certain
2789     * points in its user interaction where it wants to allow the user to focus
2790     * on content, but not as a continuous state.  For situations where the application
2791     * would like to simply stay full screen the entire time (such as a game that
2792     * wants to take over the screen), the
2793     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2794     * is usually a better approach.  The state set here will be removed by the system
2795     * in various situations (such as the user moving to another application) like
2796     * the other system UI states.
2797     *
2798     * <p>When using this flag, the application should provide some easy facility
2799     * for the user to go out of it.  A common example would be in an e-book
2800     * reader, where tapping on the screen brings back whatever screen and UI
2801     * decorations that had been hidden while the user was immersed in reading
2802     * the book.
2803     *
2804     * @see #setSystemUiVisibility(int)
2805     */
2806    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2807
2808    /**
2809     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2810     * flags, we would like a stable view of the content insets given to
2811     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2812     * will always represent the worst case that the application can expect
2813     * as a continuous state.  In the stock Android UI this is the space for
2814     * the system bar, nav bar, and status bar, but not more transient elements
2815     * such as an input method.
2816     *
2817     * The stable layout your UI sees is based on the system UI modes you can
2818     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2819     * then you will get a stable layout for changes of the
2820     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2821     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2822     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2823     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2824     * with a stable layout.  (Note that you should avoid using
2825     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2826     *
2827     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2828     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2829     * then a hidden status bar will be considered a "stable" state for purposes
2830     * here.  This allows your UI to continually hide the status bar, while still
2831     * using the system UI flags to hide the action bar while still retaining
2832     * a stable layout.  Note that changing the window fullscreen flag will never
2833     * provide a stable layout for a clean transition.
2834     *
2835     * <p>If you are using ActionBar in
2836     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2837     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2838     * insets it adds to those given to the application.
2839     */
2840    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2841
2842    /**
2843     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2844     * to be laid out as if it has requested
2845     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2846     * allows it to avoid artifacts when switching in and out of that mode, at
2847     * the expense that some of its user interface may be covered by screen
2848     * decorations when they are shown.  You can perform layout of your inner
2849     * UI elements to account for the navigation system UI through the
2850     * {@link #fitSystemWindows(Rect)} method.
2851     */
2852    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2853
2854    /**
2855     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2856     * to be laid out as if it has requested
2857     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2858     * allows it to avoid artifacts when switching in and out of that mode, at
2859     * the expense that some of its user interface may be covered by screen
2860     * decorations when they are shown.  You can perform layout of your inner
2861     * UI elements to account for non-fullscreen system UI through the
2862     * {@link #fitSystemWindows(Rect)} method.
2863     */
2864    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2865
2866    /**
2867     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2868     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2869     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2870     * user interaction.
2871     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2872     * has an effect when used in combination with that flag.</p>
2873     */
2874    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2875
2876    /**
2877     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2878     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2879     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2880     * experience while also hiding the system bars.  If this flag is not set,
2881     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2882     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2883     * if the user swipes from the top of the screen.
2884     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2885     * system gestures, such as swiping from the top of the screen.  These transient system bars
2886     * will overlay app’s content, may have some degree of transparency, and will automatically
2887     * hide after a short timeout.
2888     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2889     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2890     * with one or both of those flags.</p>
2891     */
2892    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2893
2894    /**
2895     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2896     * is compatible with light status bar backgrounds.
2897     *
2898     * <p>For this to take effect, the window must request
2899     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2900     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2901     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2902     *         FLAG_TRANSLUCENT_STATUS}.
2903     *
2904     * @see android.R.attr#windowLightStatusBar
2905     */
2906    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2907
2908    /**
2909     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2910     */
2911    @Deprecated
2912    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2913
2914    /**
2915     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2916     */
2917    @Deprecated
2918    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2919
2920    /**
2921     * @hide
2922     *
2923     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2924     * out of the public fields to keep the undefined bits out of the developer's way.
2925     *
2926     * Flag to make the status bar not expandable.  Unless you also
2927     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2928     */
2929    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2930
2931    /**
2932     * @hide
2933     *
2934     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2935     * out of the public fields to keep the undefined bits out of the developer's way.
2936     *
2937     * Flag to hide notification icons and scrolling ticker text.
2938     */
2939    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2940
2941    /**
2942     * @hide
2943     *
2944     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2945     * out of the public fields to keep the undefined bits out of the developer's way.
2946     *
2947     * Flag to disable incoming notification alerts.  This will not block
2948     * icons, but it will block sound, vibrating and other visual or aural notifications.
2949     */
2950    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2951
2952    /**
2953     * @hide
2954     *
2955     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2956     * out of the public fields to keep the undefined bits out of the developer's way.
2957     *
2958     * Flag to hide only the scrolling ticker.  Note that
2959     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2960     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2961     */
2962    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2963
2964    /**
2965     * @hide
2966     *
2967     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2968     * out of the public fields to keep the undefined bits out of the developer's way.
2969     *
2970     * Flag to hide the center system info area.
2971     */
2972    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2973
2974    /**
2975     * @hide
2976     *
2977     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2978     * out of the public fields to keep the undefined bits out of the developer's way.
2979     *
2980     * Flag to hide only the home button.  Don't use this
2981     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2982     */
2983    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2984
2985    /**
2986     * @hide
2987     *
2988     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2989     * out of the public fields to keep the undefined bits out of the developer's way.
2990     *
2991     * Flag to hide only the back button. Don't use this
2992     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2993     */
2994    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2995
2996    /**
2997     * @hide
2998     *
2999     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3000     * out of the public fields to keep the undefined bits out of the developer's way.
3001     *
3002     * Flag to hide only the clock.  You might use this if your activity has
3003     * its own clock making the status bar's clock redundant.
3004     */
3005    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3006
3007    /**
3008     * @hide
3009     *
3010     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3011     * out of the public fields to keep the undefined bits out of the developer's way.
3012     *
3013     * Flag to hide only the recent apps button. Don't use this
3014     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3015     */
3016    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3017
3018    /**
3019     * @hide
3020     *
3021     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3022     * out of the public fields to keep the undefined bits out of the developer's way.
3023     *
3024     * Flag to disable the global search gesture. Don't use this
3025     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3026     */
3027    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3028
3029    /**
3030     * @hide
3031     *
3032     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3033     * out of the public fields to keep the undefined bits out of the developer's way.
3034     *
3035     * Flag to specify that the status bar is displayed in transient mode.
3036     */
3037    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3038
3039    /**
3040     * @hide
3041     *
3042     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3043     * out of the public fields to keep the undefined bits out of the developer's way.
3044     *
3045     * Flag to specify that the navigation bar is displayed in transient mode.
3046     */
3047    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3048
3049    /**
3050     * @hide
3051     *
3052     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3053     * out of the public fields to keep the undefined bits out of the developer's way.
3054     *
3055     * Flag to specify that the hidden status bar would like to be shown.
3056     */
3057    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3058
3059    /**
3060     * @hide
3061     *
3062     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3063     * out of the public fields to keep the undefined bits out of the developer's way.
3064     *
3065     * Flag to specify that the hidden navigation bar would like to be shown.
3066     */
3067    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3068
3069    /**
3070     * @hide
3071     *
3072     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3073     * out of the public fields to keep the undefined bits out of the developer's way.
3074     *
3075     * Flag to specify that the status bar is displayed in translucent mode.
3076     */
3077    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3078
3079    /**
3080     * @hide
3081     *
3082     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3083     * out of the public fields to keep the undefined bits out of the developer's way.
3084     *
3085     * Flag to specify that the navigation bar is displayed in translucent mode.
3086     */
3087    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3088
3089    /**
3090     * @hide
3091     *
3092     * Whether Recents is visible or not.
3093     */
3094    public static final int RECENT_APPS_VISIBLE = 0x00004000;
3095
3096    /**
3097     * @hide
3098     *
3099     * Whether the TV's picture-in-picture is visible or not.
3100     */
3101    public static final int TV_PICTURE_IN_PICTURE_VISIBLE = 0x00010000;
3102
3103    /**
3104     * @hide
3105     *
3106     * Makes navigation bar transparent (but not the status bar).
3107     */
3108    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3109
3110    /**
3111     * @hide
3112     *
3113     * Makes status bar transparent (but not the navigation bar).
3114     */
3115    public static final int STATUS_BAR_TRANSPARENT = 0x0000008;
3116
3117    /**
3118     * @hide
3119     *
3120     * Makes both status bar and navigation bar transparent.
3121     */
3122    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3123            | STATUS_BAR_TRANSPARENT;
3124
3125    /**
3126     * @hide
3127     */
3128    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3129
3130    /**
3131     * These are the system UI flags that can be cleared by events outside
3132     * of an application.  Currently this is just the ability to tap on the
3133     * screen while hiding the navigation bar to have it return.
3134     * @hide
3135     */
3136    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3137            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3138            | SYSTEM_UI_FLAG_FULLSCREEN;
3139
3140    /**
3141     * Flags that can impact the layout in relation to system UI.
3142     */
3143    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3144            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3145            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3146
3147    /** @hide */
3148    @IntDef(flag = true,
3149            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3150    @Retention(RetentionPolicy.SOURCE)
3151    public @interface FindViewFlags {}
3152
3153    /**
3154     * Find views that render the specified text.
3155     *
3156     * @see #findViewsWithText(ArrayList, CharSequence, int)
3157     */
3158    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3159
3160    /**
3161     * Find find views that contain the specified content description.
3162     *
3163     * @see #findViewsWithText(ArrayList, CharSequence, int)
3164     */
3165    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3166
3167    /**
3168     * Find views that contain {@link AccessibilityNodeProvider}. Such
3169     * a View is a root of virtual view hierarchy and may contain the searched
3170     * text. If this flag is set Views with providers are automatically
3171     * added and it is a responsibility of the client to call the APIs of
3172     * the provider to determine whether the virtual tree rooted at this View
3173     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3174     * representing the virtual views with this text.
3175     *
3176     * @see #findViewsWithText(ArrayList, CharSequence, int)
3177     *
3178     * @hide
3179     */
3180    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3181
3182    /**
3183     * The undefined cursor position.
3184     *
3185     * @hide
3186     */
3187    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3188
3189    /**
3190     * Indicates that the screen has changed state and is now off.
3191     *
3192     * @see #onScreenStateChanged(int)
3193     */
3194    public static final int SCREEN_STATE_OFF = 0x0;
3195
3196    /**
3197     * Indicates that the screen has changed state and is now on.
3198     *
3199     * @see #onScreenStateChanged(int)
3200     */
3201    public static final int SCREEN_STATE_ON = 0x1;
3202
3203    /**
3204     * Indicates no axis of view scrolling.
3205     */
3206    public static final int SCROLL_AXIS_NONE = 0;
3207
3208    /**
3209     * Indicates scrolling along the horizontal axis.
3210     */
3211    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3212
3213    /**
3214     * Indicates scrolling along the vertical axis.
3215     */
3216    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3217
3218    /**
3219     * Controls the over-scroll mode for this view.
3220     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3221     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3222     * and {@link #OVER_SCROLL_NEVER}.
3223     */
3224    private int mOverScrollMode;
3225
3226    /**
3227     * The parent this view is attached to.
3228     * {@hide}
3229     *
3230     * @see #getParent()
3231     */
3232    protected ViewParent mParent;
3233
3234    /**
3235     * {@hide}
3236     */
3237    AttachInfo mAttachInfo;
3238
3239    /**
3240     * {@hide}
3241     */
3242    @ViewDebug.ExportedProperty(flagMapping = {
3243        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3244                name = "FORCE_LAYOUT"),
3245        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3246                name = "LAYOUT_REQUIRED"),
3247        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3248            name = "DRAWING_CACHE_INVALID", outputIf = false),
3249        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3250        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3251        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3252        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3253    }, formatToHexString = true)
3254    int mPrivateFlags;
3255    int mPrivateFlags2;
3256    int mPrivateFlags3;
3257
3258    /**
3259     * This view's request for the visibility of the status bar.
3260     * @hide
3261     */
3262    @ViewDebug.ExportedProperty(flagMapping = {
3263        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3264                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3265                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3266        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3267                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3268                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3269        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3270                                equals = SYSTEM_UI_FLAG_VISIBLE,
3271                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3272    }, formatToHexString = true)
3273    int mSystemUiVisibility;
3274
3275    /**
3276     * Reference count for transient state.
3277     * @see #setHasTransientState(boolean)
3278     */
3279    int mTransientStateCount = 0;
3280
3281    /**
3282     * Count of how many windows this view has been attached to.
3283     */
3284    int mWindowAttachCount;
3285
3286    /**
3287     * The layout parameters associated with this view and used by the parent
3288     * {@link android.view.ViewGroup} to determine how this view should be
3289     * laid out.
3290     * {@hide}
3291     */
3292    protected ViewGroup.LayoutParams mLayoutParams;
3293
3294    /**
3295     * The view flags hold various views states.
3296     * {@hide}
3297     */
3298    @ViewDebug.ExportedProperty(formatToHexString = true)
3299    int mViewFlags;
3300
3301    static class TransformationInfo {
3302        /**
3303         * The transform matrix for the View. This transform is calculated internally
3304         * based on the translation, rotation, and scale properties.
3305         *
3306         * Do *not* use this variable directly; instead call getMatrix(), which will
3307         * load the value from the View's RenderNode.
3308         */
3309        private final Matrix mMatrix = new Matrix();
3310
3311        /**
3312         * The inverse transform matrix for the View. This transform is calculated
3313         * internally based on the translation, rotation, and scale properties.
3314         *
3315         * Do *not* use this variable directly; instead call getInverseMatrix(),
3316         * which will load the value from the View's RenderNode.
3317         */
3318        private Matrix mInverseMatrix;
3319
3320        /**
3321         * The opacity of the View. This is a value from 0 to 1, where 0 means
3322         * completely transparent and 1 means completely opaque.
3323         */
3324        @ViewDebug.ExportedProperty
3325        float mAlpha = 1f;
3326
3327        /**
3328         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3329         * property only used by transitions, which is composited with the other alpha
3330         * values to calculate the final visual alpha value.
3331         */
3332        float mTransitionAlpha = 1f;
3333    }
3334
3335    TransformationInfo mTransformationInfo;
3336
3337    /**
3338     * Current clip bounds. to which all drawing of this view are constrained.
3339     */
3340    Rect mClipBounds = null;
3341
3342    private boolean mLastIsOpaque;
3343
3344    /**
3345     * The distance in pixels from the left edge of this view's parent
3346     * to the left edge of this view.
3347     * {@hide}
3348     */
3349    @ViewDebug.ExportedProperty(category = "layout")
3350    protected int mLeft;
3351    /**
3352     * The distance in pixels from the left edge of this view's parent
3353     * to the right edge of this view.
3354     * {@hide}
3355     */
3356    @ViewDebug.ExportedProperty(category = "layout")
3357    protected int mRight;
3358    /**
3359     * The distance in pixels from the top edge of this view's parent
3360     * to the top edge of this view.
3361     * {@hide}
3362     */
3363    @ViewDebug.ExportedProperty(category = "layout")
3364    protected int mTop;
3365    /**
3366     * The distance in pixels from the top edge of this view's parent
3367     * to the bottom edge of this view.
3368     * {@hide}
3369     */
3370    @ViewDebug.ExportedProperty(category = "layout")
3371    protected int mBottom;
3372
3373    /**
3374     * The offset, in pixels, by which the content of this view is scrolled
3375     * horizontally.
3376     * {@hide}
3377     */
3378    @ViewDebug.ExportedProperty(category = "scrolling")
3379    protected int mScrollX;
3380    /**
3381     * The offset, in pixels, by which the content of this view is scrolled
3382     * vertically.
3383     * {@hide}
3384     */
3385    @ViewDebug.ExportedProperty(category = "scrolling")
3386    protected int mScrollY;
3387
3388    /**
3389     * The left padding in pixels, that is the distance in pixels between the
3390     * left edge of this view and the left edge of its content.
3391     * {@hide}
3392     */
3393    @ViewDebug.ExportedProperty(category = "padding")
3394    protected int mPaddingLeft = 0;
3395    /**
3396     * The right padding in pixels, that is the distance in pixels between the
3397     * right edge of this view and the right edge of its content.
3398     * {@hide}
3399     */
3400    @ViewDebug.ExportedProperty(category = "padding")
3401    protected int mPaddingRight = 0;
3402    /**
3403     * The top padding in pixels, that is the distance in pixels between the
3404     * top edge of this view and the top edge of its content.
3405     * {@hide}
3406     */
3407    @ViewDebug.ExportedProperty(category = "padding")
3408    protected int mPaddingTop;
3409    /**
3410     * The bottom padding in pixels, that is the distance in pixels between the
3411     * bottom edge of this view and the bottom edge of its content.
3412     * {@hide}
3413     */
3414    @ViewDebug.ExportedProperty(category = "padding")
3415    protected int mPaddingBottom;
3416
3417    /**
3418     * The layout insets in pixels, that is the distance in pixels between the
3419     * visible edges of this view its bounds.
3420     */
3421    private Insets mLayoutInsets;
3422
3423    /**
3424     * Briefly describes the view and is primarily used for accessibility support.
3425     */
3426    private CharSequence mContentDescription;
3427
3428    /**
3429     * Specifies the id of a view for which this view serves as a label for
3430     * accessibility purposes.
3431     */
3432    private int mLabelForId = View.NO_ID;
3433
3434    /**
3435     * Predicate for matching labeled view id with its label for
3436     * accessibility purposes.
3437     */
3438    private MatchLabelForPredicate mMatchLabelForPredicate;
3439
3440    /**
3441     * Specifies a view before which this one is visited in accessibility traversal.
3442     */
3443    private int mAccessibilityTraversalBeforeId = NO_ID;
3444
3445    /**
3446     * Specifies a view after which this one is visited in accessibility traversal.
3447     */
3448    private int mAccessibilityTraversalAfterId = NO_ID;
3449
3450    /**
3451     * Predicate for matching a view by its id.
3452     */
3453    private MatchIdPredicate mMatchIdPredicate;
3454
3455    /**
3456     * Cache the paddingRight set by the user to append to the scrollbar's size.
3457     *
3458     * @hide
3459     */
3460    @ViewDebug.ExportedProperty(category = "padding")
3461    protected int mUserPaddingRight;
3462
3463    /**
3464     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3465     *
3466     * @hide
3467     */
3468    @ViewDebug.ExportedProperty(category = "padding")
3469    protected int mUserPaddingBottom;
3470
3471    /**
3472     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3473     *
3474     * @hide
3475     */
3476    @ViewDebug.ExportedProperty(category = "padding")
3477    protected int mUserPaddingLeft;
3478
3479    /**
3480     * Cache the paddingStart set by the user to append to the scrollbar's size.
3481     *
3482     */
3483    @ViewDebug.ExportedProperty(category = "padding")
3484    int mUserPaddingStart;
3485
3486    /**
3487     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3488     *
3489     */
3490    @ViewDebug.ExportedProperty(category = "padding")
3491    int mUserPaddingEnd;
3492
3493    /**
3494     * Cache initial left padding.
3495     *
3496     * @hide
3497     */
3498    int mUserPaddingLeftInitial;
3499
3500    /**
3501     * Cache initial right padding.
3502     *
3503     * @hide
3504     */
3505    int mUserPaddingRightInitial;
3506
3507    /**
3508     * Default undefined padding
3509     */
3510    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3511
3512    /**
3513     * Cache if a left padding has been defined
3514     */
3515    private boolean mLeftPaddingDefined = false;
3516
3517    /**
3518     * Cache if a right padding has been defined
3519     */
3520    private boolean mRightPaddingDefined = false;
3521
3522    /**
3523     * @hide
3524     */
3525    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3526    /**
3527     * @hide
3528     */
3529    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3530
3531    private LongSparseLongArray mMeasureCache;
3532
3533    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3534    private Drawable mBackground;
3535    private TintInfo mBackgroundTint;
3536
3537    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3538    private ForegroundInfo mForegroundInfo;
3539
3540    private Drawable mScrollIndicatorDrawable;
3541
3542    /**
3543     * RenderNode used for backgrounds.
3544     * <p>
3545     * When non-null and valid, this is expected to contain an up-to-date copy
3546     * of the background drawable. It is cleared on temporary detach, and reset
3547     * on cleanup.
3548     */
3549    private RenderNode mBackgroundRenderNode;
3550
3551    private int mBackgroundResource;
3552    private boolean mBackgroundSizeChanged;
3553
3554    private String mTransitionName;
3555
3556    static class TintInfo {
3557        ColorStateList mTintList;
3558        PorterDuff.Mode mTintMode;
3559        boolean mHasTintMode;
3560        boolean mHasTintList;
3561    }
3562
3563    private static class ForegroundInfo {
3564        private Drawable mDrawable;
3565        private TintInfo mTintInfo;
3566        private int mGravity = Gravity.FILL;
3567        private boolean mInsidePadding = true;
3568        private boolean mBoundsChanged = true;
3569        private final Rect mSelfBounds = new Rect();
3570        private final Rect mOverlayBounds = new Rect();
3571    }
3572
3573    static class ListenerInfo {
3574        /**
3575         * Listener used to dispatch focus change events.
3576         * This field should be made private, so it is hidden from the SDK.
3577         * {@hide}
3578         */
3579        protected OnFocusChangeListener mOnFocusChangeListener;
3580
3581        /**
3582         * Listeners for layout change events.
3583         */
3584        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3585
3586        protected OnScrollChangeListener mOnScrollChangeListener;
3587
3588        /**
3589         * Listeners for attach events.
3590         */
3591        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3592
3593        /**
3594         * Listener used to dispatch click events.
3595         * This field should be made private, so it is hidden from the SDK.
3596         * {@hide}
3597         */
3598        public OnClickListener mOnClickListener;
3599
3600        /**
3601         * Listener used to dispatch long click events.
3602         * This field should be made private, so it is hidden from the SDK.
3603         * {@hide}
3604         */
3605        protected OnLongClickListener mOnLongClickListener;
3606
3607        /**
3608         * Listener used to dispatch context click events. This field should be made private, so it
3609         * is hidden from the SDK.
3610         * {@hide}
3611         */
3612        protected OnContextClickListener mOnContextClickListener;
3613
3614        /**
3615         * Listener used to build the context menu.
3616         * This field should be made private, so it is hidden from the SDK.
3617         * {@hide}
3618         */
3619        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3620
3621        private OnKeyListener mOnKeyListener;
3622
3623        private OnTouchListener mOnTouchListener;
3624
3625        private OnHoverListener mOnHoverListener;
3626
3627        private OnGenericMotionListener mOnGenericMotionListener;
3628
3629        private OnDragListener mOnDragListener;
3630
3631        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3632
3633        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3634    }
3635
3636    ListenerInfo mListenerInfo;
3637
3638    // Temporary values used to hold (x,y) coordinates when delegating from the
3639    // two-arg performLongClick() method to the legacy no-arg version.
3640    private float mLongClickX = Float.NaN;
3641    private float mLongClickY = Float.NaN;
3642
3643    /**
3644     * The application environment this view lives in.
3645     * This field should be made private, so it is hidden from the SDK.
3646     * {@hide}
3647     */
3648    @ViewDebug.ExportedProperty(deepExport = true)
3649    protected Context mContext;
3650
3651    private final Resources mResources;
3652
3653    private ScrollabilityCache mScrollCache;
3654
3655    private int[] mDrawableState = null;
3656
3657    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3658
3659    /**
3660     * Animator that automatically runs based on state changes.
3661     */
3662    private StateListAnimator mStateListAnimator;
3663
3664    /**
3665     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3666     * the user may specify which view to go to next.
3667     */
3668    private int mNextFocusLeftId = View.NO_ID;
3669
3670    /**
3671     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3672     * the user may specify which view to go to next.
3673     */
3674    private int mNextFocusRightId = View.NO_ID;
3675
3676    /**
3677     * When this view has focus and the next focus is {@link #FOCUS_UP},
3678     * the user may specify which view to go to next.
3679     */
3680    private int mNextFocusUpId = View.NO_ID;
3681
3682    /**
3683     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3684     * the user may specify which view to go to next.
3685     */
3686    private int mNextFocusDownId = View.NO_ID;
3687
3688    /**
3689     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3690     * the user may specify which view to go to next.
3691     */
3692    int mNextFocusForwardId = View.NO_ID;
3693
3694    private CheckForLongPress mPendingCheckForLongPress;
3695    private CheckForTap mPendingCheckForTap = null;
3696    private PerformClick mPerformClick;
3697    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3698
3699    private UnsetPressedState mUnsetPressedState;
3700
3701    /**
3702     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3703     * up event while a long press is invoked as soon as the long press duration is reached, so
3704     * a long press could be performed before the tap is checked, in which case the tap's action
3705     * should not be invoked.
3706     */
3707    private boolean mHasPerformedLongPress;
3708
3709    /**
3710     * Whether a context click button is currently pressed down. This is true when the stylus is
3711     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3712     * pressed. This is false once the button is released or if the stylus has been lifted.
3713     */
3714    private boolean mInContextButtonPress;
3715
3716    /**
3717     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3718     * true after a stylus button press has occured, when the next up event should not be recognized
3719     * as a tap.
3720     */
3721    private boolean mIgnoreNextUpEvent;
3722
3723    /**
3724     * The minimum height of the view. We'll try our best to have the height
3725     * of this view to at least this amount.
3726     */
3727    @ViewDebug.ExportedProperty(category = "measurement")
3728    private int mMinHeight;
3729
3730    /**
3731     * The minimum width of the view. We'll try our best to have the width
3732     * of this view to at least this amount.
3733     */
3734    @ViewDebug.ExportedProperty(category = "measurement")
3735    private int mMinWidth;
3736
3737    /**
3738     * The delegate to handle touch events that are physically in this view
3739     * but should be handled by another view.
3740     */
3741    private TouchDelegate mTouchDelegate = null;
3742
3743    /**
3744     * Solid color to use as a background when creating the drawing cache. Enables
3745     * the cache to use 16 bit bitmaps instead of 32 bit.
3746     */
3747    private int mDrawingCacheBackgroundColor = 0;
3748
3749    /**
3750     * Special tree observer used when mAttachInfo is null.
3751     */
3752    private ViewTreeObserver mFloatingTreeObserver;
3753
3754    /**
3755     * Cache the touch slop from the context that created the view.
3756     */
3757    private int mTouchSlop;
3758
3759    /**
3760     * Object that handles automatic animation of view properties.
3761     */
3762    private ViewPropertyAnimator mAnimator = null;
3763
3764    /**
3765     * List of registered FrameMetricsObservers.
3766     */
3767    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3768
3769    /**
3770     * Flag indicating that a drag can cross window boundaries.  When
3771     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3772     * with this flag set, all visible applications with targetSdkVersion >=
3773     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3774     * in the drag operation and receive the dragged content.
3775     *
3776     * <p>If this is the only flag set, then the drag recipient will only have access to text data
3777     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3778     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
3779     */
3780    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3781
3782    /**
3783     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3784     * request read access to the content URI(s) contained in the {@link ClipData} object.
3785     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3786     */
3787    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3788
3789    /**
3790     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3791     * request write access to the content URI(s) contained in the {@link ClipData} object.
3792     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3793     */
3794    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3795
3796    /**
3797     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3798     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3799     * reboots until explicitly revoked with
3800     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3801     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3802     */
3803    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3804            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3805
3806    /**
3807     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3808     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3809     * match against the original granted URI.
3810     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3811     */
3812    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3813            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3814
3815    /**
3816     * Flag indicating that the drag shadow will be opaque.  When
3817     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3818     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3819     */
3820    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3821
3822    /**
3823     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3824     */
3825    private float mVerticalScrollFactor;
3826
3827    /**
3828     * Position of the vertical scroll bar.
3829     */
3830    private int mVerticalScrollbarPosition;
3831
3832    /**
3833     * Position the scroll bar at the default position as determined by the system.
3834     */
3835    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3836
3837    /**
3838     * Position the scroll bar along the left edge.
3839     */
3840    public static final int SCROLLBAR_POSITION_LEFT = 1;
3841
3842    /**
3843     * Position the scroll bar along the right edge.
3844     */
3845    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3846
3847    /**
3848     * Indicates that the view does not have a layer.
3849     *
3850     * @see #getLayerType()
3851     * @see #setLayerType(int, android.graphics.Paint)
3852     * @see #LAYER_TYPE_SOFTWARE
3853     * @see #LAYER_TYPE_HARDWARE
3854     */
3855    public static final int LAYER_TYPE_NONE = 0;
3856
3857    /**
3858     * <p>Indicates that the view has a software layer. A software layer is backed
3859     * by a bitmap and causes the view to be rendered using Android's software
3860     * rendering pipeline, even if hardware acceleration is enabled.</p>
3861     *
3862     * <p>Software layers have various usages:</p>
3863     * <p>When the application is not using hardware acceleration, a software layer
3864     * is useful to apply a specific color filter and/or blending mode and/or
3865     * translucency to a view and all its children.</p>
3866     * <p>When the application is using hardware acceleration, a software layer
3867     * is useful to render drawing primitives not supported by the hardware
3868     * accelerated pipeline. It can also be used to cache a complex view tree
3869     * into a texture and reduce the complexity of drawing operations. For instance,
3870     * when animating a complex view tree with a translation, a software layer can
3871     * be used to render the view tree only once.</p>
3872     * <p>Software layers should be avoided when the affected view tree updates
3873     * often. Every update will require to re-render the software layer, which can
3874     * potentially be slow (particularly when hardware acceleration is turned on
3875     * since the layer will have to be uploaded into a hardware texture after every
3876     * update.)</p>
3877     *
3878     * @see #getLayerType()
3879     * @see #setLayerType(int, android.graphics.Paint)
3880     * @see #LAYER_TYPE_NONE
3881     * @see #LAYER_TYPE_HARDWARE
3882     */
3883    public static final int LAYER_TYPE_SOFTWARE = 1;
3884
3885    /**
3886     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3887     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3888     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3889     * rendering pipeline, but only if hardware acceleration is turned on for the
3890     * view hierarchy. When hardware acceleration is turned off, hardware layers
3891     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3892     *
3893     * <p>A hardware layer is useful to apply a specific color filter and/or
3894     * blending mode and/or translucency to a view and all its children.</p>
3895     * <p>A hardware layer can be used to cache a complex view tree into a
3896     * texture and reduce the complexity of drawing operations. For instance,
3897     * when animating a complex view tree with a translation, a hardware layer can
3898     * be used to render the view tree only once.</p>
3899     * <p>A hardware layer can also be used to increase the rendering quality when
3900     * rotation transformations are applied on a view. It can also be used to
3901     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3902     *
3903     * @see #getLayerType()
3904     * @see #setLayerType(int, android.graphics.Paint)
3905     * @see #LAYER_TYPE_NONE
3906     * @see #LAYER_TYPE_SOFTWARE
3907     */
3908    public static final int LAYER_TYPE_HARDWARE = 2;
3909
3910    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3911            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3912            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3913            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3914    })
3915    int mLayerType = LAYER_TYPE_NONE;
3916    Paint mLayerPaint;
3917
3918    /**
3919     * Set to true when drawing cache is enabled and cannot be created.
3920     *
3921     * @hide
3922     */
3923    public boolean mCachingFailed;
3924    private Bitmap mDrawingCache;
3925    private Bitmap mUnscaledDrawingCache;
3926
3927    /**
3928     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3929     * <p>
3930     * When non-null and valid, this is expected to contain an up-to-date copy
3931     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3932     * cleanup.
3933     */
3934    final RenderNode mRenderNode;
3935
3936    /**
3937     * Set to true when the view is sending hover accessibility events because it
3938     * is the innermost hovered view.
3939     */
3940    private boolean mSendingHoverAccessibilityEvents;
3941
3942    /**
3943     * Delegate for injecting accessibility functionality.
3944     */
3945    AccessibilityDelegate mAccessibilityDelegate;
3946
3947    /**
3948     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3949     * and add/remove objects to/from the overlay directly through the Overlay methods.
3950     */
3951    ViewOverlay mOverlay;
3952
3953    /**
3954     * The currently active parent view for receiving delegated nested scrolling events.
3955     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3956     * by {@link #stopNestedScroll()} at the same point where we clear
3957     * requestDisallowInterceptTouchEvent.
3958     */
3959    private ViewParent mNestedScrollingParent;
3960
3961    /**
3962     * Consistency verifier for debugging purposes.
3963     * @hide
3964     */
3965    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3966            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3967                    new InputEventConsistencyVerifier(this, 0) : null;
3968
3969    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3970
3971    private int[] mTempNestedScrollConsumed;
3972
3973    /**
3974     * An overlay is going to draw this View instead of being drawn as part of this
3975     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3976     * when this view is invalidated.
3977     */
3978    GhostView mGhostView;
3979
3980    /**
3981     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3982     * @hide
3983     */
3984    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3985    public String[] mAttributes;
3986
3987    /**
3988     * Maps a Resource id to its name.
3989     */
3990    private static SparseArray<String> mAttributeMap;
3991
3992    /**
3993     * Queue of pending runnables. Used to postpone calls to post() until this
3994     * view is attached and has a handler.
3995     */
3996    private HandlerActionQueue mRunQueue;
3997
3998    /**
3999     * The pointer icon when the mouse hovers on this view. The default is null.
4000     */
4001    private PointerIcon mPointerIcon;
4002
4003    /**
4004     * @hide
4005     */
4006    String mStartActivityRequestWho;
4007
4008    @Nullable
4009    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4010
4011    /**
4012     * Simple constructor to use when creating a view from code.
4013     *
4014     * @param context The Context the view is running in, through which it can
4015     *        access the current theme, resources, etc.
4016     */
4017    public View(Context context) {
4018        mContext = context;
4019        mResources = context != null ? context.getResources() : null;
4020        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
4021        // Set some flags defaults
4022        mPrivateFlags2 =
4023                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4024                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4025                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4026                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4027                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4028                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4029        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4030        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4031        mUserPaddingStart = UNDEFINED_PADDING;
4032        mUserPaddingEnd = UNDEFINED_PADDING;
4033        mRenderNode = RenderNode.create(getClass().getName(), this);
4034
4035        if (!sCompatibilityDone && context != null) {
4036            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4037
4038            // Older apps may need this compatibility hack for measurement.
4039            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4040
4041            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4042            // of whether a layout was requested on that View.
4043            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4044
4045            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4046
4047            // In M and newer, our widgets can pass a "hint" value in the size
4048            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4049            // know what the expected parent size is going to be, so e.g. list items can size
4050            // themselves at 1/3 the size of their container. It breaks older apps though,
4051            // specifically apps that use some popular open source libraries.
4052            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4053
4054            // Old versions of the platform would give different results from
4055            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4056            // modes, so we always need to run an additional EXACTLY pass.
4057            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4058
4059            // Prior to N, layout params could change without requiring a
4060            // subsequent call to setLayoutParams() and they would usually
4061            // work. Partial layout breaks this assumption.
4062            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4063
4064            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4065            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4066            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4067
4068            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4069            // in apps so we target check it to avoid breaking existing apps.
4070            sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N;
4071
4072            sCompatibilityDone = true;
4073        }
4074    }
4075
4076    /**
4077     * Constructor that is called when inflating a view from XML. This is called
4078     * when a view is being constructed from an XML file, supplying attributes
4079     * that were specified in the XML file. This version uses a default style of
4080     * 0, so the only attribute values applied are those in the Context's Theme
4081     * and the given AttributeSet.
4082     *
4083     * <p>
4084     * The method onFinishInflate() will be called after all children have been
4085     * added.
4086     *
4087     * @param context The Context the view is running in, through which it can
4088     *        access the current theme, resources, etc.
4089     * @param attrs The attributes of the XML tag that is inflating the view.
4090     * @see #View(Context, AttributeSet, int)
4091     */
4092    public View(Context context, @Nullable AttributeSet attrs) {
4093        this(context, attrs, 0);
4094    }
4095
4096    /**
4097     * Perform inflation from XML and apply a class-specific base style from a
4098     * theme attribute. This constructor of View allows subclasses to use their
4099     * own base style when they are inflating. For example, a Button class's
4100     * constructor would call this version of the super class constructor and
4101     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4102     * allows the theme's button style to modify all of the base view attributes
4103     * (in particular its background) as well as the Button class's attributes.
4104     *
4105     * @param context The Context the view is running in, through which it can
4106     *        access the current theme, resources, etc.
4107     * @param attrs The attributes of the XML tag that is inflating the view.
4108     * @param defStyleAttr An attribute in the current theme that contains a
4109     *        reference to a style resource that supplies default values for
4110     *        the view. Can be 0 to not look for defaults.
4111     * @see #View(Context, AttributeSet)
4112     */
4113    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4114        this(context, attrs, defStyleAttr, 0);
4115    }
4116
4117    /**
4118     * Perform inflation from XML and apply a class-specific base style from a
4119     * theme attribute or style resource. This constructor of View allows
4120     * subclasses to use their own base style when they are inflating.
4121     * <p>
4122     * When determining the final value of a particular attribute, there are
4123     * four inputs that come into play:
4124     * <ol>
4125     * <li>Any attribute values in the given AttributeSet.
4126     * <li>The style resource specified in the AttributeSet (named "style").
4127     * <li>The default style specified by <var>defStyleAttr</var>.
4128     * <li>The default style specified by <var>defStyleRes</var>.
4129     * <li>The base values in this theme.
4130     * </ol>
4131     * <p>
4132     * Each of these inputs is considered in-order, with the first listed taking
4133     * precedence over the following ones. In other words, if in the
4134     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4135     * , then the button's text will <em>always</em> be black, regardless of
4136     * what is specified in any of the styles.
4137     *
4138     * @param context The Context the view is running in, through which it can
4139     *        access the current theme, resources, etc.
4140     * @param attrs The attributes of the XML tag that is inflating the view.
4141     * @param defStyleAttr An attribute in the current theme that contains a
4142     *        reference to a style resource that supplies default values for
4143     *        the view. Can be 0 to not look for defaults.
4144     * @param defStyleRes A resource identifier of a style resource that
4145     *        supplies default values for the view, used only if
4146     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4147     *        to not look for defaults.
4148     * @see #View(Context, AttributeSet, int)
4149     */
4150    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4151        this(context);
4152
4153        final TypedArray a = context.obtainStyledAttributes(
4154                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4155
4156        if (mDebugViewAttributes) {
4157            saveAttributeData(attrs, a);
4158        }
4159
4160        Drawable background = null;
4161
4162        int leftPadding = -1;
4163        int topPadding = -1;
4164        int rightPadding = -1;
4165        int bottomPadding = -1;
4166        int startPadding = UNDEFINED_PADDING;
4167        int endPadding = UNDEFINED_PADDING;
4168
4169        int padding = -1;
4170
4171        int viewFlagValues = 0;
4172        int viewFlagMasks = 0;
4173
4174        boolean setScrollContainer = false;
4175
4176        int x = 0;
4177        int y = 0;
4178
4179        float tx = 0;
4180        float ty = 0;
4181        float tz = 0;
4182        float elevation = 0;
4183        float rotation = 0;
4184        float rotationX = 0;
4185        float rotationY = 0;
4186        float sx = 1f;
4187        float sy = 1f;
4188        boolean transformSet = false;
4189
4190        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4191        int overScrollMode = mOverScrollMode;
4192        boolean initializeScrollbars = false;
4193        boolean initializeScrollIndicators = false;
4194
4195        boolean startPaddingDefined = false;
4196        boolean endPaddingDefined = false;
4197        boolean leftPaddingDefined = false;
4198        boolean rightPaddingDefined = false;
4199
4200        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4201
4202        final int N = a.getIndexCount();
4203        for (int i = 0; i < N; i++) {
4204            int attr = a.getIndex(i);
4205            switch (attr) {
4206                case com.android.internal.R.styleable.View_background:
4207                    background = a.getDrawable(attr);
4208                    break;
4209                case com.android.internal.R.styleable.View_padding:
4210                    padding = a.getDimensionPixelSize(attr, -1);
4211                    mUserPaddingLeftInitial = padding;
4212                    mUserPaddingRightInitial = padding;
4213                    leftPaddingDefined = true;
4214                    rightPaddingDefined = true;
4215                    break;
4216                 case com.android.internal.R.styleable.View_paddingLeft:
4217                    leftPadding = a.getDimensionPixelSize(attr, -1);
4218                    mUserPaddingLeftInitial = leftPadding;
4219                    leftPaddingDefined = true;
4220                    break;
4221                case com.android.internal.R.styleable.View_paddingTop:
4222                    topPadding = a.getDimensionPixelSize(attr, -1);
4223                    break;
4224                case com.android.internal.R.styleable.View_paddingRight:
4225                    rightPadding = a.getDimensionPixelSize(attr, -1);
4226                    mUserPaddingRightInitial = rightPadding;
4227                    rightPaddingDefined = true;
4228                    break;
4229                case com.android.internal.R.styleable.View_paddingBottom:
4230                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4231                    break;
4232                case com.android.internal.R.styleable.View_paddingStart:
4233                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4234                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4235                    break;
4236                case com.android.internal.R.styleable.View_paddingEnd:
4237                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4238                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4239                    break;
4240                case com.android.internal.R.styleable.View_scrollX:
4241                    x = a.getDimensionPixelOffset(attr, 0);
4242                    break;
4243                case com.android.internal.R.styleable.View_scrollY:
4244                    y = a.getDimensionPixelOffset(attr, 0);
4245                    break;
4246                case com.android.internal.R.styleable.View_alpha:
4247                    setAlpha(a.getFloat(attr, 1f));
4248                    break;
4249                case com.android.internal.R.styleable.View_transformPivotX:
4250                    setPivotX(a.getDimension(attr, 0));
4251                    break;
4252                case com.android.internal.R.styleable.View_transformPivotY:
4253                    setPivotY(a.getDimension(attr, 0));
4254                    break;
4255                case com.android.internal.R.styleable.View_translationX:
4256                    tx = a.getDimension(attr, 0);
4257                    transformSet = true;
4258                    break;
4259                case com.android.internal.R.styleable.View_translationY:
4260                    ty = a.getDimension(attr, 0);
4261                    transformSet = true;
4262                    break;
4263                case com.android.internal.R.styleable.View_translationZ:
4264                    tz = a.getDimension(attr, 0);
4265                    transformSet = true;
4266                    break;
4267                case com.android.internal.R.styleable.View_elevation:
4268                    elevation = a.getDimension(attr, 0);
4269                    transformSet = true;
4270                    break;
4271                case com.android.internal.R.styleable.View_rotation:
4272                    rotation = a.getFloat(attr, 0);
4273                    transformSet = true;
4274                    break;
4275                case com.android.internal.R.styleable.View_rotationX:
4276                    rotationX = a.getFloat(attr, 0);
4277                    transformSet = true;
4278                    break;
4279                case com.android.internal.R.styleable.View_rotationY:
4280                    rotationY = a.getFloat(attr, 0);
4281                    transformSet = true;
4282                    break;
4283                case com.android.internal.R.styleable.View_scaleX:
4284                    sx = a.getFloat(attr, 1f);
4285                    transformSet = true;
4286                    break;
4287                case com.android.internal.R.styleable.View_scaleY:
4288                    sy = a.getFloat(attr, 1f);
4289                    transformSet = true;
4290                    break;
4291                case com.android.internal.R.styleable.View_id:
4292                    mID = a.getResourceId(attr, NO_ID);
4293                    break;
4294                case com.android.internal.R.styleable.View_tag:
4295                    mTag = a.getText(attr);
4296                    break;
4297                case com.android.internal.R.styleable.View_fitsSystemWindows:
4298                    if (a.getBoolean(attr, false)) {
4299                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4300                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4301                    }
4302                    break;
4303                case com.android.internal.R.styleable.View_focusable:
4304                    if (a.getBoolean(attr, false)) {
4305                        viewFlagValues |= FOCUSABLE;
4306                        viewFlagMasks |= FOCUSABLE_MASK;
4307                    }
4308                    break;
4309                case com.android.internal.R.styleable.View_focusableInTouchMode:
4310                    if (a.getBoolean(attr, false)) {
4311                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4312                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4313                    }
4314                    break;
4315                case com.android.internal.R.styleable.View_clickable:
4316                    if (a.getBoolean(attr, false)) {
4317                        viewFlagValues |= CLICKABLE;
4318                        viewFlagMasks |= CLICKABLE;
4319                    }
4320                    break;
4321                case com.android.internal.R.styleable.View_longClickable:
4322                    if (a.getBoolean(attr, false)) {
4323                        viewFlagValues |= LONG_CLICKABLE;
4324                        viewFlagMasks |= LONG_CLICKABLE;
4325                    }
4326                    break;
4327                case com.android.internal.R.styleable.View_contextClickable:
4328                    if (a.getBoolean(attr, false)) {
4329                        viewFlagValues |= CONTEXT_CLICKABLE;
4330                        viewFlagMasks |= CONTEXT_CLICKABLE;
4331                    }
4332                    break;
4333                case com.android.internal.R.styleable.View_saveEnabled:
4334                    if (!a.getBoolean(attr, true)) {
4335                        viewFlagValues |= SAVE_DISABLED;
4336                        viewFlagMasks |= SAVE_DISABLED_MASK;
4337                    }
4338                    break;
4339                case com.android.internal.R.styleable.View_duplicateParentState:
4340                    if (a.getBoolean(attr, false)) {
4341                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4342                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4343                    }
4344                    break;
4345                case com.android.internal.R.styleable.View_visibility:
4346                    final int visibility = a.getInt(attr, 0);
4347                    if (visibility != 0) {
4348                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4349                        viewFlagMasks |= VISIBILITY_MASK;
4350                    }
4351                    break;
4352                case com.android.internal.R.styleable.View_layoutDirection:
4353                    // Clear any layout direction flags (included resolved bits) already set
4354                    mPrivateFlags2 &=
4355                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4356                    // Set the layout direction flags depending on the value of the attribute
4357                    final int layoutDirection = a.getInt(attr, -1);
4358                    final int value = (layoutDirection != -1) ?
4359                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4360                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4361                    break;
4362                case com.android.internal.R.styleable.View_drawingCacheQuality:
4363                    final int cacheQuality = a.getInt(attr, 0);
4364                    if (cacheQuality != 0) {
4365                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4366                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4367                    }
4368                    break;
4369                case com.android.internal.R.styleable.View_contentDescription:
4370                    setContentDescription(a.getString(attr));
4371                    break;
4372                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4373                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4374                    break;
4375                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4376                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4377                    break;
4378                case com.android.internal.R.styleable.View_labelFor:
4379                    setLabelFor(a.getResourceId(attr, NO_ID));
4380                    break;
4381                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4382                    if (!a.getBoolean(attr, true)) {
4383                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4384                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4385                    }
4386                    break;
4387                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4388                    if (!a.getBoolean(attr, true)) {
4389                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4390                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4391                    }
4392                    break;
4393                case R.styleable.View_scrollbars:
4394                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4395                    if (scrollbars != SCROLLBARS_NONE) {
4396                        viewFlagValues |= scrollbars;
4397                        viewFlagMasks |= SCROLLBARS_MASK;
4398                        initializeScrollbars = true;
4399                    }
4400                    break;
4401                //noinspection deprecation
4402                case R.styleable.View_fadingEdge:
4403                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4404                        // Ignore the attribute starting with ICS
4405                        break;
4406                    }
4407                    // With builds < ICS, fall through and apply fading edges
4408                case R.styleable.View_requiresFadingEdge:
4409                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4410                    if (fadingEdge != FADING_EDGE_NONE) {
4411                        viewFlagValues |= fadingEdge;
4412                        viewFlagMasks |= FADING_EDGE_MASK;
4413                        initializeFadingEdgeInternal(a);
4414                    }
4415                    break;
4416                case R.styleable.View_scrollbarStyle:
4417                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4418                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4419                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4420                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4421                    }
4422                    break;
4423                case R.styleable.View_isScrollContainer:
4424                    setScrollContainer = true;
4425                    if (a.getBoolean(attr, false)) {
4426                        setScrollContainer(true);
4427                    }
4428                    break;
4429                case com.android.internal.R.styleable.View_keepScreenOn:
4430                    if (a.getBoolean(attr, false)) {
4431                        viewFlagValues |= KEEP_SCREEN_ON;
4432                        viewFlagMasks |= KEEP_SCREEN_ON;
4433                    }
4434                    break;
4435                case R.styleable.View_filterTouchesWhenObscured:
4436                    if (a.getBoolean(attr, false)) {
4437                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4438                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4439                    }
4440                    break;
4441                case R.styleable.View_nextFocusLeft:
4442                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4443                    break;
4444                case R.styleable.View_nextFocusRight:
4445                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4446                    break;
4447                case R.styleable.View_nextFocusUp:
4448                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4449                    break;
4450                case R.styleable.View_nextFocusDown:
4451                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4452                    break;
4453                case R.styleable.View_nextFocusForward:
4454                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4455                    break;
4456                case R.styleable.View_minWidth:
4457                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4458                    break;
4459                case R.styleable.View_minHeight:
4460                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4461                    break;
4462                case R.styleable.View_onClick:
4463                    if (context.isRestricted()) {
4464                        throw new IllegalStateException("The android:onClick attribute cannot "
4465                                + "be used within a restricted context");
4466                    }
4467
4468                    final String handlerName = a.getString(attr);
4469                    if (handlerName != null) {
4470                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4471                    }
4472                    break;
4473                case R.styleable.View_overScrollMode:
4474                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4475                    break;
4476                case R.styleable.View_verticalScrollbarPosition:
4477                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4478                    break;
4479                case R.styleable.View_layerType:
4480                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4481                    break;
4482                case R.styleable.View_textDirection:
4483                    // Clear any text direction flag already set
4484                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4485                    // Set the text direction flags depending on the value of the attribute
4486                    final int textDirection = a.getInt(attr, -1);
4487                    if (textDirection != -1) {
4488                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4489                    }
4490                    break;
4491                case R.styleable.View_textAlignment:
4492                    // Clear any text alignment flag already set
4493                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4494                    // Set the text alignment flag depending on the value of the attribute
4495                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4496                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4497                    break;
4498                case R.styleable.View_importantForAccessibility:
4499                    setImportantForAccessibility(a.getInt(attr,
4500                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4501                    break;
4502                case R.styleable.View_accessibilityLiveRegion:
4503                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4504                    break;
4505                case R.styleable.View_transitionName:
4506                    setTransitionName(a.getString(attr));
4507                    break;
4508                case R.styleable.View_nestedScrollingEnabled:
4509                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4510                    break;
4511                case R.styleable.View_stateListAnimator:
4512                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4513                            a.getResourceId(attr, 0)));
4514                    break;
4515                case R.styleable.View_backgroundTint:
4516                    // This will get applied later during setBackground().
4517                    if (mBackgroundTint == null) {
4518                        mBackgroundTint = new TintInfo();
4519                    }
4520                    mBackgroundTint.mTintList = a.getColorStateList(
4521                            R.styleable.View_backgroundTint);
4522                    mBackgroundTint.mHasTintList = true;
4523                    break;
4524                case R.styleable.View_backgroundTintMode:
4525                    // This will get applied later during setBackground().
4526                    if (mBackgroundTint == null) {
4527                        mBackgroundTint = new TintInfo();
4528                    }
4529                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4530                            R.styleable.View_backgroundTintMode, -1), null);
4531                    mBackgroundTint.mHasTintMode = true;
4532                    break;
4533                case R.styleable.View_outlineProvider:
4534                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4535                            PROVIDER_BACKGROUND));
4536                    break;
4537                case R.styleable.View_foreground:
4538                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4539                        setForeground(a.getDrawable(attr));
4540                    }
4541                    break;
4542                case R.styleable.View_foregroundGravity:
4543                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4544                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4545                    }
4546                    break;
4547                case R.styleable.View_foregroundTintMode:
4548                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4549                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4550                    }
4551                    break;
4552                case R.styleable.View_foregroundTint:
4553                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4554                        setForegroundTintList(a.getColorStateList(attr));
4555                    }
4556                    break;
4557                case R.styleable.View_foregroundInsidePadding:
4558                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4559                        if (mForegroundInfo == null) {
4560                            mForegroundInfo = new ForegroundInfo();
4561                        }
4562                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4563                                mForegroundInfo.mInsidePadding);
4564                    }
4565                    break;
4566                case R.styleable.View_scrollIndicators:
4567                    final int scrollIndicators =
4568                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4569                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4570                    if (scrollIndicators != 0) {
4571                        mPrivateFlags3 |= scrollIndicators;
4572                        initializeScrollIndicators = true;
4573                    }
4574                    break;
4575                case R.styleable.View_pointerIcon:
4576                    final int resourceId = a.getResourceId(attr, 0);
4577                    if (resourceId != 0) {
4578                        setPointerIcon(PointerIcon.load(
4579                                context.getResources(), resourceId));
4580                    } else {
4581                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4582                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4583                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4584                        }
4585                    }
4586                    break;
4587                case R.styleable.View_forceHasOverlappingRendering:
4588                    if (a.peekValue(attr) != null) {
4589                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4590                    }
4591                    break;
4592
4593            }
4594        }
4595
4596        setOverScrollMode(overScrollMode);
4597
4598        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4599        // the resolved layout direction). Those cached values will be used later during padding
4600        // resolution.
4601        mUserPaddingStart = startPadding;
4602        mUserPaddingEnd = endPadding;
4603
4604        if (background != null) {
4605            setBackground(background);
4606        }
4607
4608        // setBackground above will record that padding is currently provided by the background.
4609        // If we have padding specified via xml, record that here instead and use it.
4610        mLeftPaddingDefined = leftPaddingDefined;
4611        mRightPaddingDefined = rightPaddingDefined;
4612
4613        if (padding >= 0) {
4614            leftPadding = padding;
4615            topPadding = padding;
4616            rightPadding = padding;
4617            bottomPadding = padding;
4618            mUserPaddingLeftInitial = padding;
4619            mUserPaddingRightInitial = padding;
4620        }
4621
4622        if (isRtlCompatibilityMode()) {
4623            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4624            // left / right padding are used if defined (meaning here nothing to do). If they are not
4625            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4626            // start / end and resolve them as left / right (layout direction is not taken into account).
4627            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4628            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4629            // defined.
4630            if (!mLeftPaddingDefined && startPaddingDefined) {
4631                leftPadding = startPadding;
4632            }
4633            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4634            if (!mRightPaddingDefined && endPaddingDefined) {
4635                rightPadding = endPadding;
4636            }
4637            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4638        } else {
4639            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4640            // values defined. Otherwise, left /right values are used.
4641            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4642            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4643            // defined.
4644            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4645
4646            if (mLeftPaddingDefined && !hasRelativePadding) {
4647                mUserPaddingLeftInitial = leftPadding;
4648            }
4649            if (mRightPaddingDefined && !hasRelativePadding) {
4650                mUserPaddingRightInitial = rightPadding;
4651            }
4652        }
4653
4654        internalSetPadding(
4655                mUserPaddingLeftInitial,
4656                topPadding >= 0 ? topPadding : mPaddingTop,
4657                mUserPaddingRightInitial,
4658                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4659
4660        if (viewFlagMasks != 0) {
4661            setFlags(viewFlagValues, viewFlagMasks);
4662        }
4663
4664        if (initializeScrollbars) {
4665            initializeScrollbarsInternal(a);
4666        }
4667
4668        if (initializeScrollIndicators) {
4669            initializeScrollIndicatorsInternal();
4670        }
4671
4672        a.recycle();
4673
4674        // Needs to be called after mViewFlags is set
4675        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4676            recomputePadding();
4677        }
4678
4679        if (x != 0 || y != 0) {
4680            scrollTo(x, y);
4681        }
4682
4683        if (transformSet) {
4684            setTranslationX(tx);
4685            setTranslationY(ty);
4686            setTranslationZ(tz);
4687            setElevation(elevation);
4688            setRotation(rotation);
4689            setRotationX(rotationX);
4690            setRotationY(rotationY);
4691            setScaleX(sx);
4692            setScaleY(sy);
4693        }
4694
4695        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4696            setScrollContainer(true);
4697        }
4698
4699        computeOpaqueFlags();
4700    }
4701
4702    /**
4703     * An implementation of OnClickListener that attempts to lazily load a
4704     * named click handling method from a parent or ancestor context.
4705     */
4706    private static class DeclaredOnClickListener implements OnClickListener {
4707        private final View mHostView;
4708        private final String mMethodName;
4709
4710        private Method mResolvedMethod;
4711        private Context mResolvedContext;
4712
4713        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4714            mHostView = hostView;
4715            mMethodName = methodName;
4716        }
4717
4718        @Override
4719        public void onClick(@NonNull View v) {
4720            if (mResolvedMethod == null) {
4721                resolveMethod(mHostView.getContext(), mMethodName);
4722            }
4723
4724            try {
4725                mResolvedMethod.invoke(mResolvedContext, v);
4726            } catch (IllegalAccessException e) {
4727                throw new IllegalStateException(
4728                        "Could not execute non-public method for android:onClick", e);
4729            } catch (InvocationTargetException e) {
4730                throw new IllegalStateException(
4731                        "Could not execute method for android:onClick", e);
4732            }
4733        }
4734
4735        @NonNull
4736        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4737            while (context != null) {
4738                try {
4739                    if (!context.isRestricted()) {
4740                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4741                        if (method != null) {
4742                            mResolvedMethod = method;
4743                            mResolvedContext = context;
4744                            return;
4745                        }
4746                    }
4747                } catch (NoSuchMethodException e) {
4748                    // Failed to find method, keep searching up the hierarchy.
4749                }
4750
4751                if (context instanceof ContextWrapper) {
4752                    context = ((ContextWrapper) context).getBaseContext();
4753                } else {
4754                    // Can't search up the hierarchy, null out and fail.
4755                    context = null;
4756                }
4757            }
4758
4759            final int id = mHostView.getId();
4760            final String idText = id == NO_ID ? "" : " with id '"
4761                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4762            throw new IllegalStateException("Could not find method " + mMethodName
4763                    + "(View) in a parent or ancestor Context for android:onClick "
4764                    + "attribute defined on view " + mHostView.getClass() + idText);
4765        }
4766    }
4767
4768    /**
4769     * Non-public constructor for use in testing
4770     */
4771    View() {
4772        mResources = null;
4773        mRenderNode = RenderNode.create(getClass().getName(), this);
4774    }
4775
4776    private static SparseArray<String> getAttributeMap() {
4777        if (mAttributeMap == null) {
4778            mAttributeMap = new SparseArray<>();
4779        }
4780        return mAttributeMap;
4781    }
4782
4783    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4784        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4785        final int indexCount = t.getIndexCount();
4786        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4787
4788        int i = 0;
4789
4790        // Store raw XML attributes.
4791        for (int j = 0; j < attrsCount; ++j) {
4792            attributes[i] = attrs.getAttributeName(j);
4793            attributes[i + 1] = attrs.getAttributeValue(j);
4794            i += 2;
4795        }
4796
4797        // Store resolved styleable attributes.
4798        final Resources res = t.getResources();
4799        final SparseArray<String> attributeMap = getAttributeMap();
4800        for (int j = 0; j < indexCount; ++j) {
4801            final int index = t.getIndex(j);
4802            if (!t.hasValueOrEmpty(index)) {
4803                // Value is undefined. Skip it.
4804                continue;
4805            }
4806
4807            final int resourceId = t.getResourceId(index, 0);
4808            if (resourceId == 0) {
4809                // Value is not a reference. Skip it.
4810                continue;
4811            }
4812
4813            String resourceName = attributeMap.get(resourceId);
4814            if (resourceName == null) {
4815                try {
4816                    resourceName = res.getResourceName(resourceId);
4817                } catch (Resources.NotFoundException e) {
4818                    resourceName = "0x" + Integer.toHexString(resourceId);
4819                }
4820                attributeMap.put(resourceId, resourceName);
4821            }
4822
4823            attributes[i] = resourceName;
4824            attributes[i + 1] = t.getString(index);
4825            i += 2;
4826        }
4827
4828        // Trim to fit contents.
4829        final String[] trimmed = new String[i];
4830        System.arraycopy(attributes, 0, trimmed, 0, i);
4831        mAttributes = trimmed;
4832    }
4833
4834    public String toString() {
4835        StringBuilder out = new StringBuilder(128);
4836        out.append(getClass().getName());
4837        out.append('{');
4838        out.append(Integer.toHexString(System.identityHashCode(this)));
4839        out.append(' ');
4840        switch (mViewFlags&VISIBILITY_MASK) {
4841            case VISIBLE: out.append('V'); break;
4842            case INVISIBLE: out.append('I'); break;
4843            case GONE: out.append('G'); break;
4844            default: out.append('.'); break;
4845        }
4846        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4847        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4848        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4849        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4850        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4851        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4852        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4853        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4854        out.append(' ');
4855        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4856        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4857        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4858        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4859            out.append('p');
4860        } else {
4861            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4862        }
4863        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4864        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4865        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4866        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4867        out.append(' ');
4868        out.append(mLeft);
4869        out.append(',');
4870        out.append(mTop);
4871        out.append('-');
4872        out.append(mRight);
4873        out.append(',');
4874        out.append(mBottom);
4875        final int id = getId();
4876        if (id != NO_ID) {
4877            out.append(" #");
4878            out.append(Integer.toHexString(id));
4879            final Resources r = mResources;
4880            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
4881                try {
4882                    String pkgname;
4883                    switch (id&0xff000000) {
4884                        case 0x7f000000:
4885                            pkgname="app";
4886                            break;
4887                        case 0x01000000:
4888                            pkgname="android";
4889                            break;
4890                        default:
4891                            pkgname = r.getResourcePackageName(id);
4892                            break;
4893                    }
4894                    String typename = r.getResourceTypeName(id);
4895                    String entryname = r.getResourceEntryName(id);
4896                    out.append(" ");
4897                    out.append(pkgname);
4898                    out.append(":");
4899                    out.append(typename);
4900                    out.append("/");
4901                    out.append(entryname);
4902                } catch (Resources.NotFoundException e) {
4903                }
4904            }
4905        }
4906        out.append("}");
4907        return out.toString();
4908    }
4909
4910    /**
4911     * <p>
4912     * Initializes the fading edges from a given set of styled attributes. This
4913     * method should be called by subclasses that need fading edges and when an
4914     * instance of these subclasses is created programmatically rather than
4915     * being inflated from XML. This method is automatically called when the XML
4916     * is inflated.
4917     * </p>
4918     *
4919     * @param a the styled attributes set to initialize the fading edges from
4920     *
4921     * @removed
4922     */
4923    protected void initializeFadingEdge(TypedArray a) {
4924        // This method probably shouldn't have been included in the SDK to begin with.
4925        // It relies on 'a' having been initialized using an attribute filter array that is
4926        // not publicly available to the SDK. The old method has been renamed
4927        // to initializeFadingEdgeInternal and hidden for framework use only;
4928        // this one initializes using defaults to make it safe to call for apps.
4929
4930        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4931
4932        initializeFadingEdgeInternal(arr);
4933
4934        arr.recycle();
4935    }
4936
4937    /**
4938     * <p>
4939     * Initializes the fading edges from a given set of styled attributes. This
4940     * method should be called by subclasses that need fading edges and when an
4941     * instance of these subclasses is created programmatically rather than
4942     * being inflated from XML. This method is automatically called when the XML
4943     * is inflated.
4944     * </p>
4945     *
4946     * @param a the styled attributes set to initialize the fading edges from
4947     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4948     */
4949    protected void initializeFadingEdgeInternal(TypedArray a) {
4950        initScrollCache();
4951
4952        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4953                R.styleable.View_fadingEdgeLength,
4954                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4955    }
4956
4957    /**
4958     * Returns the size of the vertical faded edges used to indicate that more
4959     * content in this view is visible.
4960     *
4961     * @return The size in pixels of the vertical faded edge or 0 if vertical
4962     *         faded edges are not enabled for this view.
4963     * @attr ref android.R.styleable#View_fadingEdgeLength
4964     */
4965    public int getVerticalFadingEdgeLength() {
4966        if (isVerticalFadingEdgeEnabled()) {
4967            ScrollabilityCache cache = mScrollCache;
4968            if (cache != null) {
4969                return cache.fadingEdgeLength;
4970            }
4971        }
4972        return 0;
4973    }
4974
4975    /**
4976     * Set the size of the faded edge used to indicate that more content in this
4977     * view is available.  Will not change whether the fading edge is enabled; use
4978     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4979     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4980     * for the vertical or horizontal fading edges.
4981     *
4982     * @param length The size in pixels of the faded edge used to indicate that more
4983     *        content in this view is visible.
4984     */
4985    public void setFadingEdgeLength(int length) {
4986        initScrollCache();
4987        mScrollCache.fadingEdgeLength = length;
4988    }
4989
4990    /**
4991     * Returns the size of the horizontal faded edges used to indicate that more
4992     * content in this view is visible.
4993     *
4994     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4995     *         faded edges are not enabled for this view.
4996     * @attr ref android.R.styleable#View_fadingEdgeLength
4997     */
4998    public int getHorizontalFadingEdgeLength() {
4999        if (isHorizontalFadingEdgeEnabled()) {
5000            ScrollabilityCache cache = mScrollCache;
5001            if (cache != null) {
5002                return cache.fadingEdgeLength;
5003            }
5004        }
5005        return 0;
5006    }
5007
5008    /**
5009     * Returns the width of the vertical scrollbar.
5010     *
5011     * @return The width in pixels of the vertical scrollbar or 0 if there
5012     *         is no vertical scrollbar.
5013     */
5014    public int getVerticalScrollbarWidth() {
5015        ScrollabilityCache cache = mScrollCache;
5016        if (cache != null) {
5017            ScrollBarDrawable scrollBar = cache.scrollBar;
5018            if (scrollBar != null) {
5019                int size = scrollBar.getSize(true);
5020                if (size <= 0) {
5021                    size = cache.scrollBarSize;
5022                }
5023                return size;
5024            }
5025            return 0;
5026        }
5027        return 0;
5028    }
5029
5030    /**
5031     * Returns the height of the horizontal scrollbar.
5032     *
5033     * @return The height in pixels of the horizontal scrollbar or 0 if
5034     *         there is no horizontal scrollbar.
5035     */
5036    protected int getHorizontalScrollbarHeight() {
5037        ScrollabilityCache cache = mScrollCache;
5038        if (cache != null) {
5039            ScrollBarDrawable scrollBar = cache.scrollBar;
5040            if (scrollBar != null) {
5041                int size = scrollBar.getSize(false);
5042                if (size <= 0) {
5043                    size = cache.scrollBarSize;
5044                }
5045                return size;
5046            }
5047            return 0;
5048        }
5049        return 0;
5050    }
5051
5052    /**
5053     * <p>
5054     * Initializes the scrollbars from a given set of styled attributes. This
5055     * method should be called by subclasses that need scrollbars and when an
5056     * instance of these subclasses is created programmatically rather than
5057     * being inflated from XML. This method is automatically called when the XML
5058     * is inflated.
5059     * </p>
5060     *
5061     * @param a the styled attributes set to initialize the scrollbars from
5062     *
5063     * @removed
5064     */
5065    protected void initializeScrollbars(TypedArray a) {
5066        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5067        // using the View filter array which is not available to the SDK. As such, internal
5068        // framework usage now uses initializeScrollbarsInternal and we grab a default
5069        // TypedArray with the right filter instead here.
5070        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5071
5072        initializeScrollbarsInternal(arr);
5073
5074        // We ignored the method parameter. Recycle the one we actually did use.
5075        arr.recycle();
5076    }
5077
5078    /**
5079     * <p>
5080     * Initializes the scrollbars from a given set of styled attributes. This
5081     * method should be called by subclasses that need scrollbars and when an
5082     * instance of these subclasses is created programmatically rather than
5083     * being inflated from XML. This method is automatically called when the XML
5084     * is inflated.
5085     * </p>
5086     *
5087     * @param a the styled attributes set to initialize the scrollbars from
5088     * @hide
5089     */
5090    protected void initializeScrollbarsInternal(TypedArray a) {
5091        initScrollCache();
5092
5093        final ScrollabilityCache scrollabilityCache = mScrollCache;
5094
5095        if (scrollabilityCache.scrollBar == null) {
5096            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5097            scrollabilityCache.scrollBar.setState(getDrawableState());
5098            scrollabilityCache.scrollBar.setCallback(this);
5099        }
5100
5101        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5102
5103        if (!fadeScrollbars) {
5104            scrollabilityCache.state = ScrollabilityCache.ON;
5105        }
5106        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5107
5108
5109        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5110                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5111                        .getScrollBarFadeDuration());
5112        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5113                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5114                ViewConfiguration.getScrollDefaultDelay());
5115
5116
5117        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5118                com.android.internal.R.styleable.View_scrollbarSize,
5119                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5120
5121        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5122        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5123
5124        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5125        if (thumb != null) {
5126            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5127        }
5128
5129        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5130                false);
5131        if (alwaysDraw) {
5132            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5133        }
5134
5135        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5136        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5137
5138        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5139        if (thumb != null) {
5140            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5141        }
5142
5143        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5144                false);
5145        if (alwaysDraw) {
5146            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5147        }
5148
5149        // Apply layout direction to the new Drawables if needed
5150        final int layoutDirection = getLayoutDirection();
5151        if (track != null) {
5152            track.setLayoutDirection(layoutDirection);
5153        }
5154        if (thumb != null) {
5155            thumb.setLayoutDirection(layoutDirection);
5156        }
5157
5158        // Re-apply user/background padding so that scrollbar(s) get added
5159        resolvePadding();
5160    }
5161
5162    private void initializeScrollIndicatorsInternal() {
5163        // Some day maybe we'll break this into top/left/start/etc. and let the
5164        // client control it. Until then, you can have any scroll indicator you
5165        // want as long as it's a 1dp foreground-colored rectangle.
5166        if (mScrollIndicatorDrawable == null) {
5167            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5168        }
5169    }
5170
5171    /**
5172     * <p>
5173     * Initalizes the scrollability cache if necessary.
5174     * </p>
5175     */
5176    private void initScrollCache() {
5177        if (mScrollCache == null) {
5178            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5179        }
5180    }
5181
5182    private ScrollabilityCache getScrollCache() {
5183        initScrollCache();
5184        return mScrollCache;
5185    }
5186
5187    /**
5188     * Set the position of the vertical scroll bar. Should be one of
5189     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5190     * {@link #SCROLLBAR_POSITION_RIGHT}.
5191     *
5192     * @param position Where the vertical scroll bar should be positioned.
5193     */
5194    public void setVerticalScrollbarPosition(int position) {
5195        if (mVerticalScrollbarPosition != position) {
5196            mVerticalScrollbarPosition = position;
5197            computeOpaqueFlags();
5198            resolvePadding();
5199        }
5200    }
5201
5202    /**
5203     * @return The position where the vertical scroll bar will show, if applicable.
5204     * @see #setVerticalScrollbarPosition(int)
5205     */
5206    public int getVerticalScrollbarPosition() {
5207        return mVerticalScrollbarPosition;
5208    }
5209
5210    boolean isOnScrollbar(float x, float y) {
5211        if (mScrollCache == null) {
5212            return false;
5213        }
5214        x += getScrollX();
5215        y += getScrollY();
5216        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5217            final Rect bounds = mScrollCache.mScrollBarBounds;
5218            getVerticalScrollBarBounds(bounds);
5219            if (bounds.contains((int)x, (int)y)) {
5220                return true;
5221            }
5222        }
5223        if (isHorizontalScrollBarEnabled()) {
5224            final Rect bounds = mScrollCache.mScrollBarBounds;
5225            getHorizontalScrollBarBounds(bounds);
5226            if (bounds.contains((int)x, (int)y)) {
5227                return true;
5228            }
5229        }
5230        return false;
5231    }
5232
5233    boolean isOnScrollbarThumb(float x, float y) {
5234        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5235    }
5236
5237    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5238        if (mScrollCache == null) {
5239            return false;
5240        }
5241        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5242            x += getScrollX();
5243            y += getScrollY();
5244            final Rect bounds = mScrollCache.mScrollBarBounds;
5245            getVerticalScrollBarBounds(bounds);
5246            final int range = computeVerticalScrollRange();
5247            final int offset = computeVerticalScrollOffset();
5248            final int extent = computeVerticalScrollExtent();
5249            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5250                    extent, range);
5251            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5252                    extent, range, offset);
5253            final int thumbTop = bounds.top + thumbOffset;
5254            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5255                    && y <= thumbTop + thumbLength) {
5256                return true;
5257            }
5258        }
5259        return false;
5260    }
5261
5262    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5263        if (mScrollCache == null) {
5264            return false;
5265        }
5266        if (isHorizontalScrollBarEnabled()) {
5267            x += getScrollX();
5268            y += getScrollY();
5269            final Rect bounds = mScrollCache.mScrollBarBounds;
5270            getHorizontalScrollBarBounds(bounds);
5271            final int range = computeHorizontalScrollRange();
5272            final int offset = computeHorizontalScrollOffset();
5273            final int extent = computeHorizontalScrollExtent();
5274            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5275                    extent, range);
5276            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5277                    extent, range, offset);
5278            final int thumbLeft = bounds.left + thumbOffset;
5279            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5280                    && y <= bounds.bottom) {
5281                return true;
5282            }
5283        }
5284        return false;
5285    }
5286
5287    boolean isDraggingScrollBar() {
5288        return mScrollCache != null
5289                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5290    }
5291
5292    /**
5293     * Sets the state of all scroll indicators.
5294     * <p>
5295     * See {@link #setScrollIndicators(int, int)} for usage information.
5296     *
5297     * @param indicators a bitmask of indicators that should be enabled, or
5298     *                   {@code 0} to disable all indicators
5299     * @see #setScrollIndicators(int, int)
5300     * @see #getScrollIndicators()
5301     * @attr ref android.R.styleable#View_scrollIndicators
5302     */
5303    public void setScrollIndicators(@ScrollIndicators int indicators) {
5304        setScrollIndicators(indicators,
5305                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5306    }
5307
5308    /**
5309     * Sets the state of the scroll indicators specified by the mask. To change
5310     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5311     * <p>
5312     * When a scroll indicator is enabled, it will be displayed if the view
5313     * can scroll in the direction of the indicator.
5314     * <p>
5315     * Multiple indicator types may be enabled or disabled by passing the
5316     * logical OR of the desired types. If multiple types are specified, they
5317     * will all be set to the same enabled state.
5318     * <p>
5319     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5320     *
5321     * @param indicators the indicator direction, or the logical OR of multiple
5322     *             indicator directions. One or more of:
5323     *             <ul>
5324     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5325     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5326     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5327     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5328     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5329     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5330     *             </ul>
5331     * @see #setScrollIndicators(int)
5332     * @see #getScrollIndicators()
5333     * @attr ref android.R.styleable#View_scrollIndicators
5334     */
5335    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5336        // Shift and sanitize mask.
5337        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5338        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5339
5340        // Shift and mask indicators.
5341        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5342        indicators &= mask;
5343
5344        // Merge with non-masked flags.
5345        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5346
5347        if (mPrivateFlags3 != updatedFlags) {
5348            mPrivateFlags3 = updatedFlags;
5349
5350            if (indicators != 0) {
5351                initializeScrollIndicatorsInternal();
5352            }
5353            invalidate();
5354        }
5355    }
5356
5357    /**
5358     * Returns a bitmask representing the enabled scroll indicators.
5359     * <p>
5360     * For example, if the top and left scroll indicators are enabled and all
5361     * other indicators are disabled, the return value will be
5362     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5363     * <p>
5364     * To check whether the bottom scroll indicator is enabled, use the value
5365     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5366     *
5367     * @return a bitmask representing the enabled scroll indicators
5368     */
5369    @ScrollIndicators
5370    public int getScrollIndicators() {
5371        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5372                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5373    }
5374
5375    ListenerInfo getListenerInfo() {
5376        if (mListenerInfo != null) {
5377            return mListenerInfo;
5378        }
5379        mListenerInfo = new ListenerInfo();
5380        return mListenerInfo;
5381    }
5382
5383    /**
5384     * Register a callback to be invoked when the scroll X or Y positions of
5385     * this view change.
5386     * <p>
5387     * <b>Note:</b> Some views handle scrolling independently from View and may
5388     * have their own separate listeners for scroll-type events. For example,
5389     * {@link android.widget.ListView ListView} allows clients to register an
5390     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5391     * to listen for changes in list scroll position.
5392     *
5393     * @param l The listener to notify when the scroll X or Y position changes.
5394     * @see android.view.View#getScrollX()
5395     * @see android.view.View#getScrollY()
5396     */
5397    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5398        getListenerInfo().mOnScrollChangeListener = l;
5399    }
5400
5401    /**
5402     * Register a callback to be invoked when focus of this view changed.
5403     *
5404     * @param l The callback that will run.
5405     */
5406    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5407        getListenerInfo().mOnFocusChangeListener = l;
5408    }
5409
5410    /**
5411     * Add a listener that will be called when the bounds of the view change due to
5412     * layout processing.
5413     *
5414     * @param listener The listener that will be called when layout bounds change.
5415     */
5416    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5417        ListenerInfo li = getListenerInfo();
5418        if (li.mOnLayoutChangeListeners == null) {
5419            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5420        }
5421        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5422            li.mOnLayoutChangeListeners.add(listener);
5423        }
5424    }
5425
5426    /**
5427     * Remove a listener for layout changes.
5428     *
5429     * @param listener The listener for layout bounds change.
5430     */
5431    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5432        ListenerInfo li = mListenerInfo;
5433        if (li == null || li.mOnLayoutChangeListeners == null) {
5434            return;
5435        }
5436        li.mOnLayoutChangeListeners.remove(listener);
5437    }
5438
5439    /**
5440     * Add a listener for attach state changes.
5441     *
5442     * This listener will be called whenever this view is attached or detached
5443     * from a window. Remove the listener using
5444     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5445     *
5446     * @param listener Listener to attach
5447     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5448     */
5449    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5450        ListenerInfo li = getListenerInfo();
5451        if (li.mOnAttachStateChangeListeners == null) {
5452            li.mOnAttachStateChangeListeners
5453                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5454        }
5455        li.mOnAttachStateChangeListeners.add(listener);
5456    }
5457
5458    /**
5459     * Remove a listener for attach state changes. The listener will receive no further
5460     * notification of window attach/detach events.
5461     *
5462     * @param listener Listener to remove
5463     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5464     */
5465    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5466        ListenerInfo li = mListenerInfo;
5467        if (li == null || li.mOnAttachStateChangeListeners == null) {
5468            return;
5469        }
5470        li.mOnAttachStateChangeListeners.remove(listener);
5471    }
5472
5473    /**
5474     * Returns the focus-change callback registered for this view.
5475     *
5476     * @return The callback, or null if one is not registered.
5477     */
5478    public OnFocusChangeListener getOnFocusChangeListener() {
5479        ListenerInfo li = mListenerInfo;
5480        return li != null ? li.mOnFocusChangeListener : null;
5481    }
5482
5483    /**
5484     * Register a callback to be invoked when this view is clicked. If this view is not
5485     * clickable, it becomes clickable.
5486     *
5487     * @param l The callback that will run
5488     *
5489     * @see #setClickable(boolean)
5490     */
5491    public void setOnClickListener(@Nullable OnClickListener l) {
5492        if (!isClickable()) {
5493            setClickable(true);
5494        }
5495        getListenerInfo().mOnClickListener = l;
5496    }
5497
5498    /**
5499     * Return whether this view has an attached OnClickListener.  Returns
5500     * true if there is a listener, false if there is none.
5501     */
5502    public boolean hasOnClickListeners() {
5503        ListenerInfo li = mListenerInfo;
5504        return (li != null && li.mOnClickListener != null);
5505    }
5506
5507    /**
5508     * Register a callback to be invoked when this view is clicked and held. If this view is not
5509     * long clickable, it becomes long clickable.
5510     *
5511     * @param l The callback that will run
5512     *
5513     * @see #setLongClickable(boolean)
5514     */
5515    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5516        if (!isLongClickable()) {
5517            setLongClickable(true);
5518        }
5519        getListenerInfo().mOnLongClickListener = l;
5520    }
5521
5522    /**
5523     * Register a callback to be invoked when this view is context clicked. If the view is not
5524     * context clickable, it becomes context clickable.
5525     *
5526     * @param l The callback that will run
5527     * @see #setContextClickable(boolean)
5528     */
5529    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5530        if (!isContextClickable()) {
5531            setContextClickable(true);
5532        }
5533        getListenerInfo().mOnContextClickListener = l;
5534    }
5535
5536    /**
5537     * Register a callback to be invoked when the context menu for this view is
5538     * being built. If this view is not long clickable, it becomes long clickable.
5539     *
5540     * @param l The callback that will run
5541     *
5542     */
5543    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5544        if (!isLongClickable()) {
5545            setLongClickable(true);
5546        }
5547        getListenerInfo().mOnCreateContextMenuListener = l;
5548    }
5549
5550    /**
5551     * Set an observer to collect stats for each frame rendered for this view.
5552     *
5553     * @hide
5554     */
5555    public void addFrameMetricsListener(Window window,
5556            Window.OnFrameMetricsAvailableListener listener,
5557            Handler handler) {
5558        if (mAttachInfo != null) {
5559            if (mAttachInfo.mThreadedRenderer != null) {
5560                if (mFrameMetricsObservers == null) {
5561                    mFrameMetricsObservers = new ArrayList<>();
5562                }
5563
5564                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5565                        handler.getLooper(), listener);
5566                mFrameMetricsObservers.add(fmo);
5567                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
5568            } else {
5569                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5570            }
5571        } else {
5572            if (mFrameMetricsObservers == null) {
5573                mFrameMetricsObservers = new ArrayList<>();
5574            }
5575
5576            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5577                    handler.getLooper(), listener);
5578            mFrameMetricsObservers.add(fmo);
5579        }
5580    }
5581
5582    /**
5583     * Remove observer configured to collect frame stats for this view.
5584     *
5585     * @hide
5586     */
5587    public void removeFrameMetricsListener(
5588            Window.OnFrameMetricsAvailableListener listener) {
5589        ThreadedRenderer renderer = getThreadedRenderer();
5590        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5591        if (fmo == null) {
5592            throw new IllegalArgumentException(
5593                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5594        }
5595
5596        if (mFrameMetricsObservers != null) {
5597            mFrameMetricsObservers.remove(fmo);
5598            if (renderer != null) {
5599                renderer.removeFrameMetricsObserver(fmo);
5600            }
5601        }
5602    }
5603
5604    private void registerPendingFrameMetricsObservers() {
5605        if (mFrameMetricsObservers != null) {
5606            ThreadedRenderer renderer = getThreadedRenderer();
5607            if (renderer != null) {
5608                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5609                    renderer.addFrameMetricsObserver(fmo);
5610                }
5611            } else {
5612                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5613            }
5614        }
5615    }
5616
5617    private FrameMetricsObserver findFrameMetricsObserver(
5618            Window.OnFrameMetricsAvailableListener listener) {
5619        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5620            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5621            if (observer.mListener == listener) {
5622                return observer;
5623            }
5624        }
5625
5626        return null;
5627    }
5628
5629    /**
5630     * Call this view's OnClickListener, if it is defined.  Performs all normal
5631     * actions associated with clicking: reporting accessibility event, playing
5632     * a sound, etc.
5633     *
5634     * @return True there was an assigned OnClickListener that was called, false
5635     *         otherwise is returned.
5636     */
5637    public boolean performClick() {
5638        final boolean result;
5639        final ListenerInfo li = mListenerInfo;
5640        if (li != null && li.mOnClickListener != null) {
5641            playSoundEffect(SoundEffectConstants.CLICK);
5642            li.mOnClickListener.onClick(this);
5643            result = true;
5644        } else {
5645            result = false;
5646        }
5647
5648        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5649        return result;
5650    }
5651
5652    /**
5653     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5654     * this only calls the listener, and does not do any associated clicking
5655     * actions like reporting an accessibility event.
5656     *
5657     * @return True there was an assigned OnClickListener that was called, false
5658     *         otherwise is returned.
5659     */
5660    public boolean callOnClick() {
5661        ListenerInfo li = mListenerInfo;
5662        if (li != null && li.mOnClickListener != null) {
5663            li.mOnClickListener.onClick(this);
5664            return true;
5665        }
5666        return false;
5667    }
5668
5669    /**
5670     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5671     * context menu if the OnLongClickListener did not consume the event.
5672     *
5673     * @return {@code true} if one of the above receivers consumed the event,
5674     *         {@code false} otherwise
5675     */
5676    public boolean performLongClick() {
5677        return performLongClickInternal(mLongClickX, mLongClickY);
5678    }
5679
5680    /**
5681     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5682     * context menu if the OnLongClickListener did not consume the event,
5683     * anchoring it to an (x,y) coordinate.
5684     *
5685     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5686     *          to disable anchoring
5687     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5688     *          to disable anchoring
5689     * @return {@code true} if one of the above receivers consumed the event,
5690     *         {@code false} otherwise
5691     */
5692    public boolean performLongClick(float x, float y) {
5693        mLongClickX = x;
5694        mLongClickY = y;
5695        final boolean handled = performLongClick();
5696        mLongClickX = Float.NaN;
5697        mLongClickY = Float.NaN;
5698        return handled;
5699    }
5700
5701    /**
5702     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5703     * context menu if the OnLongClickListener did not consume the event,
5704     * optionally anchoring it to an (x,y) coordinate.
5705     *
5706     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5707     *          to disable anchoring
5708     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5709     *          to disable anchoring
5710     * @return {@code true} if one of the above receivers consumed the event,
5711     *         {@code false} otherwise
5712     */
5713    private boolean performLongClickInternal(float x, float y) {
5714        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5715
5716        boolean handled = false;
5717        final ListenerInfo li = mListenerInfo;
5718        if (li != null && li.mOnLongClickListener != null) {
5719            handled = li.mOnLongClickListener.onLongClick(View.this);
5720        }
5721        if (!handled) {
5722            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5723            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5724        }
5725        if (handled) {
5726            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5727        }
5728        return handled;
5729    }
5730
5731    /**
5732     * Call this view's OnContextClickListener, if it is defined.
5733     *
5734     * @param x the x coordinate of the context click
5735     * @param y the y coordinate of the context click
5736     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5737     *         otherwise.
5738     */
5739    public boolean performContextClick(float x, float y) {
5740        return performContextClick();
5741    }
5742
5743    /**
5744     * Call this view's OnContextClickListener, if it is defined.
5745     *
5746     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5747     *         otherwise.
5748     */
5749    public boolean performContextClick() {
5750        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5751
5752        boolean handled = false;
5753        ListenerInfo li = mListenerInfo;
5754        if (li != null && li.mOnContextClickListener != null) {
5755            handled = li.mOnContextClickListener.onContextClick(View.this);
5756        }
5757        if (handled) {
5758            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5759        }
5760        return handled;
5761    }
5762
5763    /**
5764     * Performs button-related actions during a touch down event.
5765     *
5766     * @param event The event.
5767     * @return True if the down was consumed.
5768     *
5769     * @hide
5770     */
5771    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5772        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5773            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5774            showContextMenu(event.getX(), event.getY());
5775            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5776            return true;
5777        }
5778        return false;
5779    }
5780
5781    /**
5782     * Shows the context menu for this view.
5783     *
5784     * @return {@code true} if the context menu was shown, {@code false}
5785     *         otherwise
5786     * @see #showContextMenu(float, float)
5787     */
5788    public boolean showContextMenu() {
5789        return getParent().showContextMenuForChild(this);
5790    }
5791
5792    /**
5793     * Shows the context menu for this view anchored to the specified
5794     * view-relative coordinate.
5795     *
5796     * @param x the X coordinate in pixels relative to the view to which the
5797     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5798     * @param y the Y coordinate in pixels relative to the view to which the
5799     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5800     * @return {@code true} if the context menu was shown, {@code false}
5801     *         otherwise
5802     */
5803    public boolean showContextMenu(float x, float y) {
5804        return getParent().showContextMenuForChild(this, x, y);
5805    }
5806
5807    /**
5808     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5809     *
5810     * @param callback Callback that will control the lifecycle of the action mode
5811     * @return The new action mode if it is started, null otherwise
5812     *
5813     * @see ActionMode
5814     * @see #startActionMode(android.view.ActionMode.Callback, int)
5815     */
5816    public ActionMode startActionMode(ActionMode.Callback callback) {
5817        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5818    }
5819
5820    /**
5821     * Start an action mode with the given type.
5822     *
5823     * @param callback Callback that will control the lifecycle of the action mode
5824     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5825     * @return The new action mode if it is started, null otherwise
5826     *
5827     * @see ActionMode
5828     */
5829    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5830        ViewParent parent = getParent();
5831        if (parent == null) return null;
5832        try {
5833            return parent.startActionModeForChild(this, callback, type);
5834        } catch (AbstractMethodError ame) {
5835            // Older implementations of custom views might not implement this.
5836            return parent.startActionModeForChild(this, callback);
5837        }
5838    }
5839
5840    /**
5841     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5842     * Context, creating a unique View identifier to retrieve the result.
5843     *
5844     * @param intent The Intent to be started.
5845     * @param requestCode The request code to use.
5846     * @hide
5847     */
5848    public void startActivityForResult(Intent intent, int requestCode) {
5849        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5850        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5851    }
5852
5853    /**
5854     * If this View corresponds to the calling who, dispatches the activity result.
5855     * @param who The identifier for the targeted View to receive the result.
5856     * @param requestCode The integer request code originally supplied to
5857     *                    startActivityForResult(), allowing you to identify who this
5858     *                    result came from.
5859     * @param resultCode The integer result code returned by the child activity
5860     *                   through its setResult().
5861     * @param data An Intent, which can return result data to the caller
5862     *               (various data can be attached to Intent "extras").
5863     * @return {@code true} if the activity result was dispatched.
5864     * @hide
5865     */
5866    public boolean dispatchActivityResult(
5867            String who, int requestCode, int resultCode, Intent data) {
5868        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5869            onActivityResult(requestCode, resultCode, data);
5870            mStartActivityRequestWho = null;
5871            return true;
5872        }
5873        return false;
5874    }
5875
5876    /**
5877     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5878     *
5879     * @param requestCode The integer request code originally supplied to
5880     *                    startActivityForResult(), allowing you to identify who this
5881     *                    result came from.
5882     * @param resultCode The integer result code returned by the child activity
5883     *                   through its setResult().
5884     * @param data An Intent, which can return result data to the caller
5885     *               (various data can be attached to Intent "extras").
5886     * @hide
5887     */
5888    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5889        // Do nothing.
5890    }
5891
5892    /**
5893     * Register a callback to be invoked when a hardware key is pressed in this view.
5894     * Key presses in software input methods will generally not trigger the methods of
5895     * this listener.
5896     * @param l the key listener to attach to this view
5897     */
5898    public void setOnKeyListener(OnKeyListener l) {
5899        getListenerInfo().mOnKeyListener = l;
5900    }
5901
5902    /**
5903     * Register a callback to be invoked when a touch event is sent to this view.
5904     * @param l the touch listener to attach to this view
5905     */
5906    public void setOnTouchListener(OnTouchListener l) {
5907        getListenerInfo().mOnTouchListener = l;
5908    }
5909
5910    /**
5911     * Register a callback to be invoked when a generic motion event is sent to this view.
5912     * @param l the generic motion listener to attach to this view
5913     */
5914    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5915        getListenerInfo().mOnGenericMotionListener = l;
5916    }
5917
5918    /**
5919     * Register a callback to be invoked when a hover event is sent to this view.
5920     * @param l the hover listener to attach to this view
5921     */
5922    public void setOnHoverListener(OnHoverListener l) {
5923        getListenerInfo().mOnHoverListener = l;
5924    }
5925
5926    /**
5927     * Register a drag event listener callback object for this View. The parameter is
5928     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5929     * View, the system calls the
5930     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5931     * @param l An implementation of {@link android.view.View.OnDragListener}.
5932     */
5933    public void setOnDragListener(OnDragListener l) {
5934        getListenerInfo().mOnDragListener = l;
5935    }
5936
5937    /**
5938     * Give this view focus. This will cause
5939     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5940     *
5941     * Note: this does not check whether this {@link View} should get focus, it just
5942     * gives it focus no matter what.  It should only be called internally by framework
5943     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5944     *
5945     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5946     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5947     *        focus moved when requestFocus() is called. It may not always
5948     *        apply, in which case use the default View.FOCUS_DOWN.
5949     * @param previouslyFocusedRect The rectangle of the view that had focus
5950     *        prior in this View's coordinate system.
5951     */
5952    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5953        if (DBG) {
5954            System.out.println(this + " requestFocus()");
5955        }
5956
5957        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5958            mPrivateFlags |= PFLAG_FOCUSED;
5959
5960            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5961
5962            if (mParent != null) {
5963                mParent.requestChildFocus(this, this);
5964            }
5965
5966            if (mAttachInfo != null) {
5967                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5968            }
5969
5970            onFocusChanged(true, direction, previouslyFocusedRect);
5971            refreshDrawableState();
5972        }
5973    }
5974
5975    /**
5976     * Sets this view's preference for reveal behavior when it gains focus.
5977     *
5978     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
5979     * this view would prefer to be brought fully into view when it gains focus.
5980     * For example, a text field that a user is meant to type into. Other views such
5981     * as scrolling containers may prefer to opt-out of this behavior.</p>
5982     *
5983     * <p>The default value for views is true, though subclasses may change this
5984     * based on their preferred behavior.</p>
5985     *
5986     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
5987     *
5988     * @see #getRevealOnFocusHint()
5989     */
5990    public final void setRevealOnFocusHint(boolean revealOnFocus) {
5991        if (revealOnFocus) {
5992            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
5993        } else {
5994            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
5995        }
5996    }
5997
5998    /**
5999     * Returns this view's preference for reveal behavior when it gains focus.
6000     *
6001     * <p>When this method returns true for a child view requesting focus, ancestor
6002     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6003     * should make a best effort to make the newly focused child fully visible to the user.
6004     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6005     * other properties affecting visibility to the user as part of the focus change.</p>
6006     *
6007     * @return true if this view would prefer to become fully visible when it gains focus,
6008     *         false if it would prefer not to disrupt scroll positioning
6009     *
6010     * @see #setRevealOnFocusHint(boolean)
6011     */
6012    public final boolean getRevealOnFocusHint() {
6013        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6014    }
6015
6016    /**
6017     * Populates <code>outRect</code> with the hotspot bounds. By default,
6018     * the hotspot bounds are identical to the screen bounds.
6019     *
6020     * @param outRect rect to populate with hotspot bounds
6021     * @hide Only for internal use by views and widgets.
6022     */
6023    public void getHotspotBounds(Rect outRect) {
6024        final Drawable background = getBackground();
6025        if (background != null) {
6026            background.getHotspotBounds(outRect);
6027        } else {
6028            getBoundsOnScreen(outRect);
6029        }
6030    }
6031
6032    /**
6033     * Request that a rectangle of this view be visible on the screen,
6034     * scrolling if necessary just enough.
6035     *
6036     * <p>A View should call this if it maintains some notion of which part
6037     * of its content is interesting.  For example, a text editing view
6038     * should call this when its cursor moves.
6039     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6040     * It should not be affected by which part of the View is currently visible or its scroll
6041     * position.
6042     *
6043     * @param rectangle The rectangle in the View's content coordinate space
6044     * @return Whether any parent scrolled.
6045     */
6046    public boolean requestRectangleOnScreen(Rect rectangle) {
6047        return requestRectangleOnScreen(rectangle, false);
6048    }
6049
6050    /**
6051     * Request that a rectangle of this view be visible on the screen,
6052     * scrolling if necessary just enough.
6053     *
6054     * <p>A View should call this if it maintains some notion of which part
6055     * of its content is interesting.  For example, a text editing view
6056     * should call this when its cursor moves.
6057     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6058     * It should not be affected by which part of the View is currently visible or its scroll
6059     * position.
6060     * <p>When <code>immediate</code> is set to true, scrolling will not be
6061     * animated.
6062     *
6063     * @param rectangle The rectangle in the View's content coordinate space
6064     * @param immediate True to forbid animated scrolling, false otherwise
6065     * @return Whether any parent scrolled.
6066     */
6067    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6068        if (mParent == null) {
6069            return false;
6070        }
6071
6072        View child = this;
6073
6074        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6075        position.set(rectangle);
6076
6077        ViewParent parent = mParent;
6078        boolean scrolled = false;
6079        while (parent != null) {
6080            rectangle.set((int) position.left, (int) position.top,
6081                    (int) position.right, (int) position.bottom);
6082
6083            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6084
6085            if (!(parent instanceof View)) {
6086                break;
6087            }
6088
6089            // move it from child's content coordinate space to parent's content coordinate space
6090            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6091
6092            child = (View) parent;
6093            parent = child.getParent();
6094        }
6095
6096        return scrolled;
6097    }
6098
6099    /**
6100     * Called when this view wants to give up focus. If focus is cleared
6101     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6102     * <p>
6103     * <strong>Note:</strong> When a View clears focus the framework is trying
6104     * to give focus to the first focusable View from the top. Hence, if this
6105     * View is the first from the top that can take focus, then all callbacks
6106     * related to clearing focus will be invoked after which the framework will
6107     * give focus to this view.
6108     * </p>
6109     */
6110    public void clearFocus() {
6111        if (DBG) {
6112            System.out.println(this + " clearFocus()");
6113        }
6114
6115        clearFocusInternal(null, true, true);
6116    }
6117
6118    /**
6119     * Clears focus from the view, optionally propagating the change up through
6120     * the parent hierarchy and requesting that the root view place new focus.
6121     *
6122     * @param propagate whether to propagate the change up through the parent
6123     *            hierarchy
6124     * @param refocus when propagate is true, specifies whether to request the
6125     *            root view place new focus
6126     */
6127    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6128        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6129            mPrivateFlags &= ~PFLAG_FOCUSED;
6130
6131            if (propagate && mParent != null) {
6132                mParent.clearChildFocus(this);
6133            }
6134
6135            onFocusChanged(false, 0, null);
6136            refreshDrawableState();
6137
6138            if (propagate && (!refocus || !rootViewRequestFocus())) {
6139                notifyGlobalFocusCleared(this);
6140            }
6141        }
6142    }
6143
6144    void notifyGlobalFocusCleared(View oldFocus) {
6145        if (oldFocus != null && mAttachInfo != null) {
6146            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6147        }
6148    }
6149
6150    boolean rootViewRequestFocus() {
6151        final View root = getRootView();
6152        return root != null && root.requestFocus();
6153    }
6154
6155    /**
6156     * Called internally by the view system when a new view is getting focus.
6157     * This is what clears the old focus.
6158     * <p>
6159     * <b>NOTE:</b> The parent view's focused child must be updated manually
6160     * after calling this method. Otherwise, the view hierarchy may be left in
6161     * an inconstent state.
6162     */
6163    void unFocus(View focused) {
6164        if (DBG) {
6165            System.out.println(this + " unFocus()");
6166        }
6167
6168        clearFocusInternal(focused, false, false);
6169    }
6170
6171    /**
6172     * Returns true if this view has focus itself, or is the ancestor of the
6173     * view that has focus.
6174     *
6175     * @return True if this view has or contains focus, false otherwise.
6176     */
6177    @ViewDebug.ExportedProperty(category = "focus")
6178    public boolean hasFocus() {
6179        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6180    }
6181
6182    /**
6183     * Returns true if this view is focusable or if it contains a reachable View
6184     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6185     * is a View whose parents do not block descendants focus.
6186     *
6187     * Only {@link #VISIBLE} views are considered focusable.
6188     *
6189     * @return True if the view is focusable or if the view contains a focusable
6190     *         View, false otherwise.
6191     *
6192     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6193     * @see ViewGroup#getTouchscreenBlocksFocus()
6194     */
6195    public boolean hasFocusable() {
6196        if (!isFocusableInTouchMode()) {
6197            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6198                final ViewGroup g = (ViewGroup) p;
6199                if (g.shouldBlockFocusForTouchscreen()) {
6200                    return false;
6201                }
6202            }
6203        }
6204        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6205    }
6206
6207    /**
6208     * Called by the view system when the focus state of this view changes.
6209     * When the focus change event is caused by directional navigation, direction
6210     * and previouslyFocusedRect provide insight into where the focus is coming from.
6211     * When overriding, be sure to call up through to the super class so that
6212     * the standard focus handling will occur.
6213     *
6214     * @param gainFocus True if the View has focus; false otherwise.
6215     * @param direction The direction focus has moved when requestFocus()
6216     *                  is called to give this view focus. Values are
6217     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6218     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6219     *                  It may not always apply, in which case use the default.
6220     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6221     *        system, of the previously focused view.  If applicable, this will be
6222     *        passed in as finer grained information about where the focus is coming
6223     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6224     */
6225    @CallSuper
6226    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6227            @Nullable Rect previouslyFocusedRect) {
6228        if (gainFocus) {
6229            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6230        } else {
6231            notifyViewAccessibilityStateChangedIfNeeded(
6232                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6233        }
6234
6235        InputMethodManager imm = InputMethodManager.peekInstance();
6236        if (!gainFocus) {
6237            if (isPressed()) {
6238                setPressed(false);
6239            }
6240            if (imm != null && mAttachInfo != null
6241                    && mAttachInfo.mHasWindowFocus) {
6242                imm.focusOut(this);
6243            }
6244            onFocusLost();
6245        } else if (imm != null && mAttachInfo != null
6246                && mAttachInfo.mHasWindowFocus) {
6247            imm.focusIn(this);
6248        }
6249
6250        invalidate(true);
6251        ListenerInfo li = mListenerInfo;
6252        if (li != null && li.mOnFocusChangeListener != null) {
6253            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6254        }
6255
6256        if (mAttachInfo != null) {
6257            mAttachInfo.mKeyDispatchState.reset(this);
6258        }
6259    }
6260
6261    /**
6262     * Sends an accessibility event of the given type. If accessibility is
6263     * not enabled this method has no effect. The default implementation calls
6264     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6265     * to populate information about the event source (this View), then calls
6266     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6267     * populate the text content of the event source including its descendants,
6268     * and last calls
6269     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6270     * on its parent to request sending of the event to interested parties.
6271     * <p>
6272     * If an {@link AccessibilityDelegate} has been specified via calling
6273     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6274     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6275     * responsible for handling this call.
6276     * </p>
6277     *
6278     * @param eventType The type of the event to send, as defined by several types from
6279     * {@link android.view.accessibility.AccessibilityEvent}, such as
6280     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6281     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6282     *
6283     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6284     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6285     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6286     * @see AccessibilityDelegate
6287     */
6288    public void sendAccessibilityEvent(int eventType) {
6289        if (mAccessibilityDelegate != null) {
6290            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6291        } else {
6292            sendAccessibilityEventInternal(eventType);
6293        }
6294    }
6295
6296    /**
6297     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6298     * {@link AccessibilityEvent} to make an announcement which is related to some
6299     * sort of a context change for which none of the events representing UI transitions
6300     * is a good fit. For example, announcing a new page in a book. If accessibility
6301     * is not enabled this method does nothing.
6302     *
6303     * @param text The announcement text.
6304     */
6305    public void announceForAccessibility(CharSequence text) {
6306        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6307            AccessibilityEvent event = AccessibilityEvent.obtain(
6308                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6309            onInitializeAccessibilityEvent(event);
6310            event.getText().add(text);
6311            event.setContentDescription(null);
6312            mParent.requestSendAccessibilityEvent(this, event);
6313        }
6314    }
6315
6316    /**
6317     * @see #sendAccessibilityEvent(int)
6318     *
6319     * Note: Called from the default {@link AccessibilityDelegate}.
6320     *
6321     * @hide
6322     */
6323    public void sendAccessibilityEventInternal(int eventType) {
6324        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6325            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6326        }
6327    }
6328
6329    /**
6330     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6331     * takes as an argument an empty {@link AccessibilityEvent} and does not
6332     * perform a check whether accessibility is enabled.
6333     * <p>
6334     * If an {@link AccessibilityDelegate} has been specified via calling
6335     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6336     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6337     * is responsible for handling this call.
6338     * </p>
6339     *
6340     * @param event The event to send.
6341     *
6342     * @see #sendAccessibilityEvent(int)
6343     */
6344    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6345        if (mAccessibilityDelegate != null) {
6346            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6347        } else {
6348            sendAccessibilityEventUncheckedInternal(event);
6349        }
6350    }
6351
6352    /**
6353     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6354     *
6355     * Note: Called from the default {@link AccessibilityDelegate}.
6356     *
6357     * @hide
6358     */
6359    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6360        if (!isShown()) {
6361            return;
6362        }
6363        onInitializeAccessibilityEvent(event);
6364        // Only a subset of accessibility events populates text content.
6365        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6366            dispatchPopulateAccessibilityEvent(event);
6367        }
6368        // In the beginning we called #isShown(), so we know that getParent() is not null.
6369        getParent().requestSendAccessibilityEvent(this, event);
6370    }
6371
6372    /**
6373     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6374     * to its children for adding their text content to the event. Note that the
6375     * event text is populated in a separate dispatch path since we add to the
6376     * event not only the text of the source but also the text of all its descendants.
6377     * A typical implementation will call
6378     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6379     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6380     * on each child. Override this method if custom population of the event text
6381     * content is required.
6382     * <p>
6383     * If an {@link AccessibilityDelegate} has been specified via calling
6384     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6385     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6386     * is responsible for handling this call.
6387     * </p>
6388     * <p>
6389     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6390     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6391     * </p>
6392     *
6393     * @param event The event.
6394     *
6395     * @return True if the event population was completed.
6396     */
6397    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6398        if (mAccessibilityDelegate != null) {
6399            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6400        } else {
6401            return dispatchPopulateAccessibilityEventInternal(event);
6402        }
6403    }
6404
6405    /**
6406     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6407     *
6408     * Note: Called from the default {@link AccessibilityDelegate}.
6409     *
6410     * @hide
6411     */
6412    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6413        onPopulateAccessibilityEvent(event);
6414        return false;
6415    }
6416
6417    /**
6418     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6419     * giving a chance to this View to populate the accessibility event with its
6420     * text content. While this method is free to modify event
6421     * attributes other than text content, doing so should normally be performed in
6422     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6423     * <p>
6424     * Example: Adding formatted date string to an accessibility event in addition
6425     *          to the text added by the super implementation:
6426     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6427     *     super.onPopulateAccessibilityEvent(event);
6428     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6429     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6430     *         mCurrentDate.getTimeInMillis(), flags);
6431     *     event.getText().add(selectedDateUtterance);
6432     * }</pre>
6433     * <p>
6434     * If an {@link AccessibilityDelegate} has been specified via calling
6435     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6436     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6437     * is responsible for handling this call.
6438     * </p>
6439     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6440     * information to the event, in case the default implementation has basic information to add.
6441     * </p>
6442     *
6443     * @param event The accessibility event which to populate.
6444     *
6445     * @see #sendAccessibilityEvent(int)
6446     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6447     */
6448    @CallSuper
6449    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6450        if (mAccessibilityDelegate != null) {
6451            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6452        } else {
6453            onPopulateAccessibilityEventInternal(event);
6454        }
6455    }
6456
6457    /**
6458     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6459     *
6460     * Note: Called from the default {@link AccessibilityDelegate}.
6461     *
6462     * @hide
6463     */
6464    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6465    }
6466
6467    /**
6468     * Initializes an {@link AccessibilityEvent} with information about
6469     * this View which is the event source. In other words, the source of
6470     * an accessibility event is the view whose state change triggered firing
6471     * the event.
6472     * <p>
6473     * Example: Setting the password property of an event in addition
6474     *          to properties set by the super implementation:
6475     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6476     *     super.onInitializeAccessibilityEvent(event);
6477     *     event.setPassword(true);
6478     * }</pre>
6479     * <p>
6480     * If an {@link AccessibilityDelegate} has been specified via calling
6481     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6482     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6483     * is responsible for handling this call.
6484     * </p>
6485     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6486     * information to the event, in case the default implementation has basic information to add.
6487     * </p>
6488     * @param event The event to initialize.
6489     *
6490     * @see #sendAccessibilityEvent(int)
6491     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6492     */
6493    @CallSuper
6494    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6495        if (mAccessibilityDelegate != null) {
6496            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6497        } else {
6498            onInitializeAccessibilityEventInternal(event);
6499        }
6500    }
6501
6502    /**
6503     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6504     *
6505     * Note: Called from the default {@link AccessibilityDelegate}.
6506     *
6507     * @hide
6508     */
6509    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6510        event.setSource(this);
6511        event.setClassName(getAccessibilityClassName());
6512        event.setPackageName(getContext().getPackageName());
6513        event.setEnabled(isEnabled());
6514        event.setContentDescription(mContentDescription);
6515
6516        switch (event.getEventType()) {
6517            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6518                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6519                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6520                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6521                event.setItemCount(focusablesTempList.size());
6522                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6523                if (mAttachInfo != null) {
6524                    focusablesTempList.clear();
6525                }
6526            } break;
6527            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6528                CharSequence text = getIterableTextForAccessibility();
6529                if (text != null && text.length() > 0) {
6530                    event.setFromIndex(getAccessibilitySelectionStart());
6531                    event.setToIndex(getAccessibilitySelectionEnd());
6532                    event.setItemCount(text.length());
6533                }
6534            } break;
6535        }
6536    }
6537
6538    /**
6539     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6540     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6541     * This method is responsible for obtaining an accessibility node info from a
6542     * pool of reusable instances and calling
6543     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6544     * initialize the former.
6545     * <p>
6546     * Note: The client is responsible for recycling the obtained instance by calling
6547     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6548     * </p>
6549     *
6550     * @return A populated {@link AccessibilityNodeInfo}.
6551     *
6552     * @see AccessibilityNodeInfo
6553     */
6554    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6555        if (mAccessibilityDelegate != null) {
6556            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6557        } else {
6558            return createAccessibilityNodeInfoInternal();
6559        }
6560    }
6561
6562    /**
6563     * @see #createAccessibilityNodeInfo()
6564     *
6565     * @hide
6566     */
6567    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6568        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6569        if (provider != null) {
6570            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6571        } else {
6572            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6573            onInitializeAccessibilityNodeInfo(info);
6574            return info;
6575        }
6576    }
6577
6578    /**
6579     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6580     * The base implementation sets:
6581     * <ul>
6582     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6583     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6584     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6585     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6586     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6587     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6588     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6589     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6590     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6591     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6592     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6593     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6594     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6595     * </ul>
6596     * <p>
6597     * Subclasses should override this method, call the super implementation,
6598     * and set additional attributes.
6599     * </p>
6600     * <p>
6601     * If an {@link AccessibilityDelegate} has been specified via calling
6602     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6603     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6604     * is responsible for handling this call.
6605     * </p>
6606     *
6607     * @param info The instance to initialize.
6608     */
6609    @CallSuper
6610    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6611        if (mAccessibilityDelegate != null) {
6612            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6613        } else {
6614            onInitializeAccessibilityNodeInfoInternal(info);
6615        }
6616    }
6617
6618    /**
6619     * Gets the location of this view in screen coordinates.
6620     *
6621     * @param outRect The output location
6622     * @hide
6623     */
6624    public void getBoundsOnScreen(Rect outRect) {
6625        getBoundsOnScreen(outRect, false);
6626    }
6627
6628    /**
6629     * Gets the location of this view in screen coordinates.
6630     *
6631     * @param outRect The output location
6632     * @param clipToParent Whether to clip child bounds to the parent ones.
6633     * @hide
6634     */
6635    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6636        if (mAttachInfo == null) {
6637            return;
6638        }
6639
6640        RectF position = mAttachInfo.mTmpTransformRect;
6641        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6642
6643        if (!hasIdentityMatrix()) {
6644            getMatrix().mapRect(position);
6645        }
6646
6647        position.offset(mLeft, mTop);
6648
6649        ViewParent parent = mParent;
6650        while (parent instanceof View) {
6651            View parentView = (View) parent;
6652
6653            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6654
6655            if (clipToParent) {
6656                position.left = Math.max(position.left, 0);
6657                position.top = Math.max(position.top, 0);
6658                position.right = Math.min(position.right, parentView.getWidth());
6659                position.bottom = Math.min(position.bottom, parentView.getHeight());
6660            }
6661
6662            if (!parentView.hasIdentityMatrix()) {
6663                parentView.getMatrix().mapRect(position);
6664            }
6665
6666            position.offset(parentView.mLeft, parentView.mTop);
6667
6668            parent = parentView.mParent;
6669        }
6670
6671        if (parent instanceof ViewRootImpl) {
6672            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6673            position.offset(0, -viewRootImpl.mCurScrollY);
6674        }
6675
6676        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6677
6678        outRect.set(Math.round(position.left), Math.round(position.top),
6679                Math.round(position.right), Math.round(position.bottom));
6680    }
6681
6682    /**
6683     * Return the class name of this object to be used for accessibility purposes.
6684     * Subclasses should only override this if they are implementing something that
6685     * should be seen as a completely new class of view when used by accessibility,
6686     * unrelated to the class it is deriving from.  This is used to fill in
6687     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6688     */
6689    public CharSequence getAccessibilityClassName() {
6690        return View.class.getName();
6691    }
6692
6693    /**
6694     * Called when assist structure is being retrieved from a view as part of
6695     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6696     * @param structure Fill in with structured view data.  The default implementation
6697     * fills in all data that can be inferred from the view itself.
6698     */
6699    public void onProvideStructure(ViewStructure structure) {
6700        final int id = mID;
6701        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6702                && (id&0x0000ffff) != 0) {
6703            String pkg, type, entry;
6704            try {
6705                final Resources res = getResources();
6706                entry = res.getResourceEntryName(id);
6707                type = res.getResourceTypeName(id);
6708                pkg = res.getResourcePackageName(id);
6709            } catch (Resources.NotFoundException e) {
6710                entry = type = pkg = null;
6711            }
6712            structure.setId(id, pkg, type, entry);
6713        } else {
6714            structure.setId(id, null, null, null);
6715        }
6716        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6717        if (!hasIdentityMatrix()) {
6718            structure.setTransformation(getMatrix());
6719        }
6720        structure.setElevation(getZ());
6721        structure.setVisibility(getVisibility());
6722        structure.setEnabled(isEnabled());
6723        if (isClickable()) {
6724            structure.setClickable(true);
6725        }
6726        if (isFocusable()) {
6727            structure.setFocusable(true);
6728        }
6729        if (isFocused()) {
6730            structure.setFocused(true);
6731        }
6732        if (isAccessibilityFocused()) {
6733            structure.setAccessibilityFocused(true);
6734        }
6735        if (isSelected()) {
6736            structure.setSelected(true);
6737        }
6738        if (isActivated()) {
6739            structure.setActivated(true);
6740        }
6741        if (isLongClickable()) {
6742            structure.setLongClickable(true);
6743        }
6744        if (this instanceof Checkable) {
6745            structure.setCheckable(true);
6746            if (((Checkable)this).isChecked()) {
6747                structure.setChecked(true);
6748            }
6749        }
6750        if (isContextClickable()) {
6751            structure.setContextClickable(true);
6752        }
6753        structure.setClassName(getAccessibilityClassName().toString());
6754        structure.setContentDescription(getContentDescription());
6755    }
6756
6757    /**
6758     * Called when assist structure is being retrieved from a view as part of
6759     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6760     * generate additional virtual structure under this view.  The defaullt implementation
6761     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6762     * view's virtual accessibility nodes, if any.  You can override this for a more
6763     * optimal implementation providing this data.
6764     */
6765    public void onProvideVirtualStructure(ViewStructure structure) {
6766        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6767        if (provider != null) {
6768            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6769            structure.setChildCount(1);
6770            ViewStructure root = structure.newChild(0);
6771            populateVirtualStructure(root, provider, info);
6772            info.recycle();
6773        }
6774    }
6775
6776    private void populateVirtualStructure(ViewStructure structure,
6777            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6778        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6779                null, null, null);
6780        Rect rect = structure.getTempRect();
6781        info.getBoundsInParent(rect);
6782        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6783        structure.setVisibility(VISIBLE);
6784        structure.setEnabled(info.isEnabled());
6785        if (info.isClickable()) {
6786            structure.setClickable(true);
6787        }
6788        if (info.isFocusable()) {
6789            structure.setFocusable(true);
6790        }
6791        if (info.isFocused()) {
6792            structure.setFocused(true);
6793        }
6794        if (info.isAccessibilityFocused()) {
6795            structure.setAccessibilityFocused(true);
6796        }
6797        if (info.isSelected()) {
6798            structure.setSelected(true);
6799        }
6800        if (info.isLongClickable()) {
6801            structure.setLongClickable(true);
6802        }
6803        if (info.isCheckable()) {
6804            structure.setCheckable(true);
6805            if (info.isChecked()) {
6806                structure.setChecked(true);
6807            }
6808        }
6809        if (info.isContextClickable()) {
6810            structure.setContextClickable(true);
6811        }
6812        CharSequence cname = info.getClassName();
6813        structure.setClassName(cname != null ? cname.toString() : null);
6814        structure.setContentDescription(info.getContentDescription());
6815        if (info.getText() != null || info.getError() != null) {
6816            structure.setText(info.getText(), info.getTextSelectionStart(),
6817                    info.getTextSelectionEnd());
6818        }
6819        final int NCHILDREN = info.getChildCount();
6820        if (NCHILDREN > 0) {
6821            structure.setChildCount(NCHILDREN);
6822            for (int i=0; i<NCHILDREN; i++) {
6823                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6824                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6825                ViewStructure child = structure.newChild(i);
6826                populateVirtualStructure(child, provider, cinfo);
6827                cinfo.recycle();
6828            }
6829        }
6830    }
6831
6832    /**
6833     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6834     * implementation calls {@link #onProvideStructure} and
6835     * {@link #onProvideVirtualStructure}.
6836     */
6837    public void dispatchProvideStructure(ViewStructure structure) {
6838        if (!isAssistBlocked()) {
6839            onProvideStructure(structure);
6840            onProvideVirtualStructure(structure);
6841        } else {
6842            structure.setClassName(getAccessibilityClassName().toString());
6843            structure.setAssistBlocked(true);
6844        }
6845    }
6846
6847    /**
6848     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6849     *
6850     * Note: Called from the default {@link AccessibilityDelegate}.
6851     *
6852     * @hide
6853     */
6854    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6855        if (mAttachInfo == null) {
6856            return;
6857        }
6858
6859        Rect bounds = mAttachInfo.mTmpInvalRect;
6860
6861        getDrawingRect(bounds);
6862        info.setBoundsInParent(bounds);
6863
6864        getBoundsOnScreen(bounds, true);
6865        info.setBoundsInScreen(bounds);
6866
6867        ViewParent parent = getParentForAccessibility();
6868        if (parent instanceof View) {
6869            info.setParent((View) parent);
6870        }
6871
6872        if (mID != View.NO_ID) {
6873            View rootView = getRootView();
6874            if (rootView == null) {
6875                rootView = this;
6876            }
6877
6878            View label = rootView.findLabelForView(this, mID);
6879            if (label != null) {
6880                info.setLabeledBy(label);
6881            }
6882
6883            if ((mAttachInfo.mAccessibilityFetchFlags
6884                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6885                    && Resources.resourceHasPackage(mID)) {
6886                try {
6887                    String viewId = getResources().getResourceName(mID);
6888                    info.setViewIdResourceName(viewId);
6889                } catch (Resources.NotFoundException nfe) {
6890                    /* ignore */
6891                }
6892            }
6893        }
6894
6895        if (mLabelForId != View.NO_ID) {
6896            View rootView = getRootView();
6897            if (rootView == null) {
6898                rootView = this;
6899            }
6900            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6901            if (labeled != null) {
6902                info.setLabelFor(labeled);
6903            }
6904        }
6905
6906        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6907            View rootView = getRootView();
6908            if (rootView == null) {
6909                rootView = this;
6910            }
6911            View next = rootView.findViewInsideOutShouldExist(this,
6912                    mAccessibilityTraversalBeforeId);
6913            if (next != null && next.includeForAccessibility()) {
6914                info.setTraversalBefore(next);
6915            }
6916        }
6917
6918        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6919            View rootView = getRootView();
6920            if (rootView == null) {
6921                rootView = this;
6922            }
6923            View next = rootView.findViewInsideOutShouldExist(this,
6924                    mAccessibilityTraversalAfterId);
6925            if (next != null && next.includeForAccessibility()) {
6926                info.setTraversalAfter(next);
6927            }
6928        }
6929
6930        info.setVisibleToUser(isVisibleToUser());
6931
6932        if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags
6933                & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) {
6934            info.setImportantForAccessibility(isImportantForAccessibility());
6935        } else {
6936            info.setImportantForAccessibility(true);
6937        }
6938
6939        info.setPackageName(mContext.getPackageName());
6940        info.setClassName(getAccessibilityClassName());
6941        info.setContentDescription(getContentDescription());
6942
6943        info.setEnabled(isEnabled());
6944        info.setClickable(isClickable());
6945        info.setFocusable(isFocusable());
6946        info.setFocused(isFocused());
6947        info.setAccessibilityFocused(isAccessibilityFocused());
6948        info.setSelected(isSelected());
6949        info.setLongClickable(isLongClickable());
6950        info.setContextClickable(isContextClickable());
6951        info.setLiveRegion(getAccessibilityLiveRegion());
6952
6953        // TODO: These make sense only if we are in an AdapterView but all
6954        // views can be selected. Maybe from accessibility perspective
6955        // we should report as selectable view in an AdapterView.
6956        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6957        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6958
6959        if (isFocusable()) {
6960            if (isFocused()) {
6961                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6962            } else {
6963                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6964            }
6965        }
6966
6967        if (!isAccessibilityFocused()) {
6968            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6969        } else {
6970            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6971        }
6972
6973        if (isClickable() && isEnabled()) {
6974            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6975        }
6976
6977        if (isLongClickable() && isEnabled()) {
6978            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6979        }
6980
6981        if (isContextClickable() && isEnabled()) {
6982            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6983        }
6984
6985        CharSequence text = getIterableTextForAccessibility();
6986        if (text != null && text.length() > 0) {
6987            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6988
6989            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6990            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6991            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6992            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6993                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6994                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6995        }
6996
6997        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6998        populateAccessibilityNodeInfoDrawingOrderInParent(info);
6999    }
7000
7001    /**
7002     * Determine the order in which this view will be drawn relative to its siblings for a11y
7003     *
7004     * @param info The info whose drawing order should be populated
7005     */
7006    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7007        /*
7008         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7009         * drawing order may not be well-defined, and some Views with custom drawing order may
7010         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7011         */
7012        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7013            info.setDrawingOrder(0);
7014            return;
7015        }
7016        int drawingOrderInParent = 1;
7017        // Iterate up the hierarchy if parents are not important for a11y
7018        View viewAtDrawingLevel = this;
7019        final ViewParent parent = getParentForAccessibility();
7020        while (viewAtDrawingLevel != parent) {
7021            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7022            if (!(currentParent instanceof ViewGroup)) {
7023                // Should only happen for the Decor
7024                drawingOrderInParent = 0;
7025                break;
7026            } else {
7027                final ViewGroup parentGroup = (ViewGroup) currentParent;
7028                final int childCount = parentGroup.getChildCount();
7029                if (childCount > 1) {
7030                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7031                    if (preorderedList != null) {
7032                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7033                        for (int i = 0; i < childDrawIndex; i++) {
7034                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7035                        }
7036                    } else {
7037                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7038                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7039                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7040                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7041                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7042                        if (childDrawIndex != 0) {
7043                            for (int i = 0; i < numChildrenToIterate; i++) {
7044                                final int otherDrawIndex = (customOrder ?
7045                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7046                                if (otherDrawIndex < childDrawIndex) {
7047                                    drawingOrderInParent +=
7048                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7049                                }
7050                            }
7051                        }
7052                    }
7053                }
7054            }
7055            viewAtDrawingLevel = (View) currentParent;
7056        }
7057        info.setDrawingOrder(drawingOrderInParent);
7058    }
7059
7060    private static int numViewsForAccessibility(View view) {
7061        if (view != null) {
7062            if (view.includeForAccessibility()) {
7063                return 1;
7064            } else if (view instanceof ViewGroup) {
7065                return ((ViewGroup) view).getNumChildrenForAccessibility();
7066            }
7067        }
7068        return 0;
7069    }
7070
7071    private View findLabelForView(View view, int labeledId) {
7072        if (mMatchLabelForPredicate == null) {
7073            mMatchLabelForPredicate = new MatchLabelForPredicate();
7074        }
7075        mMatchLabelForPredicate.mLabeledId = labeledId;
7076        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7077    }
7078
7079    /**
7080     * Computes whether this view is visible to the user. Such a view is
7081     * attached, visible, all its predecessors are visible, it is not clipped
7082     * entirely by its predecessors, and has an alpha greater than zero.
7083     *
7084     * @return Whether the view is visible on the screen.
7085     *
7086     * @hide
7087     */
7088    protected boolean isVisibleToUser() {
7089        return isVisibleToUser(null);
7090    }
7091
7092    /**
7093     * Computes whether the given portion of this view is visible to the user.
7094     * Such a view is attached, visible, all its predecessors are visible,
7095     * has an alpha greater than zero, and the specified portion is not
7096     * clipped entirely by its predecessors.
7097     *
7098     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7099     *                    <code>null</code>, and the entire view will be tested in this case.
7100     *                    When <code>true</code> is returned by the function, the actual visible
7101     *                    region will be stored in this parameter; that is, if boundInView is fully
7102     *                    contained within the view, no modification will be made, otherwise regions
7103     *                    outside of the visible area of the view will be clipped.
7104     *
7105     * @return Whether the specified portion of the view is visible on the screen.
7106     *
7107     * @hide
7108     */
7109    protected boolean isVisibleToUser(Rect boundInView) {
7110        if (mAttachInfo != null) {
7111            // Attached to invisible window means this view is not visible.
7112            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7113                return false;
7114            }
7115            // An invisible predecessor or one with alpha zero means
7116            // that this view is not visible to the user.
7117            Object current = this;
7118            while (current instanceof View) {
7119                View view = (View) current;
7120                // We have attach info so this view is attached and there is no
7121                // need to check whether we reach to ViewRootImpl on the way up.
7122                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7123                        view.getVisibility() != VISIBLE) {
7124                    return false;
7125                }
7126                current = view.mParent;
7127            }
7128            // Check if the view is entirely covered by its predecessors.
7129            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7130            Point offset = mAttachInfo.mPoint;
7131            if (!getGlobalVisibleRect(visibleRect, offset)) {
7132                return false;
7133            }
7134            // Check if the visible portion intersects the rectangle of interest.
7135            if (boundInView != null) {
7136                visibleRect.offset(-offset.x, -offset.y);
7137                return boundInView.intersect(visibleRect);
7138            }
7139            return true;
7140        }
7141        return false;
7142    }
7143
7144    /**
7145     * Returns the delegate for implementing accessibility support via
7146     * composition. For more details see {@link AccessibilityDelegate}.
7147     *
7148     * @return The delegate, or null if none set.
7149     *
7150     * @hide
7151     */
7152    public AccessibilityDelegate getAccessibilityDelegate() {
7153        return mAccessibilityDelegate;
7154    }
7155
7156    /**
7157     * Sets a delegate for implementing accessibility support via composition
7158     * (as opposed to inheritance). For more details, see
7159     * {@link AccessibilityDelegate}.
7160     * <p>
7161     * <strong>Note:</strong> On platform versions prior to
7162     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7163     * views in the {@code android.widget.*} package are called <i>before</i>
7164     * host methods. This prevents certain properties such as class name from
7165     * being modified by overriding
7166     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7167     * as any changes will be overwritten by the host class.
7168     * <p>
7169     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7170     * methods are called <i>after</i> host methods, which all properties to be
7171     * modified without being overwritten by the host class.
7172     *
7173     * @param delegate the object to which accessibility method calls should be
7174     *                 delegated
7175     * @see AccessibilityDelegate
7176     */
7177    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7178        mAccessibilityDelegate = delegate;
7179    }
7180
7181    /**
7182     * Gets the provider for managing a virtual view hierarchy rooted at this View
7183     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7184     * that explore the window content.
7185     * <p>
7186     * If this method returns an instance, this instance is responsible for managing
7187     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7188     * View including the one representing the View itself. Similarly the returned
7189     * instance is responsible for performing accessibility actions on any virtual
7190     * view or the root view itself.
7191     * </p>
7192     * <p>
7193     * If an {@link AccessibilityDelegate} has been specified via calling
7194     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7195     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7196     * is responsible for handling this call.
7197     * </p>
7198     *
7199     * @return The provider.
7200     *
7201     * @see AccessibilityNodeProvider
7202     */
7203    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7204        if (mAccessibilityDelegate != null) {
7205            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7206        } else {
7207            return null;
7208        }
7209    }
7210
7211    /**
7212     * Gets the unique identifier of this view on the screen for accessibility purposes.
7213     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
7214     *
7215     * @return The view accessibility id.
7216     *
7217     * @hide
7218     */
7219    public int getAccessibilityViewId() {
7220        if (mAccessibilityViewId == NO_ID) {
7221            mAccessibilityViewId = sNextAccessibilityViewId++;
7222        }
7223        return mAccessibilityViewId;
7224    }
7225
7226    /**
7227     * Gets the unique identifier of the window in which this View reseides.
7228     *
7229     * @return The window accessibility id.
7230     *
7231     * @hide
7232     */
7233    public int getAccessibilityWindowId() {
7234        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7235                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7236    }
7237
7238    /**
7239     * Returns the {@link View}'s content description.
7240     * <p>
7241     * <strong>Note:</strong> Do not override this method, as it will have no
7242     * effect on the content description presented to accessibility services.
7243     * You must call {@link #setContentDescription(CharSequence)} to modify the
7244     * content description.
7245     *
7246     * @return the content description
7247     * @see #setContentDescription(CharSequence)
7248     * @attr ref android.R.styleable#View_contentDescription
7249     */
7250    @ViewDebug.ExportedProperty(category = "accessibility")
7251    public CharSequence getContentDescription() {
7252        return mContentDescription;
7253    }
7254
7255    /**
7256     * Sets the {@link View}'s content description.
7257     * <p>
7258     * A content description briefly describes the view and is primarily used
7259     * for accessibility support to determine how a view should be presented to
7260     * the user. In the case of a view with no textual representation, such as
7261     * {@link android.widget.ImageButton}, a useful content description
7262     * explains what the view does. For example, an image button with a phone
7263     * icon that is used to place a call may use "Call" as its content
7264     * description. An image of a floppy disk that is used to save a file may
7265     * use "Save".
7266     *
7267     * @param contentDescription The content description.
7268     * @see #getContentDescription()
7269     * @attr ref android.R.styleable#View_contentDescription
7270     */
7271    @RemotableViewMethod
7272    public void setContentDescription(CharSequence contentDescription) {
7273        if (mContentDescription == null) {
7274            if (contentDescription == null) {
7275                return;
7276            }
7277        } else if (mContentDescription.equals(contentDescription)) {
7278            return;
7279        }
7280        mContentDescription = contentDescription;
7281        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7282        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7283            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7284            notifySubtreeAccessibilityStateChangedIfNeeded();
7285        } else {
7286            notifyViewAccessibilityStateChangedIfNeeded(
7287                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7288        }
7289    }
7290
7291    /**
7292     * Sets the id of a view before which this one is visited in accessibility traversal.
7293     * A screen-reader must visit the content of this view before the content of the one
7294     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7295     * will traverse the entire content of B before traversing the entire content of A,
7296     * regardles of what traversal strategy it is using.
7297     * <p>
7298     * Views that do not have specified before/after relationships are traversed in order
7299     * determined by the screen-reader.
7300     * </p>
7301     * <p>
7302     * Setting that this view is before a view that is not important for accessibility
7303     * or if this view is not important for accessibility will have no effect as the
7304     * screen-reader is not aware of unimportant views.
7305     * </p>
7306     *
7307     * @param beforeId The id of a view this one precedes in accessibility traversal.
7308     *
7309     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7310     *
7311     * @see #setImportantForAccessibility(int)
7312     */
7313    @RemotableViewMethod
7314    public void setAccessibilityTraversalBefore(int beforeId) {
7315        if (mAccessibilityTraversalBeforeId == beforeId) {
7316            return;
7317        }
7318        mAccessibilityTraversalBeforeId = beforeId;
7319        notifyViewAccessibilityStateChangedIfNeeded(
7320                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7321    }
7322
7323    /**
7324     * Gets the id of a view before which this one is visited in accessibility traversal.
7325     *
7326     * @return The id of a view this one precedes in accessibility traversal if
7327     *         specified, otherwise {@link #NO_ID}.
7328     *
7329     * @see #setAccessibilityTraversalBefore(int)
7330     */
7331    public int getAccessibilityTraversalBefore() {
7332        return mAccessibilityTraversalBeforeId;
7333    }
7334
7335    /**
7336     * Sets the id of a view after which this one is visited in accessibility traversal.
7337     * A screen-reader must visit the content of the other view before the content of this
7338     * one. For example, if view B is set to be after view A, then a screen-reader
7339     * will traverse the entire content of A before traversing the entire content of B,
7340     * regardles of what traversal strategy it is using.
7341     * <p>
7342     * Views that do not have specified before/after relationships are traversed in order
7343     * determined by the screen-reader.
7344     * </p>
7345     * <p>
7346     * Setting that this view is after a view that is not important for accessibility
7347     * or if this view is not important for accessibility will have no effect as the
7348     * screen-reader is not aware of unimportant views.
7349     * </p>
7350     *
7351     * @param afterId The id of a view this one succedees in accessibility traversal.
7352     *
7353     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7354     *
7355     * @see #setImportantForAccessibility(int)
7356     */
7357    @RemotableViewMethod
7358    public void setAccessibilityTraversalAfter(int afterId) {
7359        if (mAccessibilityTraversalAfterId == afterId) {
7360            return;
7361        }
7362        mAccessibilityTraversalAfterId = afterId;
7363        notifyViewAccessibilityStateChangedIfNeeded(
7364                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7365    }
7366
7367    /**
7368     * Gets the id of a view after which this one is visited in accessibility traversal.
7369     *
7370     * @return The id of a view this one succeedes in accessibility traversal if
7371     *         specified, otherwise {@link #NO_ID}.
7372     *
7373     * @see #setAccessibilityTraversalAfter(int)
7374     */
7375    public int getAccessibilityTraversalAfter() {
7376        return mAccessibilityTraversalAfterId;
7377    }
7378
7379    /**
7380     * Gets the id of a view for which this view serves as a label for
7381     * accessibility purposes.
7382     *
7383     * @return The labeled view id.
7384     */
7385    @ViewDebug.ExportedProperty(category = "accessibility")
7386    public int getLabelFor() {
7387        return mLabelForId;
7388    }
7389
7390    /**
7391     * Sets the id of a view for which this view serves as a label for
7392     * accessibility purposes.
7393     *
7394     * @param id The labeled view id.
7395     */
7396    @RemotableViewMethod
7397    public void setLabelFor(@IdRes int id) {
7398        if (mLabelForId == id) {
7399            return;
7400        }
7401        mLabelForId = id;
7402        if (mLabelForId != View.NO_ID
7403                && mID == View.NO_ID) {
7404            mID = generateViewId();
7405        }
7406        notifyViewAccessibilityStateChangedIfNeeded(
7407                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7408    }
7409
7410    /**
7411     * Invoked whenever this view loses focus, either by losing window focus or by losing
7412     * focus within its window. This method can be used to clear any state tied to the
7413     * focus. For instance, if a button is held pressed with the trackball and the window
7414     * loses focus, this method can be used to cancel the press.
7415     *
7416     * Subclasses of View overriding this method should always call super.onFocusLost().
7417     *
7418     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7419     * @see #onWindowFocusChanged(boolean)
7420     *
7421     * @hide pending API council approval
7422     */
7423    @CallSuper
7424    protected void onFocusLost() {
7425        resetPressedState();
7426    }
7427
7428    private void resetPressedState() {
7429        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7430            return;
7431        }
7432
7433        if (isPressed()) {
7434            setPressed(false);
7435
7436            if (!mHasPerformedLongPress) {
7437                removeLongPressCallback();
7438            }
7439        }
7440    }
7441
7442    /**
7443     * Returns true if this view has focus
7444     *
7445     * @return True if this view has focus, false otherwise.
7446     */
7447    @ViewDebug.ExportedProperty(category = "focus")
7448    public boolean isFocused() {
7449        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7450    }
7451
7452    /**
7453     * Find the view in the hierarchy rooted at this view that currently has
7454     * focus.
7455     *
7456     * @return The view that currently has focus, or null if no focused view can
7457     *         be found.
7458     */
7459    public View findFocus() {
7460        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7461    }
7462
7463    /**
7464     * Indicates whether this view is one of the set of scrollable containers in
7465     * its window.
7466     *
7467     * @return whether this view is one of the set of scrollable containers in
7468     * its window
7469     *
7470     * @attr ref android.R.styleable#View_isScrollContainer
7471     */
7472    public boolean isScrollContainer() {
7473        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7474    }
7475
7476    /**
7477     * Change whether this view is one of the set of scrollable containers in
7478     * its window.  This will be used to determine whether the window can
7479     * resize or must pan when a soft input area is open -- scrollable
7480     * containers allow the window to use resize mode since the container
7481     * will appropriately shrink.
7482     *
7483     * @attr ref android.R.styleable#View_isScrollContainer
7484     */
7485    public void setScrollContainer(boolean isScrollContainer) {
7486        if (isScrollContainer) {
7487            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7488                mAttachInfo.mScrollContainers.add(this);
7489                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7490            }
7491            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7492        } else {
7493            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7494                mAttachInfo.mScrollContainers.remove(this);
7495            }
7496            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7497        }
7498    }
7499
7500    /**
7501     * Returns the quality of the drawing cache.
7502     *
7503     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7504     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7505     *
7506     * @see #setDrawingCacheQuality(int)
7507     * @see #setDrawingCacheEnabled(boolean)
7508     * @see #isDrawingCacheEnabled()
7509     *
7510     * @attr ref android.R.styleable#View_drawingCacheQuality
7511     */
7512    @DrawingCacheQuality
7513    public int getDrawingCacheQuality() {
7514        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7515    }
7516
7517    /**
7518     * Set the drawing cache quality of this view. This value is used only when the
7519     * drawing cache is enabled
7520     *
7521     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7522     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7523     *
7524     * @see #getDrawingCacheQuality()
7525     * @see #setDrawingCacheEnabled(boolean)
7526     * @see #isDrawingCacheEnabled()
7527     *
7528     * @attr ref android.R.styleable#View_drawingCacheQuality
7529     */
7530    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7531        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7532    }
7533
7534    /**
7535     * Returns whether the screen should remain on, corresponding to the current
7536     * value of {@link #KEEP_SCREEN_ON}.
7537     *
7538     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7539     *
7540     * @see #setKeepScreenOn(boolean)
7541     *
7542     * @attr ref android.R.styleable#View_keepScreenOn
7543     */
7544    public boolean getKeepScreenOn() {
7545        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7546    }
7547
7548    /**
7549     * Controls whether the screen should remain on, modifying the
7550     * value of {@link #KEEP_SCREEN_ON}.
7551     *
7552     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7553     *
7554     * @see #getKeepScreenOn()
7555     *
7556     * @attr ref android.R.styleable#View_keepScreenOn
7557     */
7558    public void setKeepScreenOn(boolean keepScreenOn) {
7559        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7560    }
7561
7562    /**
7563     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7564     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7565     *
7566     * @attr ref android.R.styleable#View_nextFocusLeft
7567     */
7568    public int getNextFocusLeftId() {
7569        return mNextFocusLeftId;
7570    }
7571
7572    /**
7573     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7574     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7575     * decide automatically.
7576     *
7577     * @attr ref android.R.styleable#View_nextFocusLeft
7578     */
7579    public void setNextFocusLeftId(int nextFocusLeftId) {
7580        mNextFocusLeftId = nextFocusLeftId;
7581    }
7582
7583    /**
7584     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7585     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7586     *
7587     * @attr ref android.R.styleable#View_nextFocusRight
7588     */
7589    public int getNextFocusRightId() {
7590        return mNextFocusRightId;
7591    }
7592
7593    /**
7594     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7595     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7596     * decide automatically.
7597     *
7598     * @attr ref android.R.styleable#View_nextFocusRight
7599     */
7600    public void setNextFocusRightId(int nextFocusRightId) {
7601        mNextFocusRightId = nextFocusRightId;
7602    }
7603
7604    /**
7605     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7606     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7607     *
7608     * @attr ref android.R.styleable#View_nextFocusUp
7609     */
7610    public int getNextFocusUpId() {
7611        return mNextFocusUpId;
7612    }
7613
7614    /**
7615     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7616     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7617     * decide automatically.
7618     *
7619     * @attr ref android.R.styleable#View_nextFocusUp
7620     */
7621    public void setNextFocusUpId(int nextFocusUpId) {
7622        mNextFocusUpId = nextFocusUpId;
7623    }
7624
7625    /**
7626     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7627     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7628     *
7629     * @attr ref android.R.styleable#View_nextFocusDown
7630     */
7631    public int getNextFocusDownId() {
7632        return mNextFocusDownId;
7633    }
7634
7635    /**
7636     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7637     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7638     * decide automatically.
7639     *
7640     * @attr ref android.R.styleable#View_nextFocusDown
7641     */
7642    public void setNextFocusDownId(int nextFocusDownId) {
7643        mNextFocusDownId = nextFocusDownId;
7644    }
7645
7646    /**
7647     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7648     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7649     *
7650     * @attr ref android.R.styleable#View_nextFocusForward
7651     */
7652    public int getNextFocusForwardId() {
7653        return mNextFocusForwardId;
7654    }
7655
7656    /**
7657     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7658     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7659     * decide automatically.
7660     *
7661     * @attr ref android.R.styleable#View_nextFocusForward
7662     */
7663    public void setNextFocusForwardId(int nextFocusForwardId) {
7664        mNextFocusForwardId = nextFocusForwardId;
7665    }
7666
7667    /**
7668     * Returns the visibility of this view and all of its ancestors
7669     *
7670     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7671     */
7672    public boolean isShown() {
7673        View current = this;
7674        //noinspection ConstantConditions
7675        do {
7676            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7677                return false;
7678            }
7679            ViewParent parent = current.mParent;
7680            if (parent == null) {
7681                return false; // We are not attached to the view root
7682            }
7683            if (!(parent instanceof View)) {
7684                return true;
7685            }
7686            current = (View) parent;
7687        } while (current != null);
7688
7689        return false;
7690    }
7691
7692    /**
7693     * Called by the view hierarchy when the content insets for a window have
7694     * changed, to allow it to adjust its content to fit within those windows.
7695     * The content insets tell you the space that the status bar, input method,
7696     * and other system windows infringe on the application's window.
7697     *
7698     * <p>You do not normally need to deal with this function, since the default
7699     * window decoration given to applications takes care of applying it to the
7700     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7701     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7702     * and your content can be placed under those system elements.  You can then
7703     * use this method within your view hierarchy if you have parts of your UI
7704     * which you would like to ensure are not being covered.
7705     *
7706     * <p>The default implementation of this method simply applies the content
7707     * insets to the view's padding, consuming that content (modifying the
7708     * insets to be 0), and returning true.  This behavior is off by default, but can
7709     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7710     *
7711     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7712     * insets object is propagated down the hierarchy, so any changes made to it will
7713     * be seen by all following views (including potentially ones above in
7714     * the hierarchy since this is a depth-first traversal).  The first view
7715     * that returns true will abort the entire traversal.
7716     *
7717     * <p>The default implementation works well for a situation where it is
7718     * used with a container that covers the entire window, allowing it to
7719     * apply the appropriate insets to its content on all edges.  If you need
7720     * a more complicated layout (such as two different views fitting system
7721     * windows, one on the top of the window, and one on the bottom),
7722     * you can override the method and handle the insets however you would like.
7723     * Note that the insets provided by the framework are always relative to the
7724     * far edges of the window, not accounting for the location of the called view
7725     * within that window.  (In fact when this method is called you do not yet know
7726     * where the layout will place the view, as it is done before layout happens.)
7727     *
7728     * <p>Note: unlike many View methods, there is no dispatch phase to this
7729     * call.  If you are overriding it in a ViewGroup and want to allow the
7730     * call to continue to your children, you must be sure to call the super
7731     * implementation.
7732     *
7733     * <p>Here is a sample layout that makes use of fitting system windows
7734     * to have controls for a video view placed inside of the window decorations
7735     * that it hides and shows.  This can be used with code like the second
7736     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7737     *
7738     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7739     *
7740     * @param insets Current content insets of the window.  Prior to
7741     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7742     * the insets or else you and Android will be unhappy.
7743     *
7744     * @return {@code true} if this view applied the insets and it should not
7745     * continue propagating further down the hierarchy, {@code false} otherwise.
7746     * @see #getFitsSystemWindows()
7747     * @see #setFitsSystemWindows(boolean)
7748     * @see #setSystemUiVisibility(int)
7749     *
7750     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7751     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7752     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7753     * to implement handling their own insets.
7754     */
7755    @Deprecated
7756    protected boolean fitSystemWindows(Rect insets) {
7757        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7758            if (insets == null) {
7759                // Null insets by definition have already been consumed.
7760                // This call cannot apply insets since there are none to apply,
7761                // so return false.
7762                return false;
7763            }
7764            // If we're not in the process of dispatching the newer apply insets call,
7765            // that means we're not in the compatibility path. Dispatch into the newer
7766            // apply insets path and take things from there.
7767            try {
7768                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7769                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7770            } finally {
7771                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7772            }
7773        } else {
7774            // We're being called from the newer apply insets path.
7775            // Perform the standard fallback behavior.
7776            return fitSystemWindowsInt(insets);
7777        }
7778    }
7779
7780    private boolean fitSystemWindowsInt(Rect insets) {
7781        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7782            mUserPaddingStart = UNDEFINED_PADDING;
7783            mUserPaddingEnd = UNDEFINED_PADDING;
7784            Rect localInsets = sThreadLocal.get();
7785            if (localInsets == null) {
7786                localInsets = new Rect();
7787                sThreadLocal.set(localInsets);
7788            }
7789            boolean res = computeFitSystemWindows(insets, localInsets);
7790            mUserPaddingLeftInitial = localInsets.left;
7791            mUserPaddingRightInitial = localInsets.right;
7792            internalSetPadding(localInsets.left, localInsets.top,
7793                    localInsets.right, localInsets.bottom);
7794            return res;
7795        }
7796        return false;
7797    }
7798
7799    /**
7800     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7801     *
7802     * <p>This method should be overridden by views that wish to apply a policy different from or
7803     * in addition to the default behavior. Clients that wish to force a view subtree
7804     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7805     *
7806     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7807     * it will be called during dispatch instead of this method. The listener may optionally
7808     * call this method from its own implementation if it wishes to apply the view's default
7809     * insets policy in addition to its own.</p>
7810     *
7811     * <p>Implementations of this method should either return the insets parameter unchanged
7812     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7813     * that this view applied itself. This allows new inset types added in future platform
7814     * versions to pass through existing implementations unchanged without being erroneously
7815     * consumed.</p>
7816     *
7817     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7818     * property is set then the view will consume the system window insets and apply them
7819     * as padding for the view.</p>
7820     *
7821     * @param insets Insets to apply
7822     * @return The supplied insets with any applied insets consumed
7823     */
7824    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7825        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7826            // We weren't called from within a direct call to fitSystemWindows,
7827            // call into it as a fallback in case we're in a class that overrides it
7828            // and has logic to perform.
7829            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7830                return insets.consumeSystemWindowInsets();
7831            }
7832        } else {
7833            // We were called from within a direct call to fitSystemWindows.
7834            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7835                return insets.consumeSystemWindowInsets();
7836            }
7837        }
7838        return insets;
7839    }
7840
7841    /**
7842     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7843     * window insets to this view. The listener's
7844     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7845     * method will be called instead of the view's
7846     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7847     *
7848     * @param listener Listener to set
7849     *
7850     * @see #onApplyWindowInsets(WindowInsets)
7851     */
7852    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7853        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7854    }
7855
7856    /**
7857     * Request to apply the given window insets to this view or another view in its subtree.
7858     *
7859     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7860     * obscured by window decorations or overlays. This can include the status and navigation bars,
7861     * action bars, input methods and more. New inset categories may be added in the future.
7862     * The method returns the insets provided minus any that were applied by this view or its
7863     * children.</p>
7864     *
7865     * <p>Clients wishing to provide custom behavior should override the
7866     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7867     * {@link OnApplyWindowInsetsListener} via the
7868     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7869     * method.</p>
7870     *
7871     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7872     * </p>
7873     *
7874     * @param insets Insets to apply
7875     * @return The provided insets minus the insets that were consumed
7876     */
7877    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7878        try {
7879            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7880            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7881                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7882            } else {
7883                return onApplyWindowInsets(insets);
7884            }
7885        } finally {
7886            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7887        }
7888    }
7889
7890    /**
7891     * Compute the view's coordinate within the surface.
7892     *
7893     * <p>Computes the coordinates of this view in its surface. The argument
7894     * must be an array of two integers. After the method returns, the array
7895     * contains the x and y location in that order.</p>
7896     * @hide
7897     * @param location an array of two integers in which to hold the coordinates
7898     */
7899    public void getLocationInSurface(@Size(2) int[] location) {
7900        getLocationInWindow(location);
7901        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
7902            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
7903            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
7904        }
7905    }
7906
7907    /**
7908     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7909     * only available if the view is attached.
7910     *
7911     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7912     */
7913    public WindowInsets getRootWindowInsets() {
7914        if (mAttachInfo != null) {
7915            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7916        }
7917        return null;
7918    }
7919
7920    /**
7921     * @hide Compute the insets that should be consumed by this view and the ones
7922     * that should propagate to those under it.
7923     */
7924    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7925        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7926                || mAttachInfo == null
7927                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7928                        && !mAttachInfo.mOverscanRequested)) {
7929            outLocalInsets.set(inoutInsets);
7930            inoutInsets.set(0, 0, 0, 0);
7931            return true;
7932        } else {
7933            // The application wants to take care of fitting system window for
7934            // the content...  however we still need to take care of any overscan here.
7935            final Rect overscan = mAttachInfo.mOverscanInsets;
7936            outLocalInsets.set(overscan);
7937            inoutInsets.left -= overscan.left;
7938            inoutInsets.top -= overscan.top;
7939            inoutInsets.right -= overscan.right;
7940            inoutInsets.bottom -= overscan.bottom;
7941            return false;
7942        }
7943    }
7944
7945    /**
7946     * Compute insets that should be consumed by this view and the ones that should propagate
7947     * to those under it.
7948     *
7949     * @param in Insets currently being processed by this View, likely received as a parameter
7950     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7951     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7952     *                       by this view
7953     * @return Insets that should be passed along to views under this one
7954     */
7955    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7956        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7957                || mAttachInfo == null
7958                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7959            outLocalInsets.set(in.getSystemWindowInsets());
7960            return in.consumeSystemWindowInsets();
7961        } else {
7962            outLocalInsets.set(0, 0, 0, 0);
7963            return in;
7964        }
7965    }
7966
7967    /**
7968     * Sets whether or not this view should account for system screen decorations
7969     * such as the status bar and inset its content; that is, controlling whether
7970     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7971     * executed.  See that method for more details.
7972     *
7973     * <p>Note that if you are providing your own implementation of
7974     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7975     * flag to true -- your implementation will be overriding the default
7976     * implementation that checks this flag.
7977     *
7978     * @param fitSystemWindows If true, then the default implementation of
7979     * {@link #fitSystemWindows(Rect)} will be executed.
7980     *
7981     * @attr ref android.R.styleable#View_fitsSystemWindows
7982     * @see #getFitsSystemWindows()
7983     * @see #fitSystemWindows(Rect)
7984     * @see #setSystemUiVisibility(int)
7985     */
7986    public void setFitsSystemWindows(boolean fitSystemWindows) {
7987        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7988    }
7989
7990    /**
7991     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7992     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7993     * will be executed.
7994     *
7995     * @return {@code true} if the default implementation of
7996     * {@link #fitSystemWindows(Rect)} will be executed.
7997     *
7998     * @attr ref android.R.styleable#View_fitsSystemWindows
7999     * @see #setFitsSystemWindows(boolean)
8000     * @see #fitSystemWindows(Rect)
8001     * @see #setSystemUiVisibility(int)
8002     */
8003    @ViewDebug.ExportedProperty
8004    public boolean getFitsSystemWindows() {
8005        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8006    }
8007
8008    /** @hide */
8009    public boolean fitsSystemWindows() {
8010        return getFitsSystemWindows();
8011    }
8012
8013    /**
8014     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8015     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8016     */
8017    @Deprecated
8018    public void requestFitSystemWindows() {
8019        if (mParent != null) {
8020            mParent.requestFitSystemWindows();
8021        }
8022    }
8023
8024    /**
8025     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8026     */
8027    public void requestApplyInsets() {
8028        requestFitSystemWindows();
8029    }
8030
8031    /**
8032     * For use by PhoneWindow to make its own system window fitting optional.
8033     * @hide
8034     */
8035    public void makeOptionalFitsSystemWindows() {
8036        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8037    }
8038
8039    /**
8040     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8041     * treat them as such.
8042     * @hide
8043     */
8044    public void getOutsets(Rect outOutsetRect) {
8045        if (mAttachInfo != null) {
8046            outOutsetRect.set(mAttachInfo.mOutsets);
8047        } else {
8048            outOutsetRect.setEmpty();
8049        }
8050    }
8051
8052    /**
8053     * Returns the visibility status for this view.
8054     *
8055     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8056     * @attr ref android.R.styleable#View_visibility
8057     */
8058    @ViewDebug.ExportedProperty(mapping = {
8059        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
8060        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
8061        @ViewDebug.IntToString(from = GONE,      to = "GONE")
8062    })
8063    @Visibility
8064    public int getVisibility() {
8065        return mViewFlags & VISIBILITY_MASK;
8066    }
8067
8068    /**
8069     * Set the enabled state of this view.
8070     *
8071     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8072     * @attr ref android.R.styleable#View_visibility
8073     */
8074    @RemotableViewMethod
8075    public void setVisibility(@Visibility int visibility) {
8076        setFlags(visibility, VISIBILITY_MASK);
8077    }
8078
8079    /**
8080     * Returns the enabled status for this view. The interpretation of the
8081     * enabled state varies by subclass.
8082     *
8083     * @return True if this view is enabled, false otherwise.
8084     */
8085    @ViewDebug.ExportedProperty
8086    public boolean isEnabled() {
8087        return (mViewFlags & ENABLED_MASK) == ENABLED;
8088    }
8089
8090    /**
8091     * Set the enabled state of this view. The interpretation of the enabled
8092     * state varies by subclass.
8093     *
8094     * @param enabled True if this view is enabled, false otherwise.
8095     */
8096    @RemotableViewMethod
8097    public void setEnabled(boolean enabled) {
8098        if (enabled == isEnabled()) return;
8099
8100        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8101
8102        /*
8103         * The View most likely has to change its appearance, so refresh
8104         * the drawable state.
8105         */
8106        refreshDrawableState();
8107
8108        // Invalidate too, since the default behavior for views is to be
8109        // be drawn at 50% alpha rather than to change the drawable.
8110        invalidate(true);
8111
8112        if (!enabled) {
8113            cancelPendingInputEvents();
8114        }
8115    }
8116
8117    /**
8118     * Set whether this view can receive the focus.
8119     *
8120     * Setting this to false will also ensure that this view is not focusable
8121     * in touch mode.
8122     *
8123     * @param focusable If true, this view can receive the focus.
8124     *
8125     * @see #setFocusableInTouchMode(boolean)
8126     * @attr ref android.R.styleable#View_focusable
8127     */
8128    public void setFocusable(boolean focusable) {
8129        if (!focusable) {
8130            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8131        }
8132        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8133    }
8134
8135    /**
8136     * Set whether this view can receive focus while in touch mode.
8137     *
8138     * Setting this to true will also ensure that this view is focusable.
8139     *
8140     * @param focusableInTouchMode If true, this view can receive the focus while
8141     *   in touch mode.
8142     *
8143     * @see #setFocusable(boolean)
8144     * @attr ref android.R.styleable#View_focusableInTouchMode
8145     */
8146    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8147        // Focusable in touch mode should always be set before the focusable flag
8148        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8149        // which, in touch mode, will not successfully request focus on this view
8150        // because the focusable in touch mode flag is not set
8151        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8152        if (focusableInTouchMode) {
8153            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8154        }
8155    }
8156
8157    /**
8158     * Set whether this view should have sound effects enabled for events such as
8159     * clicking and touching.
8160     *
8161     * <p>You may wish to disable sound effects for a view if you already play sounds,
8162     * for instance, a dial key that plays dtmf tones.
8163     *
8164     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8165     * @see #isSoundEffectsEnabled()
8166     * @see #playSoundEffect(int)
8167     * @attr ref android.R.styleable#View_soundEffectsEnabled
8168     */
8169    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8170        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8171    }
8172
8173    /**
8174     * @return whether this view should have sound effects enabled for events such as
8175     *     clicking and touching.
8176     *
8177     * @see #setSoundEffectsEnabled(boolean)
8178     * @see #playSoundEffect(int)
8179     * @attr ref android.R.styleable#View_soundEffectsEnabled
8180     */
8181    @ViewDebug.ExportedProperty
8182    public boolean isSoundEffectsEnabled() {
8183        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8184    }
8185
8186    /**
8187     * Set whether this view should have haptic feedback for events such as
8188     * long presses.
8189     *
8190     * <p>You may wish to disable haptic feedback if your view already controls
8191     * its own haptic feedback.
8192     *
8193     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8194     * @see #isHapticFeedbackEnabled()
8195     * @see #performHapticFeedback(int)
8196     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8197     */
8198    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8199        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8200    }
8201
8202    /**
8203     * @return whether this view should have haptic feedback enabled for events
8204     * long presses.
8205     *
8206     * @see #setHapticFeedbackEnabled(boolean)
8207     * @see #performHapticFeedback(int)
8208     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8209     */
8210    @ViewDebug.ExportedProperty
8211    public boolean isHapticFeedbackEnabled() {
8212        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8213    }
8214
8215    /**
8216     * Returns the layout direction for this view.
8217     *
8218     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8219     *   {@link #LAYOUT_DIRECTION_RTL},
8220     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8221     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8222     *
8223     * @attr ref android.R.styleable#View_layoutDirection
8224     *
8225     * @hide
8226     */
8227    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8228        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8229        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8230        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8231        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8232    })
8233    @LayoutDir
8234    public int getRawLayoutDirection() {
8235        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8236    }
8237
8238    /**
8239     * Set the layout direction for this view. This will propagate a reset of layout direction
8240     * resolution to the view's children and resolve layout direction for this view.
8241     *
8242     * @param layoutDirection the layout direction to set. Should be one of:
8243     *
8244     * {@link #LAYOUT_DIRECTION_LTR},
8245     * {@link #LAYOUT_DIRECTION_RTL},
8246     * {@link #LAYOUT_DIRECTION_INHERIT},
8247     * {@link #LAYOUT_DIRECTION_LOCALE}.
8248     *
8249     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8250     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8251     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8252     *
8253     * @attr ref android.R.styleable#View_layoutDirection
8254     */
8255    @RemotableViewMethod
8256    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8257        if (getRawLayoutDirection() != layoutDirection) {
8258            // Reset the current layout direction and the resolved one
8259            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8260            resetRtlProperties();
8261            // Set the new layout direction (filtered)
8262            mPrivateFlags2 |=
8263                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8264            // We need to resolve all RTL properties as they all depend on layout direction
8265            resolveRtlPropertiesIfNeeded();
8266            requestLayout();
8267            invalidate(true);
8268        }
8269    }
8270
8271    /**
8272     * Returns the resolved layout direction for this view.
8273     *
8274     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8275     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8276     *
8277     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8278     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8279     *
8280     * @attr ref android.R.styleable#View_layoutDirection
8281     */
8282    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8283        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8284        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8285    })
8286    @ResolvedLayoutDir
8287    public int getLayoutDirection() {
8288        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8289        if (targetSdkVersion < JELLY_BEAN_MR1) {
8290            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8291            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8292        }
8293        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8294                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8295    }
8296
8297    /**
8298     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8299     * layout attribute and/or the inherited value from the parent
8300     *
8301     * @return true if the layout is right-to-left.
8302     *
8303     * @hide
8304     */
8305    @ViewDebug.ExportedProperty(category = "layout")
8306    public boolean isLayoutRtl() {
8307        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8308    }
8309
8310    /**
8311     * Indicates whether the view is currently tracking transient state that the
8312     * app should not need to concern itself with saving and restoring, but that
8313     * the framework should take special note to preserve when possible.
8314     *
8315     * <p>A view with transient state cannot be trivially rebound from an external
8316     * data source, such as an adapter binding item views in a list. This may be
8317     * because the view is performing an animation, tracking user selection
8318     * of content, or similar.</p>
8319     *
8320     * @return true if the view has transient state
8321     */
8322    @ViewDebug.ExportedProperty(category = "layout")
8323    public boolean hasTransientState() {
8324        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8325    }
8326
8327    /**
8328     * Set whether this view is currently tracking transient state that the
8329     * framework should attempt to preserve when possible. This flag is reference counted,
8330     * so every call to setHasTransientState(true) should be paired with a later call
8331     * to setHasTransientState(false).
8332     *
8333     * <p>A view with transient state cannot be trivially rebound from an external
8334     * data source, such as an adapter binding item views in a list. This may be
8335     * because the view is performing an animation, tracking user selection
8336     * of content, or similar.</p>
8337     *
8338     * @param hasTransientState true if this view has transient state
8339     */
8340    public void setHasTransientState(boolean hasTransientState) {
8341        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8342                mTransientStateCount - 1;
8343        if (mTransientStateCount < 0) {
8344            mTransientStateCount = 0;
8345            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8346                    "unmatched pair of setHasTransientState calls");
8347        } else if ((hasTransientState && mTransientStateCount == 1) ||
8348                (!hasTransientState && mTransientStateCount == 0)) {
8349            // update flag if we've just incremented up from 0 or decremented down to 0
8350            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8351                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8352            if (mParent != null) {
8353                try {
8354                    mParent.childHasTransientStateChanged(this, hasTransientState);
8355                } catch (AbstractMethodError e) {
8356                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8357                            " does not fully implement ViewParent", e);
8358                }
8359            }
8360        }
8361    }
8362
8363    /**
8364     * Returns true if this view is currently attached to a window.
8365     */
8366    public boolean isAttachedToWindow() {
8367        return mAttachInfo != null;
8368    }
8369
8370    /**
8371     * Returns true if this view has been through at least one layout since it
8372     * was last attached to or detached from a window.
8373     */
8374    public boolean isLaidOut() {
8375        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8376    }
8377
8378    /**
8379     * If this view doesn't do any drawing on its own, set this flag to
8380     * allow further optimizations. By default, this flag is not set on
8381     * View, but could be set on some View subclasses such as ViewGroup.
8382     *
8383     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8384     * you should clear this flag.
8385     *
8386     * @param willNotDraw whether or not this View draw on its own
8387     */
8388    public void setWillNotDraw(boolean willNotDraw) {
8389        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8390    }
8391
8392    /**
8393     * Returns whether or not this View draws on its own.
8394     *
8395     * @return true if this view has nothing to draw, false otherwise
8396     */
8397    @ViewDebug.ExportedProperty(category = "drawing")
8398    public boolean willNotDraw() {
8399        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8400    }
8401
8402    /**
8403     * When a View's drawing cache is enabled, drawing is redirected to an
8404     * offscreen bitmap. Some views, like an ImageView, must be able to
8405     * bypass this mechanism if they already draw a single bitmap, to avoid
8406     * unnecessary usage of the memory.
8407     *
8408     * @param willNotCacheDrawing true if this view does not cache its
8409     *        drawing, false otherwise
8410     */
8411    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8412        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8413    }
8414
8415    /**
8416     * Returns whether or not this View can cache its drawing or not.
8417     *
8418     * @return true if this view does not cache its drawing, false otherwise
8419     */
8420    @ViewDebug.ExportedProperty(category = "drawing")
8421    public boolean willNotCacheDrawing() {
8422        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8423    }
8424
8425    /**
8426     * Indicates whether this view reacts to click events or not.
8427     *
8428     * @return true if the view is clickable, false otherwise
8429     *
8430     * @see #setClickable(boolean)
8431     * @attr ref android.R.styleable#View_clickable
8432     */
8433    @ViewDebug.ExportedProperty
8434    public boolean isClickable() {
8435        return (mViewFlags & CLICKABLE) == CLICKABLE;
8436    }
8437
8438    /**
8439     * Enables or disables click events for this view. When a view
8440     * is clickable it will change its state to "pressed" on every click.
8441     * Subclasses should set the view clickable to visually react to
8442     * user's clicks.
8443     *
8444     * @param clickable true to make the view clickable, false otherwise
8445     *
8446     * @see #isClickable()
8447     * @attr ref android.R.styleable#View_clickable
8448     */
8449    public void setClickable(boolean clickable) {
8450        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8451    }
8452
8453    /**
8454     * Indicates whether this view reacts to long click events or not.
8455     *
8456     * @return true if the view is long clickable, false otherwise
8457     *
8458     * @see #setLongClickable(boolean)
8459     * @attr ref android.R.styleable#View_longClickable
8460     */
8461    public boolean isLongClickable() {
8462        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8463    }
8464
8465    /**
8466     * Enables or disables long click events for this view. When a view is long
8467     * clickable it reacts to the user holding down the button for a longer
8468     * duration than a tap. This event can either launch the listener or a
8469     * context menu.
8470     *
8471     * @param longClickable true to make the view long clickable, false otherwise
8472     * @see #isLongClickable()
8473     * @attr ref android.R.styleable#View_longClickable
8474     */
8475    public void setLongClickable(boolean longClickable) {
8476        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8477    }
8478
8479    /**
8480     * Indicates whether this view reacts to context clicks or not.
8481     *
8482     * @return true if the view is context clickable, false otherwise
8483     * @see #setContextClickable(boolean)
8484     * @attr ref android.R.styleable#View_contextClickable
8485     */
8486    public boolean isContextClickable() {
8487        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8488    }
8489
8490    /**
8491     * Enables or disables context clicking for this view. This event can launch the listener.
8492     *
8493     * @param contextClickable true to make the view react to a context click, false otherwise
8494     * @see #isContextClickable()
8495     * @attr ref android.R.styleable#View_contextClickable
8496     */
8497    public void setContextClickable(boolean contextClickable) {
8498        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8499    }
8500
8501    /**
8502     * Sets the pressed state for this view and provides a touch coordinate for
8503     * animation hinting.
8504     *
8505     * @param pressed Pass true to set the View's internal state to "pressed",
8506     *            or false to reverts the View's internal state from a
8507     *            previously set "pressed" state.
8508     * @param x The x coordinate of the touch that caused the press
8509     * @param y The y coordinate of the touch that caused the press
8510     */
8511    private void setPressed(boolean pressed, float x, float y) {
8512        if (pressed) {
8513            drawableHotspotChanged(x, y);
8514        }
8515
8516        setPressed(pressed);
8517    }
8518
8519    /**
8520     * Sets the pressed state for this view.
8521     *
8522     * @see #isClickable()
8523     * @see #setClickable(boolean)
8524     *
8525     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8526     *        the View's internal state from a previously set "pressed" state.
8527     */
8528    public void setPressed(boolean pressed) {
8529        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8530
8531        if (pressed) {
8532            mPrivateFlags |= PFLAG_PRESSED;
8533        } else {
8534            mPrivateFlags &= ~PFLAG_PRESSED;
8535        }
8536
8537        if (needsRefresh) {
8538            refreshDrawableState();
8539        }
8540        dispatchSetPressed(pressed);
8541    }
8542
8543    /**
8544     * Dispatch setPressed to all of this View's children.
8545     *
8546     * @see #setPressed(boolean)
8547     *
8548     * @param pressed The new pressed state
8549     */
8550    protected void dispatchSetPressed(boolean pressed) {
8551    }
8552
8553    /**
8554     * Indicates whether the view is currently in pressed state. Unless
8555     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8556     * the pressed state.
8557     *
8558     * @see #setPressed(boolean)
8559     * @see #isClickable()
8560     * @see #setClickable(boolean)
8561     *
8562     * @return true if the view is currently pressed, false otherwise
8563     */
8564    @ViewDebug.ExportedProperty
8565    public boolean isPressed() {
8566        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8567    }
8568
8569    /**
8570     * @hide
8571     * Indicates whether this view will participate in data collection through
8572     * {@link ViewStructure}.  If true, it will not provide any data
8573     * for itself or its children.  If false, the normal data collection will be allowed.
8574     *
8575     * @return Returns false if assist data collection is not blocked, else true.
8576     *
8577     * @see #setAssistBlocked(boolean)
8578     * @attr ref android.R.styleable#View_assistBlocked
8579     */
8580    public boolean isAssistBlocked() {
8581        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8582    }
8583
8584    /**
8585     * @hide
8586     * Controls whether assist data collection from this view and its children is enabled
8587     * (that is, whether {@link #onProvideStructure} and
8588     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8589     * allowing normal assist collection.  Setting this to false will disable assist collection.
8590     *
8591     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8592     * (the default) to allow it.
8593     *
8594     * @see #isAssistBlocked()
8595     * @see #onProvideStructure
8596     * @see #onProvideVirtualStructure
8597     * @attr ref android.R.styleable#View_assistBlocked
8598     */
8599    public void setAssistBlocked(boolean enabled) {
8600        if (enabled) {
8601            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8602        } else {
8603            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8604        }
8605    }
8606
8607    /**
8608     * Indicates whether this view will save its state (that is,
8609     * whether its {@link #onSaveInstanceState} method will be called).
8610     *
8611     * @return Returns true if the view state saving is enabled, else false.
8612     *
8613     * @see #setSaveEnabled(boolean)
8614     * @attr ref android.R.styleable#View_saveEnabled
8615     */
8616    public boolean isSaveEnabled() {
8617        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8618    }
8619
8620    /**
8621     * Controls whether the saving of this view's state is
8622     * enabled (that is, whether its {@link #onSaveInstanceState} method
8623     * will be called).  Note that even if freezing is enabled, the
8624     * view still must have an id assigned to it (via {@link #setId(int)})
8625     * for its state to be saved.  This flag can only disable the
8626     * saving of this view; any child views may still have their state saved.
8627     *
8628     * @param enabled Set to false to <em>disable</em> state saving, or true
8629     * (the default) to allow it.
8630     *
8631     * @see #isSaveEnabled()
8632     * @see #setId(int)
8633     * @see #onSaveInstanceState()
8634     * @attr ref android.R.styleable#View_saveEnabled
8635     */
8636    public void setSaveEnabled(boolean enabled) {
8637        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8638    }
8639
8640    /**
8641     * Gets whether the framework should discard touches when the view's
8642     * window is obscured by another visible window.
8643     * Refer to the {@link View} security documentation for more details.
8644     *
8645     * @return True if touch filtering is enabled.
8646     *
8647     * @see #setFilterTouchesWhenObscured(boolean)
8648     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8649     */
8650    @ViewDebug.ExportedProperty
8651    public boolean getFilterTouchesWhenObscured() {
8652        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8653    }
8654
8655    /**
8656     * Sets whether the framework should discard touches when the view's
8657     * window is obscured by another visible window.
8658     * Refer to the {@link View} security documentation for more details.
8659     *
8660     * @param enabled True if touch filtering should be enabled.
8661     *
8662     * @see #getFilterTouchesWhenObscured
8663     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8664     */
8665    public void setFilterTouchesWhenObscured(boolean enabled) {
8666        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8667                FILTER_TOUCHES_WHEN_OBSCURED);
8668    }
8669
8670    /**
8671     * Indicates whether the entire hierarchy under this view will save its
8672     * state when a state saving traversal occurs from its parent.  The default
8673     * is true; if false, these views will not be saved unless
8674     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8675     *
8676     * @return Returns true if the view state saving from parent is enabled, else false.
8677     *
8678     * @see #setSaveFromParentEnabled(boolean)
8679     */
8680    public boolean isSaveFromParentEnabled() {
8681        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8682    }
8683
8684    /**
8685     * Controls whether the entire hierarchy under this view will save its
8686     * state when a state saving traversal occurs from its parent.  The default
8687     * is true; if false, these views will not be saved unless
8688     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8689     *
8690     * @param enabled Set to false to <em>disable</em> state saving, or true
8691     * (the default) to allow it.
8692     *
8693     * @see #isSaveFromParentEnabled()
8694     * @see #setId(int)
8695     * @see #onSaveInstanceState()
8696     */
8697    public void setSaveFromParentEnabled(boolean enabled) {
8698        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8699    }
8700
8701
8702    /**
8703     * Returns whether this View is able to take focus.
8704     *
8705     * @return True if this view can take focus, or false otherwise.
8706     * @attr ref android.R.styleable#View_focusable
8707     */
8708    @ViewDebug.ExportedProperty(category = "focus")
8709    public final boolean isFocusable() {
8710        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8711    }
8712
8713    /**
8714     * When a view is focusable, it may not want to take focus when in touch mode.
8715     * For example, a button would like focus when the user is navigating via a D-pad
8716     * so that the user can click on it, but once the user starts touching the screen,
8717     * the button shouldn't take focus
8718     * @return Whether the view is focusable in touch mode.
8719     * @attr ref android.R.styleable#View_focusableInTouchMode
8720     */
8721    @ViewDebug.ExportedProperty
8722    public final boolean isFocusableInTouchMode() {
8723        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8724    }
8725
8726    /**
8727     * Find the nearest view in the specified direction that can take focus.
8728     * This does not actually give focus to that view.
8729     *
8730     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8731     *
8732     * @return The nearest focusable in the specified direction, or null if none
8733     *         can be found.
8734     */
8735    public View focusSearch(@FocusRealDirection int direction) {
8736        if (mParent != null) {
8737            return mParent.focusSearch(this, direction);
8738        } else {
8739            return null;
8740        }
8741    }
8742
8743    /**
8744     * This method is the last chance for the focused view and its ancestors to
8745     * respond to an arrow key. This is called when the focused view did not
8746     * consume the key internally, nor could the view system find a new view in
8747     * the requested direction to give focus to.
8748     *
8749     * @param focused The currently focused view.
8750     * @param direction The direction focus wants to move. One of FOCUS_UP,
8751     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8752     * @return True if the this view consumed this unhandled move.
8753     */
8754    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8755        return false;
8756    }
8757
8758    /**
8759     * If a user manually specified the next view id for a particular direction,
8760     * use the root to look up the view.
8761     * @param root The root view of the hierarchy containing this view.
8762     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8763     * or FOCUS_BACKWARD.
8764     * @return The user specified next view, or null if there is none.
8765     */
8766    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8767        switch (direction) {
8768            case FOCUS_LEFT:
8769                if (mNextFocusLeftId == View.NO_ID) return null;
8770                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8771            case FOCUS_RIGHT:
8772                if (mNextFocusRightId == View.NO_ID) return null;
8773                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8774            case FOCUS_UP:
8775                if (mNextFocusUpId == View.NO_ID) return null;
8776                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8777            case FOCUS_DOWN:
8778                if (mNextFocusDownId == View.NO_ID) return null;
8779                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8780            case FOCUS_FORWARD:
8781                if (mNextFocusForwardId == View.NO_ID) return null;
8782                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8783            case FOCUS_BACKWARD: {
8784                if (mID == View.NO_ID) return null;
8785                final int id = mID;
8786                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8787                    @Override
8788                    public boolean apply(View t) {
8789                        return t.mNextFocusForwardId == id;
8790                    }
8791                });
8792            }
8793        }
8794        return null;
8795    }
8796
8797    private View findViewInsideOutShouldExist(View root, int id) {
8798        if (mMatchIdPredicate == null) {
8799            mMatchIdPredicate = new MatchIdPredicate();
8800        }
8801        mMatchIdPredicate.mId = id;
8802        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8803        if (result == null) {
8804            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8805        }
8806        return result;
8807    }
8808
8809    /**
8810     * Find and return all focusable views that are descendants of this view,
8811     * possibly including this view if it is focusable itself.
8812     *
8813     * @param direction The direction of the focus
8814     * @return A list of focusable views
8815     */
8816    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8817        ArrayList<View> result = new ArrayList<View>(24);
8818        addFocusables(result, direction);
8819        return result;
8820    }
8821
8822    /**
8823     * Add any focusable views that are descendants of this view (possibly
8824     * including this view if it is focusable itself) to views.  If we are in touch mode,
8825     * only add views that are also focusable in touch mode.
8826     *
8827     * @param views Focusable views found so far
8828     * @param direction The direction of the focus
8829     */
8830    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8831        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
8832    }
8833
8834    /**
8835     * Adds any focusable views that are descendants of this view (possibly
8836     * including this view if it is focusable itself) to views. This method
8837     * adds all focusable views regardless if we are in touch mode or
8838     * only views focusable in touch mode if we are in touch mode or
8839     * only views that can take accessibility focus if accessibility is enabled
8840     * depending on the focusable mode parameter.
8841     *
8842     * @param views Focusable views found so far or null if all we are interested is
8843     *        the number of focusables.
8844     * @param direction The direction of the focus.
8845     * @param focusableMode The type of focusables to be added.
8846     *
8847     * @see #FOCUSABLES_ALL
8848     * @see #FOCUSABLES_TOUCH_MODE
8849     */
8850    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8851            @FocusableMode int focusableMode) {
8852        if (views == null) {
8853            return;
8854        }
8855        if (!isFocusable()) {
8856            return;
8857        }
8858        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8859                && !isFocusableInTouchMode()) {
8860            return;
8861        }
8862        views.add(this);
8863    }
8864
8865    /**
8866     * Finds the Views that contain given text. The containment is case insensitive.
8867     * The search is performed by either the text that the View renders or the content
8868     * description that describes the view for accessibility purposes and the view does
8869     * not render or both. Clients can specify how the search is to be performed via
8870     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8871     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8872     *
8873     * @param outViews The output list of matching Views.
8874     * @param searched The text to match against.
8875     *
8876     * @see #FIND_VIEWS_WITH_TEXT
8877     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8878     * @see #setContentDescription(CharSequence)
8879     */
8880    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8881            @FindViewFlags int flags) {
8882        if (getAccessibilityNodeProvider() != null) {
8883            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8884                outViews.add(this);
8885            }
8886        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8887                && (searched != null && searched.length() > 0)
8888                && (mContentDescription != null && mContentDescription.length() > 0)) {
8889            String searchedLowerCase = searched.toString().toLowerCase();
8890            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8891            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8892                outViews.add(this);
8893            }
8894        }
8895    }
8896
8897    /**
8898     * Find and return all touchable views that are descendants of this view,
8899     * possibly including this view if it is touchable itself.
8900     *
8901     * @return A list of touchable views
8902     */
8903    public ArrayList<View> getTouchables() {
8904        ArrayList<View> result = new ArrayList<View>();
8905        addTouchables(result);
8906        return result;
8907    }
8908
8909    /**
8910     * Add any touchable views that are descendants of this view (possibly
8911     * including this view if it is touchable itself) to views.
8912     *
8913     * @param views Touchable views found so far
8914     */
8915    public void addTouchables(ArrayList<View> views) {
8916        final int viewFlags = mViewFlags;
8917
8918        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8919                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8920                && (viewFlags & ENABLED_MASK) == ENABLED) {
8921            views.add(this);
8922        }
8923    }
8924
8925    /**
8926     * Returns whether this View is accessibility focused.
8927     *
8928     * @return True if this View is accessibility focused.
8929     */
8930    public boolean isAccessibilityFocused() {
8931        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8932    }
8933
8934    /**
8935     * Call this to try to give accessibility focus to this view.
8936     *
8937     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8938     * returns false or the view is no visible or the view already has accessibility
8939     * focus.
8940     *
8941     * See also {@link #focusSearch(int)}, which is what you call to say that you
8942     * have focus, and you want your parent to look for the next one.
8943     *
8944     * @return Whether this view actually took accessibility focus.
8945     *
8946     * @hide
8947     */
8948    public boolean requestAccessibilityFocus() {
8949        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8950        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8951            return false;
8952        }
8953        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8954            return false;
8955        }
8956        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8957            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8958            ViewRootImpl viewRootImpl = getViewRootImpl();
8959            if (viewRootImpl != null) {
8960                viewRootImpl.setAccessibilityFocus(this, null);
8961            }
8962            invalidate();
8963            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8964            return true;
8965        }
8966        return false;
8967    }
8968
8969    /**
8970     * Call this to try to clear accessibility focus of this view.
8971     *
8972     * See also {@link #focusSearch(int)}, which is what you call to say that you
8973     * have focus, and you want your parent to look for the next one.
8974     *
8975     * @hide
8976     */
8977    public void clearAccessibilityFocus() {
8978        clearAccessibilityFocusNoCallbacks(0);
8979
8980        // Clear the global reference of accessibility focus if this view or
8981        // any of its descendants had accessibility focus. This will NOT send
8982        // an event or update internal state if focus is cleared from a
8983        // descendant view, which may leave views in inconsistent states.
8984        final ViewRootImpl viewRootImpl = getViewRootImpl();
8985        if (viewRootImpl != null) {
8986            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8987            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8988                viewRootImpl.setAccessibilityFocus(null, null);
8989            }
8990        }
8991    }
8992
8993    private void sendAccessibilityHoverEvent(int eventType) {
8994        // Since we are not delivering to a client accessibility events from not
8995        // important views (unless the clinet request that) we need to fire the
8996        // event from the deepest view exposed to the client. As a consequence if
8997        // the user crosses a not exposed view the client will see enter and exit
8998        // of the exposed predecessor followed by and enter and exit of that same
8999        // predecessor when entering and exiting the not exposed descendant. This
9000        // is fine since the client has a clear idea which view is hovered at the
9001        // price of a couple more events being sent. This is a simple and
9002        // working solution.
9003        View source = this;
9004        while (true) {
9005            if (source.includeForAccessibility()) {
9006                source.sendAccessibilityEvent(eventType);
9007                return;
9008            }
9009            ViewParent parent = source.getParent();
9010            if (parent instanceof View) {
9011                source = (View) parent;
9012            } else {
9013                return;
9014            }
9015        }
9016    }
9017
9018    /**
9019     * Clears accessibility focus without calling any callback methods
9020     * normally invoked in {@link #clearAccessibilityFocus()}. This method
9021     * is used separately from that one for clearing accessibility focus when
9022     * giving this focus to another view.
9023     *
9024     * @param action The action, if any, that led to focus being cleared. Set to
9025     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
9026     * the window.
9027     */
9028    void clearAccessibilityFocusNoCallbacks(int action) {
9029        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
9030            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
9031            invalidate();
9032            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9033                AccessibilityEvent event = AccessibilityEvent.obtain(
9034                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
9035                event.setAction(action);
9036                if (mAccessibilityDelegate != null) {
9037                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
9038                } else {
9039                    sendAccessibilityEventUnchecked(event);
9040                }
9041            }
9042        }
9043    }
9044
9045    /**
9046     * Call this to try to give focus to a specific view or to one of its
9047     * descendants.
9048     *
9049     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9050     * false), or if it is focusable and it is not focusable in touch mode
9051     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9052     *
9053     * See also {@link #focusSearch(int)}, which is what you call to say that you
9054     * have focus, and you want your parent to look for the next one.
9055     *
9056     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
9057     * {@link #FOCUS_DOWN} and <code>null</code>.
9058     *
9059     * @return Whether this view or one of its descendants actually took focus.
9060     */
9061    public final boolean requestFocus() {
9062        return requestFocus(View.FOCUS_DOWN);
9063    }
9064
9065    /**
9066     * Call this to try to give focus to a specific view or to one of its
9067     * descendants and give it a hint about what direction focus is heading.
9068     *
9069     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9070     * false), or if it is focusable and it is not focusable in touch mode
9071     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9072     *
9073     * See also {@link #focusSearch(int)}, which is what you call to say that you
9074     * have focus, and you want your parent to look for the next one.
9075     *
9076     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9077     * <code>null</code> set for the previously focused rectangle.
9078     *
9079     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9080     * @return Whether this view or one of its descendants actually took focus.
9081     */
9082    public final boolean requestFocus(int direction) {
9083        return requestFocus(direction, null);
9084    }
9085
9086    /**
9087     * Call this to try to give focus to a specific view or to one of its descendants
9088     * and give it hints about the direction and a specific rectangle that the focus
9089     * is coming from.  The rectangle can help give larger views a finer grained hint
9090     * about where focus is coming from, and therefore, where to show selection, or
9091     * forward focus change internally.
9092     *
9093     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9094     * false), or if it is focusable and it is not focusable in touch mode
9095     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9096     *
9097     * A View will not take focus if it is not visible.
9098     *
9099     * A View will not take focus if one of its parents has
9100     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9101     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9102     *
9103     * See also {@link #focusSearch(int)}, which is what you call to say that you
9104     * have focus, and you want your parent to look for the next one.
9105     *
9106     * You may wish to override this method if your custom {@link View} has an internal
9107     * {@link View} that it wishes to forward the request to.
9108     *
9109     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9110     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9111     *        to give a finer grained hint about where focus is coming from.  May be null
9112     *        if there is no hint.
9113     * @return Whether this view or one of its descendants actually took focus.
9114     */
9115    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9116        return requestFocusNoSearch(direction, previouslyFocusedRect);
9117    }
9118
9119    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9120        // need to be focusable
9121        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9122                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9123            return false;
9124        }
9125
9126        // need to be focusable in touch mode if in touch mode
9127        if (isInTouchMode() &&
9128            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9129               return false;
9130        }
9131
9132        // need to not have any parents blocking us
9133        if (hasAncestorThatBlocksDescendantFocus()) {
9134            return false;
9135        }
9136
9137        handleFocusGainInternal(direction, previouslyFocusedRect);
9138        return true;
9139    }
9140
9141    /**
9142     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9143     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9144     * touch mode to request focus when they are touched.
9145     *
9146     * @return Whether this view or one of its descendants actually took focus.
9147     *
9148     * @see #isInTouchMode()
9149     *
9150     */
9151    public final boolean requestFocusFromTouch() {
9152        // Leave touch mode if we need to
9153        if (isInTouchMode()) {
9154            ViewRootImpl viewRoot = getViewRootImpl();
9155            if (viewRoot != null) {
9156                viewRoot.ensureTouchMode(false);
9157            }
9158        }
9159        return requestFocus(View.FOCUS_DOWN);
9160    }
9161
9162    /**
9163     * @return Whether any ancestor of this view blocks descendant focus.
9164     */
9165    private boolean hasAncestorThatBlocksDescendantFocus() {
9166        final boolean focusableInTouchMode = isFocusableInTouchMode();
9167        ViewParent ancestor = mParent;
9168        while (ancestor instanceof ViewGroup) {
9169            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9170            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9171                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9172                return true;
9173            } else {
9174                ancestor = vgAncestor.getParent();
9175            }
9176        }
9177        return false;
9178    }
9179
9180    /**
9181     * Gets the mode for determining whether this View is important for accessibility
9182     * which is if it fires accessibility events and if it is reported to
9183     * accessibility services that query the screen.
9184     *
9185     * @return The mode for determining whether a View is important for accessibility.
9186     *
9187     * @attr ref android.R.styleable#View_importantForAccessibility
9188     *
9189     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9190     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9191     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9192     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9193     */
9194    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9195            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9196            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9197            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9198            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9199                    to = "noHideDescendants")
9200        })
9201    public int getImportantForAccessibility() {
9202        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9203                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9204    }
9205
9206    /**
9207     * Sets the live region mode for this view. This indicates to accessibility
9208     * services whether they should automatically notify the user about changes
9209     * to the view's content description or text, or to the content descriptions
9210     * or text of the view's children (where applicable).
9211     * <p>
9212     * For example, in a login screen with a TextView that displays an "incorrect
9213     * password" notification, that view should be marked as a live region with
9214     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9215     * <p>
9216     * To disable change notifications for this view, use
9217     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9218     * mode for most views.
9219     * <p>
9220     * To indicate that the user should be notified of changes, use
9221     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9222     * <p>
9223     * If the view's changes should interrupt ongoing speech and notify the user
9224     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9225     *
9226     * @param mode The live region mode for this view, one of:
9227     *        <ul>
9228     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9229     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9230     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9231     *        </ul>
9232     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9233     */
9234    public void setAccessibilityLiveRegion(int mode) {
9235        if (mode != getAccessibilityLiveRegion()) {
9236            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9237            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9238                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9239            notifyViewAccessibilityStateChangedIfNeeded(
9240                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9241        }
9242    }
9243
9244    /**
9245     * Gets the live region mode for this View.
9246     *
9247     * @return The live region mode for the view.
9248     *
9249     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9250     *
9251     * @see #setAccessibilityLiveRegion(int)
9252     */
9253    public int getAccessibilityLiveRegion() {
9254        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9255                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9256    }
9257
9258    /**
9259     * Sets how to determine whether this view is important for accessibility
9260     * which is if it fires accessibility events and if it is reported to
9261     * accessibility services that query the screen.
9262     *
9263     * @param mode How to determine whether this view is important for accessibility.
9264     *
9265     * @attr ref android.R.styleable#View_importantForAccessibility
9266     *
9267     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9268     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9269     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9270     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9271     */
9272    public void setImportantForAccessibility(int mode) {
9273        final int oldMode = getImportantForAccessibility();
9274        if (mode != oldMode) {
9275            final boolean hideDescendants =
9276                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9277
9278            // If this node or its descendants are no longer important, try to
9279            // clear accessibility focus.
9280            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9281                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9282                if (focusHost != null) {
9283                    focusHost.clearAccessibilityFocus();
9284                }
9285            }
9286
9287            // If we're moving between AUTO and another state, we might not need
9288            // to send a subtree changed notification. We'll store the computed
9289            // importance, since we'll need to check it later to make sure.
9290            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9291                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9292            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9293            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9294            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9295                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9296            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9297                notifySubtreeAccessibilityStateChangedIfNeeded();
9298            } else {
9299                notifyViewAccessibilityStateChangedIfNeeded(
9300                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9301            }
9302        }
9303    }
9304
9305    /**
9306     * Returns the view within this view's hierarchy that is hosting
9307     * accessibility focus.
9308     *
9309     * @param searchDescendants whether to search for focus in descendant views
9310     * @return the view hosting accessibility focus, or {@code null}
9311     */
9312    private View findAccessibilityFocusHost(boolean searchDescendants) {
9313        if (isAccessibilityFocusedViewOrHost()) {
9314            return this;
9315        }
9316
9317        if (searchDescendants) {
9318            final ViewRootImpl viewRoot = getViewRootImpl();
9319            if (viewRoot != null) {
9320                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9321                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9322                    return focusHost;
9323                }
9324            }
9325        }
9326
9327        return null;
9328    }
9329
9330    /**
9331     * Computes whether this view should be exposed for accessibility. In
9332     * general, views that are interactive or provide information are exposed
9333     * while views that serve only as containers are hidden.
9334     * <p>
9335     * If an ancestor of this view has importance
9336     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9337     * returns <code>false</code>.
9338     * <p>
9339     * Otherwise, the value is computed according to the view's
9340     * {@link #getImportantForAccessibility()} value:
9341     * <ol>
9342     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9343     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9344     * </code>
9345     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9346     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9347     * view satisfies any of the following:
9348     * <ul>
9349     * <li>Is actionable, e.g. {@link #isClickable()},
9350     * {@link #isLongClickable()}, or {@link #isFocusable()}
9351     * <li>Has an {@link AccessibilityDelegate}
9352     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9353     * {@link OnKeyListener}, etc.
9354     * <li>Is an accessibility live region, e.g.
9355     * {@link #getAccessibilityLiveRegion()} is not
9356     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9357     * </ul>
9358     * </ol>
9359     *
9360     * @return Whether the view is exposed for accessibility.
9361     * @see #setImportantForAccessibility(int)
9362     * @see #getImportantForAccessibility()
9363     */
9364    public boolean isImportantForAccessibility() {
9365        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9366                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9367        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9368                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9369            return false;
9370        }
9371
9372        // Check parent mode to ensure we're not hidden.
9373        ViewParent parent = mParent;
9374        while (parent instanceof View) {
9375            if (((View) parent).getImportantForAccessibility()
9376                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9377                return false;
9378            }
9379            parent = parent.getParent();
9380        }
9381
9382        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9383                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9384                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9385    }
9386
9387    /**
9388     * Gets the parent for accessibility purposes. Note that the parent for
9389     * accessibility is not necessary the immediate parent. It is the first
9390     * predecessor that is important for accessibility.
9391     *
9392     * @return The parent for accessibility purposes.
9393     */
9394    public ViewParent getParentForAccessibility() {
9395        if (mParent instanceof View) {
9396            View parentView = (View) mParent;
9397            if (parentView.includeForAccessibility()) {
9398                return mParent;
9399            } else {
9400                return mParent.getParentForAccessibility();
9401            }
9402        }
9403        return null;
9404    }
9405
9406    /**
9407     * Adds the children of this View relevant for accessibility to the given list
9408     * as output. Since some Views are not important for accessibility the added
9409     * child views are not necessarily direct children of this view, rather they are
9410     * the first level of descendants important for accessibility.
9411     *
9412     * @param outChildren The output list that will receive children for accessibility.
9413     */
9414    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9415
9416    }
9417
9418    /**
9419     * Whether to regard this view for accessibility. A view is regarded for
9420     * accessibility if it is important for accessibility or the querying
9421     * accessibility service has explicitly requested that view not
9422     * important for accessibility are regarded.
9423     *
9424     * @return Whether to regard the view for accessibility.
9425     *
9426     * @hide
9427     */
9428    public boolean includeForAccessibility() {
9429        if (mAttachInfo != null) {
9430            return (mAttachInfo.mAccessibilityFetchFlags
9431                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9432                    || isImportantForAccessibility();
9433        }
9434        return false;
9435    }
9436
9437    /**
9438     * Returns whether the View is considered actionable from
9439     * accessibility perspective. Such view are important for
9440     * accessibility.
9441     *
9442     * @return True if the view is actionable for accessibility.
9443     *
9444     * @hide
9445     */
9446    public boolean isActionableForAccessibility() {
9447        return (isClickable() || isLongClickable() || isFocusable());
9448    }
9449
9450    /**
9451     * Returns whether the View has registered callbacks which makes it
9452     * important for accessibility.
9453     *
9454     * @return True if the view is actionable for accessibility.
9455     */
9456    private boolean hasListenersForAccessibility() {
9457        ListenerInfo info = getListenerInfo();
9458        return mTouchDelegate != null || info.mOnKeyListener != null
9459                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9460                || info.mOnHoverListener != null || info.mOnDragListener != null;
9461    }
9462
9463    /**
9464     * Notifies that the accessibility state of this view changed. The change
9465     * is local to this view and does not represent structural changes such
9466     * as children and parent. For example, the view became focusable. The
9467     * notification is at at most once every
9468     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9469     * to avoid unnecessary load to the system. Also once a view has a pending
9470     * notification this method is a NOP until the notification has been sent.
9471     *
9472     * @hide
9473     */
9474    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9475        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9476            return;
9477        }
9478        if (mSendViewStateChangedAccessibilityEvent == null) {
9479            mSendViewStateChangedAccessibilityEvent =
9480                    new SendViewStateChangedAccessibilityEvent();
9481        }
9482        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9483    }
9484
9485    /**
9486     * Notifies that the accessibility state of this view changed. The change
9487     * is *not* local to this view and does represent structural changes such
9488     * as children and parent. For example, the view size changed. The
9489     * notification is at at most once every
9490     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9491     * to avoid unnecessary load to the system. Also once a view has a pending
9492     * notification this method is a NOP until the notification has been sent.
9493     *
9494     * @hide
9495     */
9496    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9497        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9498            return;
9499        }
9500        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9501            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9502            if (mParent != null) {
9503                try {
9504                    mParent.notifySubtreeAccessibilityStateChanged(
9505                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9506                } catch (AbstractMethodError e) {
9507                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9508                            " does not fully implement ViewParent", e);
9509                }
9510            }
9511        }
9512    }
9513
9514    /**
9515     * Change the visibility of the View without triggering any other changes. This is
9516     * important for transitions, where visibility changes should not adjust focus or
9517     * trigger a new layout. This is only used when the visibility has already been changed
9518     * and we need a transient value during an animation. When the animation completes,
9519     * the original visibility value is always restored.
9520     *
9521     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9522     * @hide
9523     */
9524    public void setTransitionVisibility(@Visibility int visibility) {
9525        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9526    }
9527
9528    /**
9529     * Reset the flag indicating the accessibility state of the subtree rooted
9530     * at this view changed.
9531     */
9532    void resetSubtreeAccessibilityStateChanged() {
9533        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9534    }
9535
9536    /**
9537     * Report an accessibility action to this view's parents for delegated processing.
9538     *
9539     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9540     * call this method to delegate an accessibility action to a supporting parent. If the parent
9541     * returns true from its
9542     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9543     * method this method will return true to signify that the action was consumed.</p>
9544     *
9545     * <p>This method is useful for implementing nested scrolling child views. If
9546     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9547     * a custom view implementation may invoke this method to allow a parent to consume the
9548     * scroll first. If this method returns true the custom view should skip its own scrolling
9549     * behavior.</p>
9550     *
9551     * @param action Accessibility action to delegate
9552     * @param arguments Optional action arguments
9553     * @return true if the action was consumed by a parent
9554     */
9555    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9556        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9557            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9558                return true;
9559            }
9560        }
9561        return false;
9562    }
9563
9564    /**
9565     * Performs the specified accessibility action on the view. For
9566     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9567     * <p>
9568     * If an {@link AccessibilityDelegate} has been specified via calling
9569     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9570     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9571     * is responsible for handling this call.
9572     * </p>
9573     *
9574     * <p>The default implementation will delegate
9575     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9576     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9577     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9578     *
9579     * @param action The action to perform.
9580     * @param arguments Optional action arguments.
9581     * @return Whether the action was performed.
9582     */
9583    public boolean performAccessibilityAction(int action, Bundle arguments) {
9584      if (mAccessibilityDelegate != null) {
9585          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9586      } else {
9587          return performAccessibilityActionInternal(action, arguments);
9588      }
9589    }
9590
9591   /**
9592    * @see #performAccessibilityAction(int, Bundle)
9593    *
9594    * Note: Called from the default {@link AccessibilityDelegate}.
9595    *
9596    * @hide
9597    */
9598    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9599        if (isNestedScrollingEnabled()
9600                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9601                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9602                || action == R.id.accessibilityActionScrollUp
9603                || action == R.id.accessibilityActionScrollLeft
9604                || action == R.id.accessibilityActionScrollDown
9605                || action == R.id.accessibilityActionScrollRight)) {
9606            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9607                return true;
9608            }
9609        }
9610
9611        switch (action) {
9612            case AccessibilityNodeInfo.ACTION_CLICK: {
9613                if (isClickable()) {
9614                    performClick();
9615                    return true;
9616                }
9617            } break;
9618            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9619                if (isLongClickable()) {
9620                    performLongClick();
9621                    return true;
9622                }
9623            } break;
9624            case AccessibilityNodeInfo.ACTION_FOCUS: {
9625                if (!hasFocus()) {
9626                    // Get out of touch mode since accessibility
9627                    // wants to move focus around.
9628                    getViewRootImpl().ensureTouchMode(false);
9629                    return requestFocus();
9630                }
9631            } break;
9632            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9633                if (hasFocus()) {
9634                    clearFocus();
9635                    return !isFocused();
9636                }
9637            } break;
9638            case AccessibilityNodeInfo.ACTION_SELECT: {
9639                if (!isSelected()) {
9640                    setSelected(true);
9641                    return isSelected();
9642                }
9643            } break;
9644            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9645                if (isSelected()) {
9646                    setSelected(false);
9647                    return !isSelected();
9648                }
9649            } break;
9650            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9651                if (!isAccessibilityFocused()) {
9652                    return requestAccessibilityFocus();
9653                }
9654            } break;
9655            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
9656                if (isAccessibilityFocused()) {
9657                    clearAccessibilityFocus();
9658                    return true;
9659                }
9660            } break;
9661            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
9662                if (arguments != null) {
9663                    final int granularity = arguments.getInt(
9664                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9665                    final boolean extendSelection = arguments.getBoolean(
9666                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9667                    return traverseAtGranularity(granularity, true, extendSelection);
9668                }
9669            } break;
9670            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9671                if (arguments != null) {
9672                    final int granularity = arguments.getInt(
9673                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9674                    final boolean extendSelection = arguments.getBoolean(
9675                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9676                    return traverseAtGranularity(granularity, false, extendSelection);
9677                }
9678            } break;
9679            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9680                CharSequence text = getIterableTextForAccessibility();
9681                if (text == null) {
9682                    return false;
9683                }
9684                final int start = (arguments != null) ? arguments.getInt(
9685                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9686                final int end = (arguments != null) ? arguments.getInt(
9687                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9688                // Only cursor position can be specified (selection length == 0)
9689                if ((getAccessibilitySelectionStart() != start
9690                        || getAccessibilitySelectionEnd() != end)
9691                        && (start == end)) {
9692                    setAccessibilitySelection(start, end);
9693                    notifyViewAccessibilityStateChangedIfNeeded(
9694                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9695                    return true;
9696                }
9697            } break;
9698            case R.id.accessibilityActionShowOnScreen: {
9699                if (mAttachInfo != null) {
9700                    final Rect r = mAttachInfo.mTmpInvalRect;
9701                    getDrawingRect(r);
9702                    return requestRectangleOnScreen(r, true);
9703                }
9704            } break;
9705            case R.id.accessibilityActionContextClick: {
9706                if (isContextClickable()) {
9707                    performContextClick();
9708                    return true;
9709                }
9710            } break;
9711        }
9712        return false;
9713    }
9714
9715    private boolean traverseAtGranularity(int granularity, boolean forward,
9716            boolean extendSelection) {
9717        CharSequence text = getIterableTextForAccessibility();
9718        if (text == null || text.length() == 0) {
9719            return false;
9720        }
9721        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9722        if (iterator == null) {
9723            return false;
9724        }
9725        int current = getAccessibilitySelectionEnd();
9726        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9727            current = forward ? 0 : text.length();
9728        }
9729        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9730        if (range == null) {
9731            return false;
9732        }
9733        final int segmentStart = range[0];
9734        final int segmentEnd = range[1];
9735        int selectionStart;
9736        int selectionEnd;
9737        if (extendSelection && isAccessibilitySelectionExtendable()) {
9738            selectionStart = getAccessibilitySelectionStart();
9739            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9740                selectionStart = forward ? segmentStart : segmentEnd;
9741            }
9742            selectionEnd = forward ? segmentEnd : segmentStart;
9743        } else {
9744            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9745        }
9746        setAccessibilitySelection(selectionStart, selectionEnd);
9747        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9748                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9749        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9750        return true;
9751    }
9752
9753    /**
9754     * Gets the text reported for accessibility purposes.
9755     *
9756     * @return The accessibility text.
9757     *
9758     * @hide
9759     */
9760    public CharSequence getIterableTextForAccessibility() {
9761        return getContentDescription();
9762    }
9763
9764    /**
9765     * Gets whether accessibility selection can be extended.
9766     *
9767     * @return If selection is extensible.
9768     *
9769     * @hide
9770     */
9771    public boolean isAccessibilitySelectionExtendable() {
9772        return false;
9773    }
9774
9775    /**
9776     * @hide
9777     */
9778    public int getAccessibilitySelectionStart() {
9779        return mAccessibilityCursorPosition;
9780    }
9781
9782    /**
9783     * @hide
9784     */
9785    public int getAccessibilitySelectionEnd() {
9786        return getAccessibilitySelectionStart();
9787    }
9788
9789    /**
9790     * @hide
9791     */
9792    public void setAccessibilitySelection(int start, int end) {
9793        if (start ==  end && end == mAccessibilityCursorPosition) {
9794            return;
9795        }
9796        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9797            mAccessibilityCursorPosition = start;
9798        } else {
9799            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9800        }
9801        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9802    }
9803
9804    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9805            int fromIndex, int toIndex) {
9806        if (mParent == null) {
9807            return;
9808        }
9809        AccessibilityEvent event = AccessibilityEvent.obtain(
9810                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9811        onInitializeAccessibilityEvent(event);
9812        onPopulateAccessibilityEvent(event);
9813        event.setFromIndex(fromIndex);
9814        event.setToIndex(toIndex);
9815        event.setAction(action);
9816        event.setMovementGranularity(granularity);
9817        mParent.requestSendAccessibilityEvent(this, event);
9818    }
9819
9820    /**
9821     * @hide
9822     */
9823    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9824        switch (granularity) {
9825            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9826                CharSequence text = getIterableTextForAccessibility();
9827                if (text != null && text.length() > 0) {
9828                    CharacterTextSegmentIterator iterator =
9829                        CharacterTextSegmentIterator.getInstance(
9830                                mContext.getResources().getConfiguration().locale);
9831                    iterator.initialize(text.toString());
9832                    return iterator;
9833                }
9834            } break;
9835            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9836                CharSequence text = getIterableTextForAccessibility();
9837                if (text != null && text.length() > 0) {
9838                    WordTextSegmentIterator iterator =
9839                        WordTextSegmentIterator.getInstance(
9840                                mContext.getResources().getConfiguration().locale);
9841                    iterator.initialize(text.toString());
9842                    return iterator;
9843                }
9844            } break;
9845            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9846                CharSequence text = getIterableTextForAccessibility();
9847                if (text != null && text.length() > 0) {
9848                    ParagraphTextSegmentIterator iterator =
9849                        ParagraphTextSegmentIterator.getInstance();
9850                    iterator.initialize(text.toString());
9851                    return iterator;
9852                }
9853            } break;
9854        }
9855        return null;
9856    }
9857
9858    /**
9859     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
9860     * and {@link #onFinishTemporaryDetach()}.
9861     */
9862    public final boolean isTemporarilyDetached() {
9863        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
9864    }
9865
9866    /**
9867     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
9868     * a container View.
9869     */
9870    @CallSuper
9871    public void dispatchStartTemporaryDetach() {
9872        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
9873        onStartTemporaryDetach();
9874    }
9875
9876    /**
9877     * This is called when a container is going to temporarily detach a child, with
9878     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9879     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9880     * {@link #onDetachedFromWindow()} when the container is done.
9881     */
9882    public void onStartTemporaryDetach() {
9883        removeUnsetPressCallback();
9884        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9885    }
9886
9887    /**
9888     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
9889     * a container View.
9890     */
9891    @CallSuper
9892    public void dispatchFinishTemporaryDetach() {
9893        onFinishTemporaryDetach();
9894        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
9895        if (hasWindowFocus() && hasFocus()) {
9896            InputMethodManager.getInstance().focusIn(this);
9897        }
9898    }
9899
9900    /**
9901     * Called after {@link #onStartTemporaryDetach} when the container is done
9902     * changing the view.
9903     */
9904    public void onFinishTemporaryDetach() {
9905    }
9906
9907    /**
9908     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9909     * for this view's window.  Returns null if the view is not currently attached
9910     * to the window.  Normally you will not need to use this directly, but
9911     * just use the standard high-level event callbacks like
9912     * {@link #onKeyDown(int, KeyEvent)}.
9913     */
9914    public KeyEvent.DispatcherState getKeyDispatcherState() {
9915        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9916    }
9917
9918    /**
9919     * Dispatch a key event before it is processed by any input method
9920     * associated with the view hierarchy.  This can be used to intercept
9921     * key events in special situations before the IME consumes them; a
9922     * typical example would be handling the BACK key to update the application's
9923     * UI instead of allowing the IME to see it and close itself.
9924     *
9925     * @param event The key event to be dispatched.
9926     * @return True if the event was handled, false otherwise.
9927     */
9928    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9929        return onKeyPreIme(event.getKeyCode(), event);
9930    }
9931
9932    /**
9933     * Dispatch a key event to the next view on the focus path. This path runs
9934     * from the top of the view tree down to the currently focused view. If this
9935     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9936     * the next node down the focus path. This method also fires any key
9937     * listeners.
9938     *
9939     * @param event The key event to be dispatched.
9940     * @return True if the event was handled, false otherwise.
9941     */
9942    public boolean dispatchKeyEvent(KeyEvent event) {
9943        if (mInputEventConsistencyVerifier != null) {
9944            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9945        }
9946
9947        // Give any attached key listener a first crack at the event.
9948        //noinspection SimplifiableIfStatement
9949        ListenerInfo li = mListenerInfo;
9950        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9951                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9952            return true;
9953        }
9954
9955        if (event.dispatch(this, mAttachInfo != null
9956                ? mAttachInfo.mKeyDispatchState : null, this)) {
9957            return true;
9958        }
9959
9960        if (mInputEventConsistencyVerifier != null) {
9961            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9962        }
9963        return false;
9964    }
9965
9966    /**
9967     * Dispatches a key shortcut event.
9968     *
9969     * @param event The key event to be dispatched.
9970     * @return True if the event was handled by the view, false otherwise.
9971     */
9972    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9973        return onKeyShortcut(event.getKeyCode(), event);
9974    }
9975
9976    /**
9977     * Pass the touch screen motion event down to the target view, or this
9978     * view if it is the target.
9979     *
9980     * @param event The motion event to be dispatched.
9981     * @return True if the event was handled by the view, false otherwise.
9982     */
9983    public boolean dispatchTouchEvent(MotionEvent event) {
9984        // If the event should be handled by accessibility focus first.
9985        if (event.isTargetAccessibilityFocus()) {
9986            // We don't have focus or no virtual descendant has it, do not handle the event.
9987            if (!isAccessibilityFocusedViewOrHost()) {
9988                return false;
9989            }
9990            // We have focus and got the event, then use normal event dispatch.
9991            event.setTargetAccessibilityFocus(false);
9992        }
9993
9994        boolean result = false;
9995
9996        if (mInputEventConsistencyVerifier != null) {
9997            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
9998        }
9999
10000        final int actionMasked = event.getActionMasked();
10001        if (actionMasked == MotionEvent.ACTION_DOWN) {
10002            // Defensive cleanup for new gesture
10003            stopNestedScroll();
10004        }
10005
10006        if (onFilterTouchEventForSecurity(event)) {
10007            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
10008                result = true;
10009            }
10010            //noinspection SimplifiableIfStatement
10011            ListenerInfo li = mListenerInfo;
10012            if (li != null && li.mOnTouchListener != null
10013                    && (mViewFlags & ENABLED_MASK) == ENABLED
10014                    && li.mOnTouchListener.onTouch(this, event)) {
10015                result = true;
10016            }
10017
10018            if (!result && onTouchEvent(event)) {
10019                result = true;
10020            }
10021        }
10022
10023        if (!result && mInputEventConsistencyVerifier != null) {
10024            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10025        }
10026
10027        // Clean up after nested scrolls if this is the end of a gesture;
10028        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
10029        // of the gesture.
10030        if (actionMasked == MotionEvent.ACTION_UP ||
10031                actionMasked == MotionEvent.ACTION_CANCEL ||
10032                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
10033            stopNestedScroll();
10034        }
10035
10036        return result;
10037    }
10038
10039    boolean isAccessibilityFocusedViewOrHost() {
10040        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
10041                .getAccessibilityFocusedHost() == this);
10042    }
10043
10044    /**
10045     * Filter the touch event to apply security policies.
10046     *
10047     * @param event The motion event to be filtered.
10048     * @return True if the event should be dispatched, false if the event should be dropped.
10049     *
10050     * @see #getFilterTouchesWhenObscured
10051     */
10052    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
10053        //noinspection RedundantIfStatement
10054        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
10055                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
10056            // Window is obscured, drop this touch.
10057            return false;
10058        }
10059        return true;
10060    }
10061
10062    /**
10063     * Pass a trackball motion event down to the focused view.
10064     *
10065     * @param event The motion event to be dispatched.
10066     * @return True if the event was handled by the view, false otherwise.
10067     */
10068    public boolean dispatchTrackballEvent(MotionEvent event) {
10069        if (mInputEventConsistencyVerifier != null) {
10070            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
10071        }
10072
10073        return onTrackballEvent(event);
10074    }
10075
10076    /**
10077     * Dispatch a generic motion event.
10078     * <p>
10079     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10080     * are delivered to the view under the pointer.  All other generic motion events are
10081     * delivered to the focused view.  Hover events are handled specially and are delivered
10082     * to {@link #onHoverEvent(MotionEvent)}.
10083     * </p>
10084     *
10085     * @param event The motion event to be dispatched.
10086     * @return True if the event was handled by the view, false otherwise.
10087     */
10088    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10089        if (mInputEventConsistencyVerifier != null) {
10090            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10091        }
10092
10093        final int source = event.getSource();
10094        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10095            final int action = event.getAction();
10096            if (action == MotionEvent.ACTION_HOVER_ENTER
10097                    || action == MotionEvent.ACTION_HOVER_MOVE
10098                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10099                if (dispatchHoverEvent(event)) {
10100                    return true;
10101                }
10102            } else if (dispatchGenericPointerEvent(event)) {
10103                return true;
10104            }
10105        } else if (dispatchGenericFocusedEvent(event)) {
10106            return true;
10107        }
10108
10109        if (dispatchGenericMotionEventInternal(event)) {
10110            return true;
10111        }
10112
10113        if (mInputEventConsistencyVerifier != null) {
10114            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10115        }
10116        return false;
10117    }
10118
10119    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10120        //noinspection SimplifiableIfStatement
10121        ListenerInfo li = mListenerInfo;
10122        if (li != null && li.mOnGenericMotionListener != null
10123                && (mViewFlags & ENABLED_MASK) == ENABLED
10124                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10125            return true;
10126        }
10127
10128        if (onGenericMotionEvent(event)) {
10129            return true;
10130        }
10131
10132        final int actionButton = event.getActionButton();
10133        switch (event.getActionMasked()) {
10134            case MotionEvent.ACTION_BUTTON_PRESS:
10135                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10136                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10137                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10138                    if (performContextClick(event.getX(), event.getY())) {
10139                        mInContextButtonPress = true;
10140                        setPressed(true, event.getX(), event.getY());
10141                        removeTapCallback();
10142                        removeLongPressCallback();
10143                        return true;
10144                    }
10145                }
10146                break;
10147
10148            case MotionEvent.ACTION_BUTTON_RELEASE:
10149                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10150                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10151                    mInContextButtonPress = false;
10152                    mIgnoreNextUpEvent = true;
10153                }
10154                break;
10155        }
10156
10157        if (mInputEventConsistencyVerifier != null) {
10158            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10159        }
10160        return false;
10161    }
10162
10163    /**
10164     * Dispatch a hover event.
10165     * <p>
10166     * Do not call this method directly.
10167     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10168     * </p>
10169     *
10170     * @param event The motion event to be dispatched.
10171     * @return True if the event was handled by the view, false otherwise.
10172     */
10173    protected boolean dispatchHoverEvent(MotionEvent event) {
10174        ListenerInfo li = mListenerInfo;
10175        //noinspection SimplifiableIfStatement
10176        if (li != null && li.mOnHoverListener != null
10177                && (mViewFlags & ENABLED_MASK) == ENABLED
10178                && li.mOnHoverListener.onHover(this, event)) {
10179            return true;
10180        }
10181
10182        return onHoverEvent(event);
10183    }
10184
10185    /**
10186     * Returns true if the view has a child to which it has recently sent
10187     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10188     * it does not have a hovered child, then it must be the innermost hovered view.
10189     * @hide
10190     */
10191    protected boolean hasHoveredChild() {
10192        return false;
10193    }
10194
10195    /**
10196     * Dispatch a generic motion event to the view under the first pointer.
10197     * <p>
10198     * Do not call this method directly.
10199     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10200     * </p>
10201     *
10202     * @param event The motion event to be dispatched.
10203     * @return True if the event was handled by the view, false otherwise.
10204     */
10205    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10206        return false;
10207    }
10208
10209    /**
10210     * Dispatch a generic motion event to the currently focused view.
10211     * <p>
10212     * Do not call this method directly.
10213     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10214     * </p>
10215     *
10216     * @param event The motion event to be dispatched.
10217     * @return True if the event was handled by the view, false otherwise.
10218     */
10219    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10220        return false;
10221    }
10222
10223    /**
10224     * Dispatch a pointer event.
10225     * <p>
10226     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10227     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10228     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10229     * and should not be expected to handle other pointing device features.
10230     * </p>
10231     *
10232     * @param event The motion event to be dispatched.
10233     * @return True if the event was handled by the view, false otherwise.
10234     * @hide
10235     */
10236    public final boolean dispatchPointerEvent(MotionEvent event) {
10237        if (event.isTouchEvent()) {
10238            return dispatchTouchEvent(event);
10239        } else {
10240            return dispatchGenericMotionEvent(event);
10241        }
10242    }
10243
10244    /**
10245     * Called when the window containing this view gains or loses window focus.
10246     * ViewGroups should override to route to their children.
10247     *
10248     * @param hasFocus True if the window containing this view now has focus,
10249     *        false otherwise.
10250     */
10251    public void dispatchWindowFocusChanged(boolean hasFocus) {
10252        onWindowFocusChanged(hasFocus);
10253    }
10254
10255    /**
10256     * Called when the window containing this view gains or loses focus.  Note
10257     * that this is separate from view focus: to receive key events, both
10258     * your view and its window must have focus.  If a window is displayed
10259     * on top of yours that takes input focus, then your own window will lose
10260     * focus but the view focus will remain unchanged.
10261     *
10262     * @param hasWindowFocus True if the window containing this view now has
10263     *        focus, false otherwise.
10264     */
10265    public void onWindowFocusChanged(boolean hasWindowFocus) {
10266        InputMethodManager imm = InputMethodManager.peekInstance();
10267        if (!hasWindowFocus) {
10268            if (isPressed()) {
10269                setPressed(false);
10270            }
10271            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10272                imm.focusOut(this);
10273            }
10274            removeLongPressCallback();
10275            removeTapCallback();
10276            onFocusLost();
10277        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10278            imm.focusIn(this);
10279        }
10280        refreshDrawableState();
10281    }
10282
10283    /**
10284     * Returns true if this view is in a window that currently has window focus.
10285     * Note that this is not the same as the view itself having focus.
10286     *
10287     * @return True if this view is in a window that currently has window focus.
10288     */
10289    public boolean hasWindowFocus() {
10290        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10291    }
10292
10293    /**
10294     * Dispatch a view visibility change down the view hierarchy.
10295     * ViewGroups should override to route to their children.
10296     * @param changedView The view whose visibility changed. Could be 'this' or
10297     * an ancestor view.
10298     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10299     * {@link #INVISIBLE} or {@link #GONE}.
10300     */
10301    protected void dispatchVisibilityChanged(@NonNull View changedView,
10302            @Visibility int visibility) {
10303        onVisibilityChanged(changedView, visibility);
10304    }
10305
10306    /**
10307     * Called when the visibility of the view or an ancestor of the view has
10308     * changed.
10309     *
10310     * @param changedView The view whose visibility changed. May be
10311     *                    {@code this} or an ancestor view.
10312     * @param visibility The new visibility, one of {@link #VISIBLE},
10313     *                   {@link #INVISIBLE} or {@link #GONE}.
10314     */
10315    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10316    }
10317
10318    /**
10319     * Dispatch a hint about whether this view is displayed. For instance, when
10320     * a View moves out of the screen, it might receives a display hint indicating
10321     * the view is not displayed. Applications should not <em>rely</em> on this hint
10322     * as there is no guarantee that they will receive one.
10323     *
10324     * @param hint A hint about whether or not this view is displayed:
10325     * {@link #VISIBLE} or {@link #INVISIBLE}.
10326     */
10327    public void dispatchDisplayHint(@Visibility int hint) {
10328        onDisplayHint(hint);
10329    }
10330
10331    /**
10332     * Gives this view a hint about whether is displayed or not. For instance, when
10333     * a View moves out of the screen, it might receives a display hint indicating
10334     * the view is not displayed. Applications should not <em>rely</em> on this hint
10335     * as there is no guarantee that they will receive one.
10336     *
10337     * @param hint A hint about whether or not this view is displayed:
10338     * {@link #VISIBLE} or {@link #INVISIBLE}.
10339     */
10340    protected void onDisplayHint(@Visibility int hint) {
10341    }
10342
10343    /**
10344     * Dispatch a window visibility change down the view hierarchy.
10345     * ViewGroups should override to route to their children.
10346     *
10347     * @param visibility The new visibility of the window.
10348     *
10349     * @see #onWindowVisibilityChanged(int)
10350     */
10351    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10352        onWindowVisibilityChanged(visibility);
10353    }
10354
10355    /**
10356     * Called when the window containing has change its visibility
10357     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10358     * that this tells you whether or not your window is being made visible
10359     * to the window manager; this does <em>not</em> tell you whether or not
10360     * your window is obscured by other windows on the screen, even if it
10361     * is itself visible.
10362     *
10363     * @param visibility The new visibility of the window.
10364     */
10365    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10366        if (visibility == VISIBLE) {
10367            initialAwakenScrollBars();
10368        }
10369    }
10370
10371    /**
10372     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10373     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10374     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10375     *
10376     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10377     *                  ancestors or by window visibility
10378     * @return true if this view is visible to the user, not counting clipping or overlapping
10379     */
10380    @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) {
10381        final boolean thisVisible = getVisibility() == VISIBLE;
10382        // If we're not visible but something is telling us we are, ignore it.
10383        if (thisVisible || !isVisible) {
10384            onVisibilityAggregated(isVisible);
10385        }
10386        return thisVisible && isVisible;
10387    }
10388
10389    /**
10390     * Called when the user-visibility of this View is potentially affected by a change
10391     * to this view itself, an ancestor view or the window this view is attached to.
10392     *
10393     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10394     *                  and this view's window is also visible
10395     */
10396    @CallSuper
10397    public void onVisibilityAggregated(boolean isVisible) {
10398        if (isVisible && mAttachInfo != null) {
10399            initialAwakenScrollBars();
10400        }
10401
10402        final Drawable dr = mBackground;
10403        if (dr != null && isVisible != dr.isVisible()) {
10404            dr.setVisible(isVisible, false);
10405        }
10406        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10407        if (fg != null && isVisible != fg.isVisible()) {
10408            fg.setVisible(isVisible, false);
10409        }
10410    }
10411
10412    /**
10413     * Returns the current visibility of the window this view is attached to
10414     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10415     *
10416     * @return Returns the current visibility of the view's window.
10417     */
10418    @Visibility
10419    public int getWindowVisibility() {
10420        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10421    }
10422
10423    /**
10424     * Retrieve the overall visible display size in which the window this view is
10425     * attached to has been positioned in.  This takes into account screen
10426     * decorations above the window, for both cases where the window itself
10427     * is being position inside of them or the window is being placed under
10428     * then and covered insets are used for the window to position its content
10429     * inside.  In effect, this tells you the available area where content can
10430     * be placed and remain visible to users.
10431     *
10432     * <p>This function requires an IPC back to the window manager to retrieve
10433     * the requested information, so should not be used in performance critical
10434     * code like drawing.
10435     *
10436     * @param outRect Filled in with the visible display frame.  If the view
10437     * is not attached to a window, this is simply the raw display size.
10438     */
10439    public void getWindowVisibleDisplayFrame(Rect outRect) {
10440        if (mAttachInfo != null) {
10441            try {
10442                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10443            } catch (RemoteException e) {
10444                return;
10445            }
10446            // XXX This is really broken, and probably all needs to be done
10447            // in the window manager, and we need to know more about whether
10448            // we want the area behind or in front of the IME.
10449            final Rect insets = mAttachInfo.mVisibleInsets;
10450            outRect.left += insets.left;
10451            outRect.top += insets.top;
10452            outRect.right -= insets.right;
10453            outRect.bottom -= insets.bottom;
10454            return;
10455        }
10456        // The view is not attached to a display so we don't have a context.
10457        // Make a best guess about the display size.
10458        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10459        d.getRectSize(outRect);
10460    }
10461
10462    /**
10463     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10464     * is currently in without any insets.
10465     *
10466     * @hide
10467     */
10468    public void getWindowDisplayFrame(Rect outRect) {
10469        if (mAttachInfo != null) {
10470            try {
10471                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10472            } catch (RemoteException e) {
10473                return;
10474            }
10475            return;
10476        }
10477        // The view is not attached to a display so we don't have a context.
10478        // Make a best guess about the display size.
10479        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10480        d.getRectSize(outRect);
10481    }
10482
10483    /**
10484     * Dispatch a notification about a resource configuration change down
10485     * the view hierarchy.
10486     * ViewGroups should override to route to their children.
10487     *
10488     * @param newConfig The new resource configuration.
10489     *
10490     * @see #onConfigurationChanged(android.content.res.Configuration)
10491     */
10492    public void dispatchConfigurationChanged(Configuration newConfig) {
10493        onConfigurationChanged(newConfig);
10494    }
10495
10496    /**
10497     * Called when the current configuration of the resources being used
10498     * by the application have changed.  You can use this to decide when
10499     * to reload resources that can changed based on orientation and other
10500     * configuration characteristics.  You only need to use this if you are
10501     * not relying on the normal {@link android.app.Activity} mechanism of
10502     * recreating the activity instance upon a configuration change.
10503     *
10504     * @param newConfig The new resource configuration.
10505     */
10506    protected void onConfigurationChanged(Configuration newConfig) {
10507    }
10508
10509    /**
10510     * Private function to aggregate all per-view attributes in to the view
10511     * root.
10512     */
10513    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10514        performCollectViewAttributes(attachInfo, visibility);
10515    }
10516
10517    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10518        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10519            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10520                attachInfo.mKeepScreenOn = true;
10521            }
10522            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10523            ListenerInfo li = mListenerInfo;
10524            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10525                attachInfo.mHasSystemUiListeners = true;
10526            }
10527        }
10528    }
10529
10530    void needGlobalAttributesUpdate(boolean force) {
10531        final AttachInfo ai = mAttachInfo;
10532        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10533            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10534                    || ai.mHasSystemUiListeners) {
10535                ai.mRecomputeGlobalAttributes = true;
10536            }
10537        }
10538    }
10539
10540    /**
10541     * Returns whether the device is currently in touch mode.  Touch mode is entered
10542     * once the user begins interacting with the device by touch, and affects various
10543     * things like whether focus is always visible to the user.
10544     *
10545     * @return Whether the device is in touch mode.
10546     */
10547    @ViewDebug.ExportedProperty
10548    public boolean isInTouchMode() {
10549        if (mAttachInfo != null) {
10550            return mAttachInfo.mInTouchMode;
10551        } else {
10552            return ViewRootImpl.isInTouchMode();
10553        }
10554    }
10555
10556    /**
10557     * Returns the context the view is running in, through which it can
10558     * access the current theme, resources, etc.
10559     *
10560     * @return The view's Context.
10561     */
10562    @ViewDebug.CapturedViewProperty
10563    public final Context getContext() {
10564        return mContext;
10565    }
10566
10567    /**
10568     * Handle a key event before it is processed by any input method
10569     * associated with the view hierarchy.  This can be used to intercept
10570     * key events in special situations before the IME consumes them; a
10571     * typical example would be handling the BACK key to update the application's
10572     * UI instead of allowing the IME to see it and close itself.
10573     *
10574     * @param keyCode The value in event.getKeyCode().
10575     * @param event Description of the key event.
10576     * @return If you handled the event, return true. If you want to allow the
10577     *         event to be handled by the next receiver, return false.
10578     */
10579    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10580        return false;
10581    }
10582
10583    /**
10584     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10585     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10586     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10587     * is released, if the view is enabled and clickable.
10588     * <p>
10589     * Key presses in software keyboards will generally NOT trigger this
10590     * listener, although some may elect to do so in some situations. Do not
10591     * rely on this to catch software key presses.
10592     *
10593     * @param keyCode a key code that represents the button pressed, from
10594     *                {@link android.view.KeyEvent}
10595     * @param event the KeyEvent object that defines the button action
10596     */
10597    public boolean onKeyDown(int keyCode, KeyEvent event) {
10598        if (KeyEvent.isConfirmKey(keyCode)) {
10599            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10600                return true;
10601            }
10602
10603            // Long clickable items don't necessarily have to be clickable.
10604            if (((mViewFlags & CLICKABLE) == CLICKABLE
10605                    || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10606                    && (event.getRepeatCount() == 0)) {
10607                // For the purposes of menu anchoring and drawable hotspots,
10608                // key events are considered to be at the center of the view.
10609                final float x = getWidth() / 2f;
10610                final float y = getHeight() / 2f;
10611                setPressed(true, x, y);
10612                checkForLongClick(0, x, y);
10613                return true;
10614            }
10615        }
10616
10617        return false;
10618    }
10619
10620    /**
10621     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10622     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10623     * the event).
10624     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10625     * although some may elect to do so in some situations. Do not rely on this to
10626     * catch software key presses.
10627     */
10628    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10629        return false;
10630    }
10631
10632    /**
10633     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10634     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10635     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
10636     * or {@link KeyEvent#KEYCODE_SPACE} is released.
10637     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10638     * although some may elect to do so in some situations. Do not rely on this to
10639     * catch software key presses.
10640     *
10641     * @param keyCode A key code that represents the button pressed, from
10642     *                {@link android.view.KeyEvent}.
10643     * @param event   The KeyEvent object that defines the button action.
10644     */
10645    public boolean onKeyUp(int keyCode, KeyEvent event) {
10646        if (KeyEvent.isConfirmKey(keyCode)) {
10647            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10648                return true;
10649            }
10650            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
10651                setPressed(false);
10652
10653                if (!mHasPerformedLongPress) {
10654                    // This is a tap, so remove the longpress check
10655                    removeLongPressCallback();
10656                    return performClick();
10657                }
10658            }
10659        }
10660        return false;
10661    }
10662
10663    /**
10664     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
10665     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
10666     * the event).
10667     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10668     * although some may elect to do so in some situations. Do not rely on this to
10669     * catch software key presses.
10670     *
10671     * @param keyCode     A key code that represents the button pressed, from
10672     *                    {@link android.view.KeyEvent}.
10673     * @param repeatCount The number of times the action was made.
10674     * @param event       The KeyEvent object that defines the button action.
10675     */
10676    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
10677        return false;
10678    }
10679
10680    /**
10681     * Called on the focused view when a key shortcut event is not handled.
10682     * Override this method to implement local key shortcuts for the View.
10683     * Key shortcuts can also be implemented by setting the
10684     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
10685     *
10686     * @param keyCode The value in event.getKeyCode().
10687     * @param event Description of the key event.
10688     * @return If you handled the event, return true. If you want to allow the
10689     *         event to be handled by the next receiver, return false.
10690     */
10691    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
10692        return false;
10693    }
10694
10695    /**
10696     * Check whether the called view is a text editor, in which case it
10697     * would make sense to automatically display a soft input window for
10698     * it.  Subclasses should override this if they implement
10699     * {@link #onCreateInputConnection(EditorInfo)} to return true if
10700     * a call on that method would return a non-null InputConnection, and
10701     * they are really a first-class editor that the user would normally
10702     * start typing on when the go into a window containing your view.
10703     *
10704     * <p>The default implementation always returns false.  This does
10705     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
10706     * will not be called or the user can not otherwise perform edits on your
10707     * view; it is just a hint to the system that this is not the primary
10708     * purpose of this view.
10709     *
10710     * @return Returns true if this view is a text editor, else false.
10711     */
10712    public boolean onCheckIsTextEditor() {
10713        return false;
10714    }
10715
10716    /**
10717     * Create a new InputConnection for an InputMethod to interact
10718     * with the view.  The default implementation returns null, since it doesn't
10719     * support input methods.  You can override this to implement such support.
10720     * This is only needed for views that take focus and text input.
10721     *
10722     * <p>When implementing this, you probably also want to implement
10723     * {@link #onCheckIsTextEditor()} to indicate you will return a
10724     * non-null InputConnection.</p>
10725     *
10726     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
10727     * object correctly and in its entirety, so that the connected IME can rely
10728     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
10729     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
10730     * must be filled in with the correct cursor position for IMEs to work correctly
10731     * with your application.</p>
10732     *
10733     * @param outAttrs Fill in with attribute information about the connection.
10734     */
10735    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
10736        return null;
10737    }
10738
10739    /**
10740     * Called by the {@link android.view.inputmethod.InputMethodManager}
10741     * when a view who is not the current
10742     * input connection target is trying to make a call on the manager.  The
10743     * default implementation returns false; you can override this to return
10744     * true for certain views if you are performing InputConnection proxying
10745     * to them.
10746     * @param view The View that is making the InputMethodManager call.
10747     * @return Return true to allow the call, false to reject.
10748     */
10749    public boolean checkInputConnectionProxy(View view) {
10750        return false;
10751    }
10752
10753    /**
10754     * Show the context menu for this view. It is not safe to hold on to the
10755     * menu after returning from this method.
10756     *
10757     * You should normally not overload this method. Overload
10758     * {@link #onCreateContextMenu(ContextMenu)} or define an
10759     * {@link OnCreateContextMenuListener} to add items to the context menu.
10760     *
10761     * @param menu The context menu to populate
10762     */
10763    public void createContextMenu(ContextMenu menu) {
10764        ContextMenuInfo menuInfo = getContextMenuInfo();
10765
10766        // Sets the current menu info so all items added to menu will have
10767        // my extra info set.
10768        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10769
10770        onCreateContextMenu(menu);
10771        ListenerInfo li = mListenerInfo;
10772        if (li != null && li.mOnCreateContextMenuListener != null) {
10773            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10774        }
10775
10776        // Clear the extra information so subsequent items that aren't mine don't
10777        // have my extra info.
10778        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10779
10780        if (mParent != null) {
10781            mParent.createContextMenu(menu);
10782        }
10783    }
10784
10785    /**
10786     * Views should implement this if they have extra information to associate
10787     * with the context menu. The return result is supplied as a parameter to
10788     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10789     * callback.
10790     *
10791     * @return Extra information about the item for which the context menu
10792     *         should be shown. This information will vary across different
10793     *         subclasses of View.
10794     */
10795    protected ContextMenuInfo getContextMenuInfo() {
10796        return null;
10797    }
10798
10799    /**
10800     * Views should implement this if the view itself is going to add items to
10801     * the context menu.
10802     *
10803     * @param menu the context menu to populate
10804     */
10805    protected void onCreateContextMenu(ContextMenu menu) {
10806    }
10807
10808    /**
10809     * Implement this method to handle trackball motion events.  The
10810     * <em>relative</em> movement of the trackball since the last event
10811     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10812     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10813     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10814     * they will often be fractional values, representing the more fine-grained
10815     * movement information available from a trackball).
10816     *
10817     * @param event The motion event.
10818     * @return True if the event was handled, false otherwise.
10819     */
10820    public boolean onTrackballEvent(MotionEvent event) {
10821        return false;
10822    }
10823
10824    /**
10825     * Implement this method to handle generic motion events.
10826     * <p>
10827     * Generic motion events describe joystick movements, mouse hovers, track pad
10828     * touches, scroll wheel movements and other input events.  The
10829     * {@link MotionEvent#getSource() source} of the motion event specifies
10830     * the class of input that was received.  Implementations of this method
10831     * must examine the bits in the source before processing the event.
10832     * The following code example shows how this is done.
10833     * </p><p>
10834     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10835     * are delivered to the view under the pointer.  All other generic motion events are
10836     * delivered to the focused view.
10837     * </p>
10838     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10839     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10840     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10841     *             // process the joystick movement...
10842     *             return true;
10843     *         }
10844     *     }
10845     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10846     *         switch (event.getAction()) {
10847     *             case MotionEvent.ACTION_HOVER_MOVE:
10848     *                 // process the mouse hover movement...
10849     *                 return true;
10850     *             case MotionEvent.ACTION_SCROLL:
10851     *                 // process the scroll wheel movement...
10852     *                 return true;
10853     *         }
10854     *     }
10855     *     return super.onGenericMotionEvent(event);
10856     * }</pre>
10857     *
10858     * @param event The generic motion event being processed.
10859     * @return True if the event was handled, false otherwise.
10860     */
10861    public boolean onGenericMotionEvent(MotionEvent event) {
10862        return false;
10863    }
10864
10865    /**
10866     * Implement this method to handle hover events.
10867     * <p>
10868     * This method is called whenever a pointer is hovering into, over, or out of the
10869     * bounds of a view and the view is not currently being touched.
10870     * Hover events are represented as pointer events with action
10871     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10872     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10873     * </p>
10874     * <ul>
10875     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10876     * when the pointer enters the bounds of the view.</li>
10877     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10878     * when the pointer has already entered the bounds of the view and has moved.</li>
10879     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10880     * when the pointer has exited the bounds of the view or when the pointer is
10881     * about to go down due to a button click, tap, or similar user action that
10882     * causes the view to be touched.</li>
10883     * </ul>
10884     * <p>
10885     * The view should implement this method to return true to indicate that it is
10886     * handling the hover event, such as by changing its drawable state.
10887     * </p><p>
10888     * The default implementation calls {@link #setHovered} to update the hovered state
10889     * of the view when a hover enter or hover exit event is received, if the view
10890     * is enabled and is clickable.  The default implementation also sends hover
10891     * accessibility events.
10892     * </p>
10893     *
10894     * @param event The motion event that describes the hover.
10895     * @return True if the view handled the hover event.
10896     *
10897     * @see #isHovered
10898     * @see #setHovered
10899     * @see #onHoverChanged
10900     */
10901    public boolean onHoverEvent(MotionEvent event) {
10902        // The root view may receive hover (or touch) events that are outside the bounds of
10903        // the window.  This code ensures that we only send accessibility events for
10904        // hovers that are actually within the bounds of the root view.
10905        final int action = event.getActionMasked();
10906        if (!mSendingHoverAccessibilityEvents) {
10907            if ((action == MotionEvent.ACTION_HOVER_ENTER
10908                    || action == MotionEvent.ACTION_HOVER_MOVE)
10909                    && !hasHoveredChild()
10910                    && pointInView(event.getX(), event.getY())) {
10911                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10912                mSendingHoverAccessibilityEvents = true;
10913            }
10914        } else {
10915            if (action == MotionEvent.ACTION_HOVER_EXIT
10916                    || (action == MotionEvent.ACTION_MOVE
10917                            && !pointInView(event.getX(), event.getY()))) {
10918                mSendingHoverAccessibilityEvents = false;
10919                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10920            }
10921        }
10922
10923        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
10924                && event.isFromSource(InputDevice.SOURCE_MOUSE)
10925                && isOnScrollbar(event.getX(), event.getY())) {
10926            awakenScrollBars();
10927        }
10928        if (isHoverable()) {
10929            switch (action) {
10930                case MotionEvent.ACTION_HOVER_ENTER:
10931                    setHovered(true);
10932                    break;
10933                case MotionEvent.ACTION_HOVER_EXIT:
10934                    setHovered(false);
10935                    break;
10936            }
10937
10938            // Dispatch the event to onGenericMotionEvent before returning true.
10939            // This is to provide compatibility with existing applications that
10940            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10941            // break because of the new default handling for hoverable views
10942            // in onHoverEvent.
10943            // Note that onGenericMotionEvent will be called by default when
10944            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10945            dispatchGenericMotionEventInternal(event);
10946            // The event was already handled by calling setHovered(), so always
10947            // return true.
10948            return true;
10949        }
10950
10951        return false;
10952    }
10953
10954    /**
10955     * Returns true if the view should handle {@link #onHoverEvent}
10956     * by calling {@link #setHovered} to change its hovered state.
10957     *
10958     * @return True if the view is hoverable.
10959     */
10960    private boolean isHoverable() {
10961        final int viewFlags = mViewFlags;
10962        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10963            return false;
10964        }
10965
10966        return (viewFlags & CLICKABLE) == CLICKABLE
10967                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10968                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10969    }
10970
10971    /**
10972     * Returns true if the view is currently hovered.
10973     *
10974     * @return True if the view is currently hovered.
10975     *
10976     * @see #setHovered
10977     * @see #onHoverChanged
10978     */
10979    @ViewDebug.ExportedProperty
10980    public boolean isHovered() {
10981        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10982    }
10983
10984    /**
10985     * Sets whether the view is currently hovered.
10986     * <p>
10987     * Calling this method also changes the drawable state of the view.  This
10988     * enables the view to react to hover by using different drawable resources
10989     * to change its appearance.
10990     * </p><p>
10991     * The {@link #onHoverChanged} method is called when the hovered state changes.
10992     * </p>
10993     *
10994     * @param hovered True if the view is hovered.
10995     *
10996     * @see #isHovered
10997     * @see #onHoverChanged
10998     */
10999    public void setHovered(boolean hovered) {
11000        if (hovered) {
11001            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
11002                mPrivateFlags |= PFLAG_HOVERED;
11003                refreshDrawableState();
11004                onHoverChanged(true);
11005            }
11006        } else {
11007            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
11008                mPrivateFlags &= ~PFLAG_HOVERED;
11009                refreshDrawableState();
11010                onHoverChanged(false);
11011            }
11012        }
11013    }
11014
11015    /**
11016     * Implement this method to handle hover state changes.
11017     * <p>
11018     * This method is called whenever the hover state changes as a result of a
11019     * call to {@link #setHovered}.
11020     * </p>
11021     *
11022     * @param hovered The current hover state, as returned by {@link #isHovered}.
11023     *
11024     * @see #isHovered
11025     * @see #setHovered
11026     */
11027    public void onHoverChanged(boolean hovered) {
11028    }
11029
11030    /**
11031     * Handles scroll bar dragging by mouse input.
11032     *
11033     * @hide
11034     * @param event The motion event.
11035     *
11036     * @return true if the event was handled as a scroll bar dragging, false otherwise.
11037     */
11038    protected boolean handleScrollBarDragging(MotionEvent event) {
11039        if (mScrollCache == null) {
11040            return false;
11041        }
11042        final float x = event.getX();
11043        final float y = event.getY();
11044        final int action = event.getAction();
11045        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
11046                && action != MotionEvent.ACTION_DOWN)
11047                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
11048                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
11049            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11050            return false;
11051        }
11052
11053        switch (action) {
11054            case MotionEvent.ACTION_MOVE:
11055                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
11056                    return false;
11057                }
11058                if (mScrollCache.mScrollBarDraggingState
11059                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
11060                    final Rect bounds = mScrollCache.mScrollBarBounds;
11061                    getVerticalScrollBarBounds(bounds);
11062                    final int range = computeVerticalScrollRange();
11063                    final int offset = computeVerticalScrollOffset();
11064                    final int extent = computeVerticalScrollExtent();
11065
11066                    final int thumbLength = ScrollBarUtils.getThumbLength(
11067                            bounds.height(), bounds.width(), extent, range);
11068                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11069                            bounds.height(), thumbLength, extent, range, offset);
11070
11071                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
11072                    final float maxThumbOffset = bounds.height() - thumbLength;
11073                    final float newThumbOffset =
11074                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11075                    final int height = getHeight();
11076                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11077                            && height > 0 && extent > 0) {
11078                        final int newY = Math.round((range - extent)
11079                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11080                        if (newY != getScrollY()) {
11081                            mScrollCache.mScrollBarDraggingPos = y;
11082                            setScrollY(newY);
11083                        }
11084                    }
11085                    return true;
11086                }
11087                if (mScrollCache.mScrollBarDraggingState
11088                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11089                    final Rect bounds = mScrollCache.mScrollBarBounds;
11090                    getHorizontalScrollBarBounds(bounds);
11091                    final int range = computeHorizontalScrollRange();
11092                    final int offset = computeHorizontalScrollOffset();
11093                    final int extent = computeHorizontalScrollExtent();
11094
11095                    final int thumbLength = ScrollBarUtils.getThumbLength(
11096                            bounds.width(), bounds.height(), extent, range);
11097                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11098                            bounds.width(), thumbLength, extent, range, offset);
11099
11100                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11101                    final float maxThumbOffset = bounds.width() - thumbLength;
11102                    final float newThumbOffset =
11103                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11104                    final int width = getWidth();
11105                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11106                            && width > 0 && extent > 0) {
11107                        final int newX = Math.round((range - extent)
11108                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11109                        if (newX != getScrollX()) {
11110                            mScrollCache.mScrollBarDraggingPos = x;
11111                            setScrollX(newX);
11112                        }
11113                    }
11114                    return true;
11115                }
11116            case MotionEvent.ACTION_DOWN:
11117                if (mScrollCache.state == ScrollabilityCache.OFF) {
11118                    return false;
11119                }
11120                if (isOnVerticalScrollbarThumb(x, y)) {
11121                    mScrollCache.mScrollBarDraggingState =
11122                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11123                    mScrollCache.mScrollBarDraggingPos = y;
11124                    return true;
11125                }
11126                if (isOnHorizontalScrollbarThumb(x, y)) {
11127                    mScrollCache.mScrollBarDraggingState =
11128                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11129                    mScrollCache.mScrollBarDraggingPos = x;
11130                    return true;
11131                }
11132        }
11133        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11134        return false;
11135    }
11136
11137    /**
11138     * Implement this method to handle touch screen motion events.
11139     * <p>
11140     * If this method is used to detect click actions, it is recommended that
11141     * the actions be performed by implementing and calling
11142     * {@link #performClick()}. This will ensure consistent system behavior,
11143     * including:
11144     * <ul>
11145     * <li>obeying click sound preferences
11146     * <li>dispatching OnClickListener calls
11147     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11148     * accessibility features are enabled
11149     * </ul>
11150     *
11151     * @param event The motion event.
11152     * @return True if the event was handled, false otherwise.
11153     */
11154    public boolean onTouchEvent(MotionEvent event) {
11155        final float x = event.getX();
11156        final float y = event.getY();
11157        final int viewFlags = mViewFlags;
11158        final int action = event.getAction();
11159
11160        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11161            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11162                setPressed(false);
11163            }
11164            // A disabled view that is clickable still consumes the touch
11165            // events, it just doesn't respond to them.
11166            return (((viewFlags & CLICKABLE) == CLICKABLE
11167                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11168                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
11169        }
11170        if (mTouchDelegate != null) {
11171            if (mTouchDelegate.onTouchEvent(event)) {
11172                return true;
11173            }
11174        }
11175
11176        if (((viewFlags & CLICKABLE) == CLICKABLE ||
11177                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
11178                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
11179            switch (action) {
11180                case MotionEvent.ACTION_UP:
11181                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11182                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11183                        // take focus if we don't have it already and we should in
11184                        // touch mode.
11185                        boolean focusTaken = false;
11186                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11187                            focusTaken = requestFocus();
11188                        }
11189
11190                        if (prepressed) {
11191                            // The button is being released before we actually
11192                            // showed it as pressed.  Make it show the pressed
11193                            // state now (before scheduling the click) to ensure
11194                            // the user sees it.
11195                            setPressed(true, x, y);
11196                       }
11197
11198                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11199                            // This is a tap, so remove the longpress check
11200                            removeLongPressCallback();
11201
11202                            // Only perform take click actions if we were in the pressed state
11203                            if (!focusTaken) {
11204                                // Use a Runnable and post this rather than calling
11205                                // performClick directly. This lets other visual state
11206                                // of the view update before click actions start.
11207                                if (mPerformClick == null) {
11208                                    mPerformClick = new PerformClick();
11209                                }
11210                                if (!post(mPerformClick)) {
11211                                    performClick();
11212                                }
11213                            }
11214                        }
11215
11216                        if (mUnsetPressedState == null) {
11217                            mUnsetPressedState = new UnsetPressedState();
11218                        }
11219
11220                        if (prepressed) {
11221                            postDelayed(mUnsetPressedState,
11222                                    ViewConfiguration.getPressedStateDuration());
11223                        } else if (!post(mUnsetPressedState)) {
11224                            // If the post failed, unpress right now
11225                            mUnsetPressedState.run();
11226                        }
11227
11228                        removeTapCallback();
11229                    }
11230                    mIgnoreNextUpEvent = false;
11231                    break;
11232
11233                case MotionEvent.ACTION_DOWN:
11234                    mHasPerformedLongPress = false;
11235
11236                    if (performButtonActionOnTouchDown(event)) {
11237                        break;
11238                    }
11239
11240                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11241                    boolean isInScrollingContainer = isInScrollingContainer();
11242
11243                    // For views inside a scrolling container, delay the pressed feedback for
11244                    // a short period in case this is a scroll.
11245                    if (isInScrollingContainer) {
11246                        mPrivateFlags |= PFLAG_PREPRESSED;
11247                        if (mPendingCheckForTap == null) {
11248                            mPendingCheckForTap = new CheckForTap();
11249                        }
11250                        mPendingCheckForTap.x = event.getX();
11251                        mPendingCheckForTap.y = event.getY();
11252                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11253                    } else {
11254                        // Not inside a scrolling container, so show the feedback right away
11255                        setPressed(true, x, y);
11256                        checkForLongClick(0, x, y);
11257                    }
11258                    break;
11259
11260                case MotionEvent.ACTION_CANCEL:
11261                    setPressed(false);
11262                    removeTapCallback();
11263                    removeLongPressCallback();
11264                    mInContextButtonPress = false;
11265                    mHasPerformedLongPress = false;
11266                    mIgnoreNextUpEvent = false;
11267                    break;
11268
11269                case MotionEvent.ACTION_MOVE:
11270                    drawableHotspotChanged(x, y);
11271
11272                    // Be lenient about moving outside of buttons
11273                    if (!pointInView(x, y, mTouchSlop)) {
11274                        // Outside button
11275                        removeTapCallback();
11276                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11277                            // Remove any future long press/tap checks
11278                            removeLongPressCallback();
11279
11280                            setPressed(false);
11281                        }
11282                    }
11283                    break;
11284            }
11285
11286            return true;
11287        }
11288
11289        return false;
11290    }
11291
11292    /**
11293     * @hide
11294     */
11295    public boolean isInScrollingContainer() {
11296        ViewParent p = getParent();
11297        while (p != null && p instanceof ViewGroup) {
11298            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11299                return true;
11300            }
11301            p = p.getParent();
11302        }
11303        return false;
11304    }
11305
11306    /**
11307     * Remove the longpress detection timer.
11308     */
11309    private void removeLongPressCallback() {
11310        if (mPendingCheckForLongPress != null) {
11311          removeCallbacks(mPendingCheckForLongPress);
11312        }
11313    }
11314
11315    /**
11316     * Remove the pending click action
11317     */
11318    private void removePerformClickCallback() {
11319        if (mPerformClick != null) {
11320            removeCallbacks(mPerformClick);
11321        }
11322    }
11323
11324    /**
11325     * Remove the prepress detection timer.
11326     */
11327    private void removeUnsetPressCallback() {
11328        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11329            setPressed(false);
11330            removeCallbacks(mUnsetPressedState);
11331        }
11332    }
11333
11334    /**
11335     * Remove the tap detection timer.
11336     */
11337    private void removeTapCallback() {
11338        if (mPendingCheckForTap != null) {
11339            mPrivateFlags &= ~PFLAG_PREPRESSED;
11340            removeCallbacks(mPendingCheckForTap);
11341        }
11342    }
11343
11344    /**
11345     * Cancels a pending long press.  Your subclass can use this if you
11346     * want the context menu to come up if the user presses and holds
11347     * at the same place, but you don't want it to come up if they press
11348     * and then move around enough to cause scrolling.
11349     */
11350    public void cancelLongPress() {
11351        removeLongPressCallback();
11352
11353        /*
11354         * The prepressed state handled by the tap callback is a display
11355         * construct, but the tap callback will post a long press callback
11356         * less its own timeout. Remove it here.
11357         */
11358        removeTapCallback();
11359    }
11360
11361    /**
11362     * Remove the pending callback for sending a
11363     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11364     */
11365    private void removeSendViewScrolledAccessibilityEventCallback() {
11366        if (mSendViewScrolledAccessibilityEvent != null) {
11367            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11368            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11369        }
11370    }
11371
11372    /**
11373     * Sets the TouchDelegate for this View.
11374     */
11375    public void setTouchDelegate(TouchDelegate delegate) {
11376        mTouchDelegate = delegate;
11377    }
11378
11379    /**
11380     * Gets the TouchDelegate for this View.
11381     */
11382    public TouchDelegate getTouchDelegate() {
11383        return mTouchDelegate;
11384    }
11385
11386    /**
11387     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11388     *
11389     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11390     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11391     * available. This method should only be called for touch events.
11392     *
11393     * <p class="note">This api is not intended for most applications. Buffered dispatch
11394     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11395     * streams will not improve your input latency. Side effects include: increased latency,
11396     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11397     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11398     * you.</p>
11399     */
11400    public final void requestUnbufferedDispatch(MotionEvent event) {
11401        final int action = event.getAction();
11402        if (mAttachInfo == null
11403                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11404                || !event.isTouchEvent()) {
11405            return;
11406        }
11407        mAttachInfo.mUnbufferedDispatchRequested = true;
11408    }
11409
11410    /**
11411     * Set flags controlling behavior of this view.
11412     *
11413     * @param flags Constant indicating the value which should be set
11414     * @param mask Constant indicating the bit range that should be changed
11415     */
11416    void setFlags(int flags, int mask) {
11417        final boolean accessibilityEnabled =
11418                AccessibilityManager.getInstance(mContext).isEnabled();
11419        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11420
11421        int old = mViewFlags;
11422        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11423
11424        int changed = mViewFlags ^ old;
11425        if (changed == 0) {
11426            return;
11427        }
11428        int privateFlags = mPrivateFlags;
11429
11430        /* Check if the FOCUSABLE bit has changed */
11431        if (((changed & FOCUSABLE_MASK) != 0) &&
11432                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11433            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11434                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11435                /* Give up focus if we are no longer focusable */
11436                clearFocus();
11437            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11438                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11439                /*
11440                 * Tell the view system that we are now available to take focus
11441                 * if no one else already has it.
11442                 */
11443                if (mParent != null) mParent.focusableViewAvailable(this);
11444            }
11445        }
11446
11447        final int newVisibility = flags & VISIBILITY_MASK;
11448        if (newVisibility == VISIBLE) {
11449            if ((changed & VISIBILITY_MASK) != 0) {
11450                /*
11451                 * If this view is becoming visible, invalidate it in case it changed while
11452                 * it was not visible. Marking it drawn ensures that the invalidation will
11453                 * go through.
11454                 */
11455                mPrivateFlags |= PFLAG_DRAWN;
11456                invalidate(true);
11457
11458                needGlobalAttributesUpdate(true);
11459
11460                // a view becoming visible is worth notifying the parent
11461                // about in case nothing has focus.  even if this specific view
11462                // isn't focusable, it may contain something that is, so let
11463                // the root view try to give this focus if nothing else does.
11464                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11465                    mParent.focusableViewAvailable(this);
11466                }
11467            }
11468        }
11469
11470        /* Check if the GONE bit has changed */
11471        if ((changed & GONE) != 0) {
11472            needGlobalAttributesUpdate(false);
11473            requestLayout();
11474
11475            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11476                if (hasFocus()) clearFocus();
11477                clearAccessibilityFocus();
11478                destroyDrawingCache();
11479                if (mParent instanceof View) {
11480                    // GONE views noop invalidation, so invalidate the parent
11481                    ((View) mParent).invalidate(true);
11482                }
11483                // Mark the view drawn to ensure that it gets invalidated properly the next
11484                // time it is visible and gets invalidated
11485                mPrivateFlags |= PFLAG_DRAWN;
11486            }
11487            if (mAttachInfo != null) {
11488                mAttachInfo.mViewVisibilityChanged = true;
11489            }
11490        }
11491
11492        /* Check if the VISIBLE bit has changed */
11493        if ((changed & INVISIBLE) != 0) {
11494            needGlobalAttributesUpdate(false);
11495            /*
11496             * If this view is becoming invisible, set the DRAWN flag so that
11497             * the next invalidate() will not be skipped.
11498             */
11499            mPrivateFlags |= PFLAG_DRAWN;
11500
11501            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11502                // root view becoming invisible shouldn't clear focus and accessibility focus
11503                if (getRootView() != this) {
11504                    if (hasFocus()) clearFocus();
11505                    clearAccessibilityFocus();
11506                }
11507            }
11508            if (mAttachInfo != null) {
11509                mAttachInfo.mViewVisibilityChanged = true;
11510            }
11511        }
11512
11513        if ((changed & VISIBILITY_MASK) != 0) {
11514            // If the view is invisible, cleanup its display list to free up resources
11515            if (newVisibility != VISIBLE && mAttachInfo != null) {
11516                cleanupDraw();
11517            }
11518
11519            if (mParent instanceof ViewGroup) {
11520                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11521                        (changed & VISIBILITY_MASK), newVisibility);
11522                ((View) mParent).invalidate(true);
11523            } else if (mParent != null) {
11524                mParent.invalidateChild(this, null);
11525            }
11526
11527            if (mAttachInfo != null) {
11528                dispatchVisibilityChanged(this, newVisibility);
11529
11530                // Aggregated visibility changes are dispatched to attached views
11531                // in visible windows where the parent is currently shown/drawn
11532                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11533                // discounting clipping or overlapping. This makes it a good place
11534                // to change animation states.
11535                if (mParent != null && getWindowVisibility() == VISIBLE &&
11536                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11537                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11538                }
11539                notifySubtreeAccessibilityStateChangedIfNeeded();
11540            }
11541        }
11542
11543        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11544            destroyDrawingCache();
11545        }
11546
11547        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11548            destroyDrawingCache();
11549            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11550            invalidateParentCaches();
11551        }
11552
11553        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11554            destroyDrawingCache();
11555            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11556        }
11557
11558        if ((changed & DRAW_MASK) != 0) {
11559            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11560                if (mBackground != null
11561                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11562                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11563                } else {
11564                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11565                }
11566            } else {
11567                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11568            }
11569            requestLayout();
11570            invalidate(true);
11571        }
11572
11573        if ((changed & KEEP_SCREEN_ON) != 0) {
11574            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11575                mParent.recomputeViewAttributes(this);
11576            }
11577        }
11578
11579        if (accessibilityEnabled) {
11580            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11581                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11582                    || (changed & CONTEXT_CLICKABLE) != 0) {
11583                if (oldIncludeForAccessibility != includeForAccessibility()) {
11584                    notifySubtreeAccessibilityStateChangedIfNeeded();
11585                } else {
11586                    notifyViewAccessibilityStateChangedIfNeeded(
11587                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11588                }
11589            } else if ((changed & ENABLED_MASK) != 0) {
11590                notifyViewAccessibilityStateChangedIfNeeded(
11591                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11592            }
11593        }
11594    }
11595
11596    /**
11597     * Change the view's z order in the tree, so it's on top of other sibling
11598     * views. This ordering change may affect layout, if the parent container
11599     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11600     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11601     * method should be followed by calls to {@link #requestLayout()} and
11602     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11603     * with the new child ordering.
11604     *
11605     * @see ViewGroup#bringChildToFront(View)
11606     */
11607    public void bringToFront() {
11608        if (mParent != null) {
11609            mParent.bringChildToFront(this);
11610        }
11611    }
11612
11613    /**
11614     * This is called in response to an internal scroll in this view (i.e., the
11615     * view scrolled its own contents). This is typically as a result of
11616     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
11617     * called.
11618     *
11619     * @param l Current horizontal scroll origin.
11620     * @param t Current vertical scroll origin.
11621     * @param oldl Previous horizontal scroll origin.
11622     * @param oldt Previous vertical scroll origin.
11623     */
11624    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
11625        notifySubtreeAccessibilityStateChangedIfNeeded();
11626
11627        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11628            postSendViewScrolledAccessibilityEventCallback();
11629        }
11630
11631        mBackgroundSizeChanged = true;
11632        if (mForegroundInfo != null) {
11633            mForegroundInfo.mBoundsChanged = true;
11634        }
11635
11636        final AttachInfo ai = mAttachInfo;
11637        if (ai != null) {
11638            ai.mViewScrollChanged = true;
11639        }
11640
11641        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
11642            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
11643        }
11644    }
11645
11646    /**
11647     * Interface definition for a callback to be invoked when the scroll
11648     * X or Y positions of a view change.
11649     * <p>
11650     * <b>Note:</b> Some views handle scrolling independently from View and may
11651     * have their own separate listeners for scroll-type events. For example,
11652     * {@link android.widget.ListView ListView} allows clients to register an
11653     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
11654     * to listen for changes in list scroll position.
11655     *
11656     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
11657     */
11658    public interface OnScrollChangeListener {
11659        /**
11660         * Called when the scroll position of a view changes.
11661         *
11662         * @param v The view whose scroll position has changed.
11663         * @param scrollX Current horizontal scroll origin.
11664         * @param scrollY Current vertical scroll origin.
11665         * @param oldScrollX Previous horizontal scroll origin.
11666         * @param oldScrollY Previous vertical scroll origin.
11667         */
11668        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
11669    }
11670
11671    /**
11672     * Interface definition for a callback to be invoked when the layout bounds of a view
11673     * changes due to layout processing.
11674     */
11675    public interface OnLayoutChangeListener {
11676        /**
11677         * Called when the layout bounds of a view changes due to layout processing.
11678         *
11679         * @param v The view whose bounds have changed.
11680         * @param left The new value of the view's left property.
11681         * @param top The new value of the view's top property.
11682         * @param right The new value of the view's right property.
11683         * @param bottom The new value of the view's bottom property.
11684         * @param oldLeft The previous value of the view's left property.
11685         * @param oldTop The previous value of the view's top property.
11686         * @param oldRight The previous value of the view's right property.
11687         * @param oldBottom The previous value of the view's bottom property.
11688         */
11689        void onLayoutChange(View v, int left, int top, int right, int bottom,
11690            int oldLeft, int oldTop, int oldRight, int oldBottom);
11691    }
11692
11693    /**
11694     * This is called during layout when the size of this view has changed. If
11695     * you were just added to the view hierarchy, you're called with the old
11696     * values of 0.
11697     *
11698     * @param w Current width of this view.
11699     * @param h Current height of this view.
11700     * @param oldw Old width of this view.
11701     * @param oldh Old height of this view.
11702     */
11703    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
11704    }
11705
11706    /**
11707     * Called by draw to draw the child views. This may be overridden
11708     * by derived classes to gain control just before its children are drawn
11709     * (but after its own view has been drawn).
11710     * @param canvas the canvas on which to draw the view
11711     */
11712    protected void dispatchDraw(Canvas canvas) {
11713
11714    }
11715
11716    /**
11717     * Gets the parent of this view. Note that the parent is a
11718     * ViewParent and not necessarily a View.
11719     *
11720     * @return Parent of this view.
11721     */
11722    public final ViewParent getParent() {
11723        return mParent;
11724    }
11725
11726    /**
11727     * Set the horizontal scrolled position of your view. This will cause a call to
11728     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11729     * invalidated.
11730     * @param value the x position to scroll to
11731     */
11732    public void setScrollX(int value) {
11733        scrollTo(value, mScrollY);
11734    }
11735
11736    /**
11737     * Set the vertical scrolled position of your view. This will cause a call to
11738     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11739     * invalidated.
11740     * @param value the y position to scroll to
11741     */
11742    public void setScrollY(int value) {
11743        scrollTo(mScrollX, value);
11744    }
11745
11746    /**
11747     * Return the scrolled left position of this view. This is the left edge of
11748     * the displayed part of your view. You do not need to draw any pixels
11749     * farther left, since those are outside of the frame of your view on
11750     * screen.
11751     *
11752     * @return The left edge of the displayed part of your view, in pixels.
11753     */
11754    public final int getScrollX() {
11755        return mScrollX;
11756    }
11757
11758    /**
11759     * Return the scrolled top position of this view. This is the top edge of
11760     * the displayed part of your view. You do not need to draw any pixels above
11761     * it, since those are outside of the frame of your view on screen.
11762     *
11763     * @return The top edge of the displayed part of your view, in pixels.
11764     */
11765    public final int getScrollY() {
11766        return mScrollY;
11767    }
11768
11769    /**
11770     * Return the width of the your view.
11771     *
11772     * @return The width of your view, in pixels.
11773     */
11774    @ViewDebug.ExportedProperty(category = "layout")
11775    public final int getWidth() {
11776        return mRight - mLeft;
11777    }
11778
11779    /**
11780     * Return the height of your view.
11781     *
11782     * @return The height of your view, in pixels.
11783     */
11784    @ViewDebug.ExportedProperty(category = "layout")
11785    public final int getHeight() {
11786        return mBottom - mTop;
11787    }
11788
11789    /**
11790     * Return the visible drawing bounds of your view. Fills in the output
11791     * rectangle with the values from getScrollX(), getScrollY(),
11792     * getWidth(), and getHeight(). These bounds do not account for any
11793     * transformation properties currently set on the view, such as
11794     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
11795     *
11796     * @param outRect The (scrolled) drawing bounds of the view.
11797     */
11798    public void getDrawingRect(Rect outRect) {
11799        outRect.left = mScrollX;
11800        outRect.top = mScrollY;
11801        outRect.right = mScrollX + (mRight - mLeft);
11802        outRect.bottom = mScrollY + (mBottom - mTop);
11803    }
11804
11805    /**
11806     * Like {@link #getMeasuredWidthAndState()}, but only returns the
11807     * raw width component (that is the result is masked by
11808     * {@link #MEASURED_SIZE_MASK}).
11809     *
11810     * @return The raw measured width of this view.
11811     */
11812    public final int getMeasuredWidth() {
11813        return mMeasuredWidth & MEASURED_SIZE_MASK;
11814    }
11815
11816    /**
11817     * Return the full width measurement information for this view as computed
11818     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11819     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11820     * This should be used during measurement and layout calculations only. Use
11821     * {@link #getWidth()} to see how wide a view is after layout.
11822     *
11823     * @return The measured width of this view as a bit mask.
11824     */
11825    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11826            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11827                    name = "MEASURED_STATE_TOO_SMALL"),
11828    })
11829    public final int getMeasuredWidthAndState() {
11830        return mMeasuredWidth;
11831    }
11832
11833    /**
11834     * Like {@link #getMeasuredHeightAndState()}, but only returns the
11835     * raw height component (that is the result is masked by
11836     * {@link #MEASURED_SIZE_MASK}).
11837     *
11838     * @return The raw measured height of this view.
11839     */
11840    public final int getMeasuredHeight() {
11841        return mMeasuredHeight & MEASURED_SIZE_MASK;
11842    }
11843
11844    /**
11845     * Return the full height measurement information for this view as computed
11846     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11847     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11848     * This should be used during measurement and layout calculations only. Use
11849     * {@link #getHeight()} to see how wide a view is after layout.
11850     *
11851     * @return The measured height of this view as a bit mask.
11852     */
11853    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11854            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11855                    name = "MEASURED_STATE_TOO_SMALL"),
11856    })
11857    public final int getMeasuredHeightAndState() {
11858        return mMeasuredHeight;
11859    }
11860
11861    /**
11862     * Return only the state bits of {@link #getMeasuredWidthAndState()}
11863     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
11864     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
11865     * and the height component is at the shifted bits
11866     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
11867     */
11868    public final int getMeasuredState() {
11869        return (mMeasuredWidth&MEASURED_STATE_MASK)
11870                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
11871                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
11872    }
11873
11874    /**
11875     * The transform matrix of this view, which is calculated based on the current
11876     * rotation, scale, and pivot properties.
11877     *
11878     * @see #getRotation()
11879     * @see #getScaleX()
11880     * @see #getScaleY()
11881     * @see #getPivotX()
11882     * @see #getPivotY()
11883     * @return The current transform matrix for the view
11884     */
11885    public Matrix getMatrix() {
11886        ensureTransformationInfo();
11887        final Matrix matrix = mTransformationInfo.mMatrix;
11888        mRenderNode.getMatrix(matrix);
11889        return matrix;
11890    }
11891
11892    /**
11893     * Returns true if the transform matrix is the identity matrix.
11894     * Recomputes the matrix if necessary.
11895     *
11896     * @return True if the transform matrix is the identity matrix, false otherwise.
11897     */
11898    final boolean hasIdentityMatrix() {
11899        return mRenderNode.hasIdentityMatrix();
11900    }
11901
11902    void ensureTransformationInfo() {
11903        if (mTransformationInfo == null) {
11904            mTransformationInfo = new TransformationInfo();
11905        }
11906    }
11907
11908    /**
11909     * Utility method to retrieve the inverse of the current mMatrix property.
11910     * We cache the matrix to avoid recalculating it when transform properties
11911     * have not changed.
11912     *
11913     * @return The inverse of the current matrix of this view.
11914     * @hide
11915     */
11916    public final Matrix getInverseMatrix() {
11917        ensureTransformationInfo();
11918        if (mTransformationInfo.mInverseMatrix == null) {
11919            mTransformationInfo.mInverseMatrix = new Matrix();
11920        }
11921        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11922        mRenderNode.getInverseMatrix(matrix);
11923        return matrix;
11924    }
11925
11926    /**
11927     * Gets the distance along the Z axis from the camera to this view.
11928     *
11929     * @see #setCameraDistance(float)
11930     *
11931     * @return The distance along the Z axis.
11932     */
11933    public float getCameraDistance() {
11934        final float dpi = mResources.getDisplayMetrics().densityDpi;
11935        return -(mRenderNode.getCameraDistance() * dpi);
11936    }
11937
11938    /**
11939     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11940     * views are drawn) from the camera to this view. The camera's distance
11941     * affects 3D transformations, for instance rotations around the X and Y
11942     * axis. If the rotationX or rotationY properties are changed and this view is
11943     * large (more than half the size of the screen), it is recommended to always
11944     * use a camera distance that's greater than the height (X axis rotation) or
11945     * the width (Y axis rotation) of this view.</p>
11946     *
11947     * <p>The distance of the camera from the view plane can have an affect on the
11948     * perspective distortion of the view when it is rotated around the x or y axis.
11949     * For example, a large distance will result in a large viewing angle, and there
11950     * will not be much perspective distortion of the view as it rotates. A short
11951     * distance may cause much more perspective distortion upon rotation, and can
11952     * also result in some drawing artifacts if the rotated view ends up partially
11953     * behind the camera (which is why the recommendation is to use a distance at
11954     * least as far as the size of the view, if the view is to be rotated.)</p>
11955     *
11956     * <p>The distance is expressed in "depth pixels." The default distance depends
11957     * on the screen density. For instance, on a medium density display, the
11958     * default distance is 1280. On a high density display, the default distance
11959     * is 1920.</p>
11960     *
11961     * <p>If you want to specify a distance that leads to visually consistent
11962     * results across various densities, use the following formula:</p>
11963     * <pre>
11964     * float scale = context.getResources().getDisplayMetrics().density;
11965     * view.setCameraDistance(distance * scale);
11966     * </pre>
11967     *
11968     * <p>The density scale factor of a high density display is 1.5,
11969     * and 1920 = 1280 * 1.5.</p>
11970     *
11971     * @param distance The distance in "depth pixels", if negative the opposite
11972     *        value is used
11973     *
11974     * @see #setRotationX(float)
11975     * @see #setRotationY(float)
11976     */
11977    public void setCameraDistance(float distance) {
11978        final float dpi = mResources.getDisplayMetrics().densityDpi;
11979
11980        invalidateViewProperty(true, false);
11981        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11982        invalidateViewProperty(false, false);
11983
11984        invalidateParentIfNeededAndWasQuickRejected();
11985    }
11986
11987    /**
11988     * The degrees that the view is rotated around the pivot point.
11989     *
11990     * @see #setRotation(float)
11991     * @see #getPivotX()
11992     * @see #getPivotY()
11993     *
11994     * @return The degrees of rotation.
11995     */
11996    @ViewDebug.ExportedProperty(category = "drawing")
11997    public float getRotation() {
11998        return mRenderNode.getRotation();
11999    }
12000
12001    /**
12002     * Sets the degrees that the view is rotated around the pivot point. Increasing values
12003     * result in clockwise rotation.
12004     *
12005     * @param rotation The degrees of rotation.
12006     *
12007     * @see #getRotation()
12008     * @see #getPivotX()
12009     * @see #getPivotY()
12010     * @see #setRotationX(float)
12011     * @see #setRotationY(float)
12012     *
12013     * @attr ref android.R.styleable#View_rotation
12014     */
12015    public void setRotation(float rotation) {
12016        if (rotation != getRotation()) {
12017            // Double-invalidation is necessary to capture view's old and new areas
12018            invalidateViewProperty(true, false);
12019            mRenderNode.setRotation(rotation);
12020            invalidateViewProperty(false, true);
12021
12022            invalidateParentIfNeededAndWasQuickRejected();
12023            notifySubtreeAccessibilityStateChangedIfNeeded();
12024        }
12025    }
12026
12027    /**
12028     * The degrees that the view is rotated around the vertical axis through the pivot point.
12029     *
12030     * @see #getPivotX()
12031     * @see #getPivotY()
12032     * @see #setRotationY(float)
12033     *
12034     * @return The degrees of Y rotation.
12035     */
12036    @ViewDebug.ExportedProperty(category = "drawing")
12037    public float getRotationY() {
12038        return mRenderNode.getRotationY();
12039    }
12040
12041    /**
12042     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
12043     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
12044     * down the y axis.
12045     *
12046     * When rotating large views, it is recommended to adjust the camera distance
12047     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12048     *
12049     * @param rotationY The degrees of Y rotation.
12050     *
12051     * @see #getRotationY()
12052     * @see #getPivotX()
12053     * @see #getPivotY()
12054     * @see #setRotation(float)
12055     * @see #setRotationX(float)
12056     * @see #setCameraDistance(float)
12057     *
12058     * @attr ref android.R.styleable#View_rotationY
12059     */
12060    public void setRotationY(float rotationY) {
12061        if (rotationY != getRotationY()) {
12062            invalidateViewProperty(true, false);
12063            mRenderNode.setRotationY(rotationY);
12064            invalidateViewProperty(false, true);
12065
12066            invalidateParentIfNeededAndWasQuickRejected();
12067            notifySubtreeAccessibilityStateChangedIfNeeded();
12068        }
12069    }
12070
12071    /**
12072     * The degrees that the view is rotated around the horizontal axis through the pivot point.
12073     *
12074     * @see #getPivotX()
12075     * @see #getPivotY()
12076     * @see #setRotationX(float)
12077     *
12078     * @return The degrees of X rotation.
12079     */
12080    @ViewDebug.ExportedProperty(category = "drawing")
12081    public float getRotationX() {
12082        return mRenderNode.getRotationX();
12083    }
12084
12085    /**
12086     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12087     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12088     * x axis.
12089     *
12090     * When rotating large views, it is recommended to adjust the camera distance
12091     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12092     *
12093     * @param rotationX The degrees of X rotation.
12094     *
12095     * @see #getRotationX()
12096     * @see #getPivotX()
12097     * @see #getPivotY()
12098     * @see #setRotation(float)
12099     * @see #setRotationY(float)
12100     * @see #setCameraDistance(float)
12101     *
12102     * @attr ref android.R.styleable#View_rotationX
12103     */
12104    public void setRotationX(float rotationX) {
12105        if (rotationX != getRotationX()) {
12106            invalidateViewProperty(true, false);
12107            mRenderNode.setRotationX(rotationX);
12108            invalidateViewProperty(false, true);
12109
12110            invalidateParentIfNeededAndWasQuickRejected();
12111            notifySubtreeAccessibilityStateChangedIfNeeded();
12112        }
12113    }
12114
12115    /**
12116     * The amount that the view is scaled in x around the pivot point, as a proportion of
12117     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12118     *
12119     * <p>By default, this is 1.0f.
12120     *
12121     * @see #getPivotX()
12122     * @see #getPivotY()
12123     * @return The scaling factor.
12124     */
12125    @ViewDebug.ExportedProperty(category = "drawing")
12126    public float getScaleX() {
12127        return mRenderNode.getScaleX();
12128    }
12129
12130    /**
12131     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12132     * the view's unscaled width. A value of 1 means that no scaling is applied.
12133     *
12134     * @param scaleX The scaling factor.
12135     * @see #getPivotX()
12136     * @see #getPivotY()
12137     *
12138     * @attr ref android.R.styleable#View_scaleX
12139     */
12140    public void setScaleX(float scaleX) {
12141        if (scaleX != getScaleX()) {
12142            invalidateViewProperty(true, false);
12143            mRenderNode.setScaleX(scaleX);
12144            invalidateViewProperty(false, true);
12145
12146            invalidateParentIfNeededAndWasQuickRejected();
12147            notifySubtreeAccessibilityStateChangedIfNeeded();
12148        }
12149    }
12150
12151    /**
12152     * The amount that the view is scaled in y around the pivot point, as a proportion of
12153     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12154     *
12155     * <p>By default, this is 1.0f.
12156     *
12157     * @see #getPivotX()
12158     * @see #getPivotY()
12159     * @return The scaling factor.
12160     */
12161    @ViewDebug.ExportedProperty(category = "drawing")
12162    public float getScaleY() {
12163        return mRenderNode.getScaleY();
12164    }
12165
12166    /**
12167     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12168     * the view's unscaled width. A value of 1 means that no scaling is applied.
12169     *
12170     * @param scaleY The scaling factor.
12171     * @see #getPivotX()
12172     * @see #getPivotY()
12173     *
12174     * @attr ref android.R.styleable#View_scaleY
12175     */
12176    public void setScaleY(float scaleY) {
12177        if (scaleY != getScaleY()) {
12178            invalidateViewProperty(true, false);
12179            mRenderNode.setScaleY(scaleY);
12180            invalidateViewProperty(false, true);
12181
12182            invalidateParentIfNeededAndWasQuickRejected();
12183            notifySubtreeAccessibilityStateChangedIfNeeded();
12184        }
12185    }
12186
12187    /**
12188     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12189     * and {@link #setScaleX(float) scaled}.
12190     *
12191     * @see #getRotation()
12192     * @see #getScaleX()
12193     * @see #getScaleY()
12194     * @see #getPivotY()
12195     * @return The x location of the pivot point.
12196     *
12197     * @attr ref android.R.styleable#View_transformPivotX
12198     */
12199    @ViewDebug.ExportedProperty(category = "drawing")
12200    public float getPivotX() {
12201        return mRenderNode.getPivotX();
12202    }
12203
12204    /**
12205     * Sets the x location of the point around which the view is
12206     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12207     * By default, the pivot point is centered on the object.
12208     * Setting this property disables this behavior and causes the view to use only the
12209     * explicitly set pivotX and pivotY values.
12210     *
12211     * @param pivotX The x location of the pivot point.
12212     * @see #getRotation()
12213     * @see #getScaleX()
12214     * @see #getScaleY()
12215     * @see #getPivotY()
12216     *
12217     * @attr ref android.R.styleable#View_transformPivotX
12218     */
12219    public void setPivotX(float pivotX) {
12220        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12221            invalidateViewProperty(true, false);
12222            mRenderNode.setPivotX(pivotX);
12223            invalidateViewProperty(false, true);
12224
12225            invalidateParentIfNeededAndWasQuickRejected();
12226        }
12227    }
12228
12229    /**
12230     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12231     * and {@link #setScaleY(float) scaled}.
12232     *
12233     * @see #getRotation()
12234     * @see #getScaleX()
12235     * @see #getScaleY()
12236     * @see #getPivotY()
12237     * @return The y location of the pivot point.
12238     *
12239     * @attr ref android.R.styleable#View_transformPivotY
12240     */
12241    @ViewDebug.ExportedProperty(category = "drawing")
12242    public float getPivotY() {
12243        return mRenderNode.getPivotY();
12244    }
12245
12246    /**
12247     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12248     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12249     * Setting this property disables this behavior and causes the view to use only the
12250     * explicitly set pivotX and pivotY values.
12251     *
12252     * @param pivotY The y location of the pivot point.
12253     * @see #getRotation()
12254     * @see #getScaleX()
12255     * @see #getScaleY()
12256     * @see #getPivotY()
12257     *
12258     * @attr ref android.R.styleable#View_transformPivotY
12259     */
12260    public void setPivotY(float pivotY) {
12261        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12262            invalidateViewProperty(true, false);
12263            mRenderNode.setPivotY(pivotY);
12264            invalidateViewProperty(false, true);
12265
12266            invalidateParentIfNeededAndWasQuickRejected();
12267        }
12268    }
12269
12270    /**
12271     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12272     * completely transparent and 1 means the view is completely opaque.
12273     *
12274     * <p>By default this is 1.0f.
12275     * @return The opacity of the view.
12276     */
12277    @ViewDebug.ExportedProperty(category = "drawing")
12278    public float getAlpha() {
12279        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12280    }
12281
12282    /**
12283     * Sets the behavior for overlapping rendering for this view (see {@link
12284     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12285     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12286     * providing the value which is then used internally. That is, when {@link
12287     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12288     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12289     * instead.
12290     *
12291     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12292     * instead of that returned by {@link #hasOverlappingRendering()}.
12293     *
12294     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12295     */
12296    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12297        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12298        if (hasOverlappingRendering) {
12299            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12300        } else {
12301            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12302        }
12303    }
12304
12305    /**
12306     * Returns the value for overlapping rendering that is used internally. This is either
12307     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12308     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12309     *
12310     * @return The value for overlapping rendering being used internally.
12311     */
12312    public final boolean getHasOverlappingRendering() {
12313        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12314                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12315                hasOverlappingRendering();
12316    }
12317
12318    /**
12319     * Returns whether this View has content which overlaps.
12320     *
12321     * <p>This function, intended to be overridden by specific View types, is an optimization when
12322     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12323     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12324     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12325     * directly. An example of overlapping rendering is a TextView with a background image, such as
12326     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12327     * ImageView with only the foreground image. The default implementation returns true; subclasses
12328     * should override if they have cases which can be optimized.</p>
12329     *
12330     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12331     * necessitates that a View return true if it uses the methods internally without passing the
12332     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12333     *
12334     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12335     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12336     *
12337     * @return true if the content in this view might overlap, false otherwise.
12338     */
12339    @ViewDebug.ExportedProperty(category = "drawing")
12340    public boolean hasOverlappingRendering() {
12341        return true;
12342    }
12343
12344    /**
12345     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12346     * completely transparent and 1 means the view is completely opaque.
12347     *
12348     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12349     * can have significant performance implications, especially for large views. It is best to use
12350     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12351     *
12352     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12353     * strongly recommended for performance reasons to either override
12354     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12355     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12356     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12357     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12358     * of rendering cost, even for simple or small views. Starting with
12359     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12360     * applied to the view at the rendering level.</p>
12361     *
12362     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12363     * responsible for applying the opacity itself.</p>
12364     *
12365     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12366     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12367     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12368     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12369     *
12370     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12371     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12372     * {@link #hasOverlappingRendering}.</p>
12373     *
12374     * @param alpha The opacity of the view.
12375     *
12376     * @see #hasOverlappingRendering()
12377     * @see #setLayerType(int, android.graphics.Paint)
12378     *
12379     * @attr ref android.R.styleable#View_alpha
12380     */
12381    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12382        ensureTransformationInfo();
12383        if (mTransformationInfo.mAlpha != alpha) {
12384            // Report visibility changes, which can affect children, to accessibility
12385            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
12386                notifySubtreeAccessibilityStateChangedIfNeeded();
12387            }
12388            mTransformationInfo.mAlpha = alpha;
12389            if (onSetAlpha((int) (alpha * 255))) {
12390                mPrivateFlags |= PFLAG_ALPHA_SET;
12391                // subclass is handling alpha - don't optimize rendering cache invalidation
12392                invalidateParentCaches();
12393                invalidate(true);
12394            } else {
12395                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12396                invalidateViewProperty(true, false);
12397                mRenderNode.setAlpha(getFinalAlpha());
12398            }
12399        }
12400    }
12401
12402    /**
12403     * Faster version of setAlpha() which performs the same steps except there are
12404     * no calls to invalidate(). The caller of this function should perform proper invalidation
12405     * on the parent and this object. The return value indicates whether the subclass handles
12406     * alpha (the return value for onSetAlpha()).
12407     *
12408     * @param alpha The new value for the alpha property
12409     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12410     *         the new value for the alpha property is different from the old value
12411     */
12412    boolean setAlphaNoInvalidation(float alpha) {
12413        ensureTransformationInfo();
12414        if (mTransformationInfo.mAlpha != alpha) {
12415            mTransformationInfo.mAlpha = alpha;
12416            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12417            if (subclassHandlesAlpha) {
12418                mPrivateFlags |= PFLAG_ALPHA_SET;
12419                return true;
12420            } else {
12421                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12422                mRenderNode.setAlpha(getFinalAlpha());
12423            }
12424        }
12425        return false;
12426    }
12427
12428    /**
12429     * This property is hidden and intended only for use by the Fade transition, which
12430     * animates it to produce a visual translucency that does not side-effect (or get
12431     * affected by) the real alpha property. This value is composited with the other
12432     * alpha value (and the AlphaAnimation value, when that is present) to produce
12433     * a final visual translucency result, which is what is passed into the DisplayList.
12434     *
12435     * @hide
12436     */
12437    public void setTransitionAlpha(float alpha) {
12438        ensureTransformationInfo();
12439        if (mTransformationInfo.mTransitionAlpha != alpha) {
12440            mTransformationInfo.mTransitionAlpha = alpha;
12441            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12442            invalidateViewProperty(true, false);
12443            mRenderNode.setAlpha(getFinalAlpha());
12444        }
12445    }
12446
12447    /**
12448     * Calculates the visual alpha of this view, which is a combination of the actual
12449     * alpha value and the transitionAlpha value (if set).
12450     */
12451    private float getFinalAlpha() {
12452        if (mTransformationInfo != null) {
12453            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12454        }
12455        return 1;
12456    }
12457
12458    /**
12459     * This property is hidden and intended only for use by the Fade transition, which
12460     * animates it to produce a visual translucency that does not side-effect (or get
12461     * affected by) the real alpha property. This value is composited with the other
12462     * alpha value (and the AlphaAnimation value, when that is present) to produce
12463     * a final visual translucency result, which is what is passed into the DisplayList.
12464     *
12465     * @hide
12466     */
12467    @ViewDebug.ExportedProperty(category = "drawing")
12468    public float getTransitionAlpha() {
12469        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12470    }
12471
12472    /**
12473     * Top position of this view relative to its parent.
12474     *
12475     * @return The top of this view, in pixels.
12476     */
12477    @ViewDebug.CapturedViewProperty
12478    public final int getTop() {
12479        return mTop;
12480    }
12481
12482    /**
12483     * Sets the top position of this view relative to its parent. This method is meant to be called
12484     * by the layout system and should not generally be called otherwise, because the property
12485     * may be changed at any time by the layout.
12486     *
12487     * @param top The top of this view, in pixels.
12488     */
12489    public final void setTop(int top) {
12490        if (top != mTop) {
12491            final boolean matrixIsIdentity = hasIdentityMatrix();
12492            if (matrixIsIdentity) {
12493                if (mAttachInfo != null) {
12494                    int minTop;
12495                    int yLoc;
12496                    if (top < mTop) {
12497                        minTop = top;
12498                        yLoc = top - mTop;
12499                    } else {
12500                        minTop = mTop;
12501                        yLoc = 0;
12502                    }
12503                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12504                }
12505            } else {
12506                // Double-invalidation is necessary to capture view's old and new areas
12507                invalidate(true);
12508            }
12509
12510            int width = mRight - mLeft;
12511            int oldHeight = mBottom - mTop;
12512
12513            mTop = top;
12514            mRenderNode.setTop(mTop);
12515
12516            sizeChange(width, mBottom - mTop, width, oldHeight);
12517
12518            if (!matrixIsIdentity) {
12519                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12520                invalidate(true);
12521            }
12522            mBackgroundSizeChanged = true;
12523            if (mForegroundInfo != null) {
12524                mForegroundInfo.mBoundsChanged = true;
12525            }
12526            invalidateParentIfNeeded();
12527            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12528                // View was rejected last time it was drawn by its parent; this may have changed
12529                invalidateParentIfNeeded();
12530            }
12531        }
12532    }
12533
12534    /**
12535     * Bottom position of this view relative to its parent.
12536     *
12537     * @return The bottom of this view, in pixels.
12538     */
12539    @ViewDebug.CapturedViewProperty
12540    public final int getBottom() {
12541        return mBottom;
12542    }
12543
12544    /**
12545     * True if this view has changed since the last time being drawn.
12546     *
12547     * @return The dirty state of this view.
12548     */
12549    public boolean isDirty() {
12550        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12551    }
12552
12553    /**
12554     * Sets the bottom position of this view relative to its parent. This method is meant to be
12555     * called by the layout system and should not generally be called otherwise, because the
12556     * property may be changed at any time by the layout.
12557     *
12558     * @param bottom The bottom of this view, in pixels.
12559     */
12560    public final void setBottom(int bottom) {
12561        if (bottom != mBottom) {
12562            final boolean matrixIsIdentity = hasIdentityMatrix();
12563            if (matrixIsIdentity) {
12564                if (mAttachInfo != null) {
12565                    int maxBottom;
12566                    if (bottom < mBottom) {
12567                        maxBottom = mBottom;
12568                    } else {
12569                        maxBottom = bottom;
12570                    }
12571                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12572                }
12573            } else {
12574                // Double-invalidation is necessary to capture view's old and new areas
12575                invalidate(true);
12576            }
12577
12578            int width = mRight - mLeft;
12579            int oldHeight = mBottom - mTop;
12580
12581            mBottom = bottom;
12582            mRenderNode.setBottom(mBottom);
12583
12584            sizeChange(width, mBottom - mTop, width, oldHeight);
12585
12586            if (!matrixIsIdentity) {
12587                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12588                invalidate(true);
12589            }
12590            mBackgroundSizeChanged = true;
12591            if (mForegroundInfo != null) {
12592                mForegroundInfo.mBoundsChanged = true;
12593            }
12594            invalidateParentIfNeeded();
12595            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12596                // View was rejected last time it was drawn by its parent; this may have changed
12597                invalidateParentIfNeeded();
12598            }
12599        }
12600    }
12601
12602    /**
12603     * Left position of this view relative to its parent.
12604     *
12605     * @return The left edge of this view, in pixels.
12606     */
12607    @ViewDebug.CapturedViewProperty
12608    public final int getLeft() {
12609        return mLeft;
12610    }
12611
12612    /**
12613     * Sets the left position of this view relative to its parent. This method is meant to be called
12614     * by the layout system and should not generally be called otherwise, because the property
12615     * may be changed at any time by the layout.
12616     *
12617     * @param left The left of this view, in pixels.
12618     */
12619    public final void setLeft(int left) {
12620        if (left != mLeft) {
12621            final boolean matrixIsIdentity = hasIdentityMatrix();
12622            if (matrixIsIdentity) {
12623                if (mAttachInfo != null) {
12624                    int minLeft;
12625                    int xLoc;
12626                    if (left < mLeft) {
12627                        minLeft = left;
12628                        xLoc = left - mLeft;
12629                    } else {
12630                        minLeft = mLeft;
12631                        xLoc = 0;
12632                    }
12633                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
12634                }
12635            } else {
12636                // Double-invalidation is necessary to capture view's old and new areas
12637                invalidate(true);
12638            }
12639
12640            int oldWidth = mRight - mLeft;
12641            int height = mBottom - mTop;
12642
12643            mLeft = left;
12644            mRenderNode.setLeft(left);
12645
12646            sizeChange(mRight - mLeft, height, oldWidth, height);
12647
12648            if (!matrixIsIdentity) {
12649                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12650                invalidate(true);
12651            }
12652            mBackgroundSizeChanged = true;
12653            if (mForegroundInfo != null) {
12654                mForegroundInfo.mBoundsChanged = true;
12655            }
12656            invalidateParentIfNeeded();
12657            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12658                // View was rejected last time it was drawn by its parent; this may have changed
12659                invalidateParentIfNeeded();
12660            }
12661        }
12662    }
12663
12664    /**
12665     * Right position of this view relative to its parent.
12666     *
12667     * @return The right edge of this view, in pixels.
12668     */
12669    @ViewDebug.CapturedViewProperty
12670    public final int getRight() {
12671        return mRight;
12672    }
12673
12674    /**
12675     * Sets the right position of this view relative to its parent. This method is meant to be called
12676     * by the layout system and should not generally be called otherwise, because the property
12677     * may be changed at any time by the layout.
12678     *
12679     * @param right The right of this view, in pixels.
12680     */
12681    public final void setRight(int right) {
12682        if (right != mRight) {
12683            final boolean matrixIsIdentity = hasIdentityMatrix();
12684            if (matrixIsIdentity) {
12685                if (mAttachInfo != null) {
12686                    int maxRight;
12687                    if (right < mRight) {
12688                        maxRight = mRight;
12689                    } else {
12690                        maxRight = right;
12691                    }
12692                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
12693                }
12694            } else {
12695                // Double-invalidation is necessary to capture view's old and new areas
12696                invalidate(true);
12697            }
12698
12699            int oldWidth = mRight - mLeft;
12700            int height = mBottom - mTop;
12701
12702            mRight = right;
12703            mRenderNode.setRight(mRight);
12704
12705            sizeChange(mRight - mLeft, height, oldWidth, height);
12706
12707            if (!matrixIsIdentity) {
12708                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12709                invalidate(true);
12710            }
12711            mBackgroundSizeChanged = true;
12712            if (mForegroundInfo != null) {
12713                mForegroundInfo.mBoundsChanged = true;
12714            }
12715            invalidateParentIfNeeded();
12716            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12717                // View was rejected last time it was drawn by its parent; this may have changed
12718                invalidateParentIfNeeded();
12719            }
12720        }
12721    }
12722
12723    /**
12724     * The visual x position of this view, in pixels. This is equivalent to the
12725     * {@link #setTranslationX(float) translationX} property plus the current
12726     * {@link #getLeft() left} property.
12727     *
12728     * @return The visual x position of this view, in pixels.
12729     */
12730    @ViewDebug.ExportedProperty(category = "drawing")
12731    public float getX() {
12732        return mLeft + getTranslationX();
12733    }
12734
12735    /**
12736     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
12737     * {@link #setTranslationX(float) translationX} property to be the difference between
12738     * the x value passed in and the current {@link #getLeft() left} property.
12739     *
12740     * @param x The visual x position of this view, in pixels.
12741     */
12742    public void setX(float x) {
12743        setTranslationX(x - mLeft);
12744    }
12745
12746    /**
12747     * The visual y position of this view, in pixels. This is equivalent to the
12748     * {@link #setTranslationY(float) translationY} property plus the current
12749     * {@link #getTop() top} property.
12750     *
12751     * @return The visual y position of this view, in pixels.
12752     */
12753    @ViewDebug.ExportedProperty(category = "drawing")
12754    public float getY() {
12755        return mTop + getTranslationY();
12756    }
12757
12758    /**
12759     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
12760     * {@link #setTranslationY(float) translationY} property to be the difference between
12761     * the y value passed in and the current {@link #getTop() top} property.
12762     *
12763     * @param y The visual y position of this view, in pixels.
12764     */
12765    public void setY(float y) {
12766        setTranslationY(y - mTop);
12767    }
12768
12769    /**
12770     * The visual z position of this view, in pixels. This is equivalent to the
12771     * {@link #setTranslationZ(float) translationZ} property plus the current
12772     * {@link #getElevation() elevation} property.
12773     *
12774     * @return The visual z position of this view, in pixels.
12775     */
12776    @ViewDebug.ExportedProperty(category = "drawing")
12777    public float getZ() {
12778        return getElevation() + getTranslationZ();
12779    }
12780
12781    /**
12782     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
12783     * {@link #setTranslationZ(float) translationZ} property to be the difference between
12784     * the x value passed in and the current {@link #getElevation() elevation} property.
12785     *
12786     * @param z The visual z position of this view, in pixels.
12787     */
12788    public void setZ(float z) {
12789        setTranslationZ(z - getElevation());
12790    }
12791
12792    /**
12793     * The base elevation of this view relative to its parent, in pixels.
12794     *
12795     * @return The base depth position of the view, in pixels.
12796     */
12797    @ViewDebug.ExportedProperty(category = "drawing")
12798    public float getElevation() {
12799        return mRenderNode.getElevation();
12800    }
12801
12802    /**
12803     * Sets the base elevation of this view, in pixels.
12804     *
12805     * @attr ref android.R.styleable#View_elevation
12806     */
12807    public void setElevation(float elevation) {
12808        if (elevation != getElevation()) {
12809            invalidateViewProperty(true, false);
12810            mRenderNode.setElevation(elevation);
12811            invalidateViewProperty(false, true);
12812
12813            invalidateParentIfNeededAndWasQuickRejected();
12814        }
12815    }
12816
12817    /**
12818     * The horizontal location of this view relative to its {@link #getLeft() left} position.
12819     * This position is post-layout, in addition to wherever the object's
12820     * layout placed it.
12821     *
12822     * @return The horizontal position of this view relative to its left position, in pixels.
12823     */
12824    @ViewDebug.ExportedProperty(category = "drawing")
12825    public float getTranslationX() {
12826        return mRenderNode.getTranslationX();
12827    }
12828
12829    /**
12830     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
12831     * This effectively positions the object post-layout, in addition to wherever the object's
12832     * layout placed it.
12833     *
12834     * @param translationX The horizontal position of this view relative to its left position,
12835     * in pixels.
12836     *
12837     * @attr ref android.R.styleable#View_translationX
12838     */
12839    public void setTranslationX(float translationX) {
12840        if (translationX != getTranslationX()) {
12841            invalidateViewProperty(true, false);
12842            mRenderNode.setTranslationX(translationX);
12843            invalidateViewProperty(false, true);
12844
12845            invalidateParentIfNeededAndWasQuickRejected();
12846            notifySubtreeAccessibilityStateChangedIfNeeded();
12847        }
12848    }
12849
12850    /**
12851     * The vertical location of this view relative to its {@link #getTop() top} position.
12852     * This position is post-layout, in addition to wherever the object's
12853     * layout placed it.
12854     *
12855     * @return The vertical position of this view relative to its top position,
12856     * in pixels.
12857     */
12858    @ViewDebug.ExportedProperty(category = "drawing")
12859    public float getTranslationY() {
12860        return mRenderNode.getTranslationY();
12861    }
12862
12863    /**
12864     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
12865     * This effectively positions the object post-layout, in addition to wherever the object's
12866     * layout placed it.
12867     *
12868     * @param translationY The vertical position of this view relative to its top position,
12869     * in pixels.
12870     *
12871     * @attr ref android.R.styleable#View_translationY
12872     */
12873    public void setTranslationY(float translationY) {
12874        if (translationY != getTranslationY()) {
12875            invalidateViewProperty(true, false);
12876            mRenderNode.setTranslationY(translationY);
12877            invalidateViewProperty(false, true);
12878
12879            invalidateParentIfNeededAndWasQuickRejected();
12880            notifySubtreeAccessibilityStateChangedIfNeeded();
12881        }
12882    }
12883
12884    /**
12885     * The depth location of this view relative to its {@link #getElevation() elevation}.
12886     *
12887     * @return The depth of this view relative to its elevation.
12888     */
12889    @ViewDebug.ExportedProperty(category = "drawing")
12890    public float getTranslationZ() {
12891        return mRenderNode.getTranslationZ();
12892    }
12893
12894    /**
12895     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
12896     *
12897     * @attr ref android.R.styleable#View_translationZ
12898     */
12899    public void setTranslationZ(float translationZ) {
12900        if (translationZ != getTranslationZ()) {
12901            invalidateViewProperty(true, false);
12902            mRenderNode.setTranslationZ(translationZ);
12903            invalidateViewProperty(false, true);
12904
12905            invalidateParentIfNeededAndWasQuickRejected();
12906        }
12907    }
12908
12909    /** @hide */
12910    public void setAnimationMatrix(Matrix matrix) {
12911        invalidateViewProperty(true, false);
12912        mRenderNode.setAnimationMatrix(matrix);
12913        invalidateViewProperty(false, true);
12914
12915        invalidateParentIfNeededAndWasQuickRejected();
12916    }
12917
12918    /**
12919     * Returns the current StateListAnimator if exists.
12920     *
12921     * @return StateListAnimator or null if it does not exists
12922     * @see    #setStateListAnimator(android.animation.StateListAnimator)
12923     */
12924    public StateListAnimator getStateListAnimator() {
12925        return mStateListAnimator;
12926    }
12927
12928    /**
12929     * Attaches the provided StateListAnimator to this View.
12930     * <p>
12931     * Any previously attached StateListAnimator will be detached.
12932     *
12933     * @param stateListAnimator The StateListAnimator to update the view
12934     * @see {@link android.animation.StateListAnimator}
12935     */
12936    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12937        if (mStateListAnimator == stateListAnimator) {
12938            return;
12939        }
12940        if (mStateListAnimator != null) {
12941            mStateListAnimator.setTarget(null);
12942        }
12943        mStateListAnimator = stateListAnimator;
12944        if (stateListAnimator != null) {
12945            stateListAnimator.setTarget(this);
12946            if (isAttachedToWindow()) {
12947                stateListAnimator.setState(getDrawableState());
12948            }
12949        }
12950    }
12951
12952    /**
12953     * Returns whether the Outline should be used to clip the contents of the View.
12954     * <p>
12955     * Note that this flag will only be respected if the View's Outline returns true from
12956     * {@link Outline#canClip()}.
12957     *
12958     * @see #setOutlineProvider(ViewOutlineProvider)
12959     * @see #setClipToOutline(boolean)
12960     */
12961    public final boolean getClipToOutline() {
12962        return mRenderNode.getClipToOutline();
12963    }
12964
12965    /**
12966     * Sets whether the View's Outline should be used to clip the contents of the View.
12967     * <p>
12968     * Only a single non-rectangular clip can be applied on a View at any time.
12969     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12970     * circular reveal} animation take priority over Outline clipping, and
12971     * child Outline clipping takes priority over Outline clipping done by a
12972     * parent.
12973     * <p>
12974     * Note that this flag will only be respected if the View's Outline returns true from
12975     * {@link Outline#canClip()}.
12976     *
12977     * @see #setOutlineProvider(ViewOutlineProvider)
12978     * @see #getClipToOutline()
12979     */
12980    public void setClipToOutline(boolean clipToOutline) {
12981        damageInParent();
12982        if (getClipToOutline() != clipToOutline) {
12983            mRenderNode.setClipToOutline(clipToOutline);
12984        }
12985    }
12986
12987    // correspond to the enum values of View_outlineProvider
12988    private static final int PROVIDER_BACKGROUND = 0;
12989    private static final int PROVIDER_NONE = 1;
12990    private static final int PROVIDER_BOUNDS = 2;
12991    private static final int PROVIDER_PADDED_BOUNDS = 3;
12992    private void setOutlineProviderFromAttribute(int providerInt) {
12993        switch (providerInt) {
12994            case PROVIDER_BACKGROUND:
12995                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
12996                break;
12997            case PROVIDER_NONE:
12998                setOutlineProvider(null);
12999                break;
13000            case PROVIDER_BOUNDS:
13001                setOutlineProvider(ViewOutlineProvider.BOUNDS);
13002                break;
13003            case PROVIDER_PADDED_BOUNDS:
13004                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
13005                break;
13006        }
13007    }
13008
13009    /**
13010     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
13011     * the shape of the shadow it casts, and enables outline clipping.
13012     * <p>
13013     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
13014     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
13015     * outline provider with this method allows this behavior to be overridden.
13016     * <p>
13017     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
13018     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
13019     * <p>
13020     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
13021     *
13022     * @see #setClipToOutline(boolean)
13023     * @see #getClipToOutline()
13024     * @see #getOutlineProvider()
13025     */
13026    public void setOutlineProvider(ViewOutlineProvider provider) {
13027        mOutlineProvider = provider;
13028        invalidateOutline();
13029    }
13030
13031    /**
13032     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
13033     * that defines the shape of the shadow it casts, and enables outline clipping.
13034     *
13035     * @see #setOutlineProvider(ViewOutlineProvider)
13036     */
13037    public ViewOutlineProvider getOutlineProvider() {
13038        return mOutlineProvider;
13039    }
13040
13041    /**
13042     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
13043     *
13044     * @see #setOutlineProvider(ViewOutlineProvider)
13045     */
13046    public void invalidateOutline() {
13047        rebuildOutline();
13048
13049        notifySubtreeAccessibilityStateChangedIfNeeded();
13050        invalidateViewProperty(false, false);
13051    }
13052
13053    /**
13054     * Internal version of {@link #invalidateOutline()} which invalidates the
13055     * outline without invalidating the view itself. This is intended to be called from
13056     * within methods in the View class itself which are the result of the view being
13057     * invalidated already. For example, when we are drawing the background of a View,
13058     * we invalidate the outline in case it changed in the meantime, but we do not
13059     * need to invalidate the view because we're already drawing the background as part
13060     * of drawing the view in response to an earlier invalidation of the view.
13061     */
13062    private void rebuildOutline() {
13063        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
13064        if (mAttachInfo == null) return;
13065
13066        if (mOutlineProvider == null) {
13067            // no provider, remove outline
13068            mRenderNode.setOutline(null);
13069        } else {
13070            final Outline outline = mAttachInfo.mTmpOutline;
13071            outline.setEmpty();
13072            outline.setAlpha(1.0f);
13073
13074            mOutlineProvider.getOutline(this, outline);
13075            mRenderNode.setOutline(outline);
13076        }
13077    }
13078
13079    /**
13080     * HierarchyViewer only
13081     *
13082     * @hide
13083     */
13084    @ViewDebug.ExportedProperty(category = "drawing")
13085    public boolean hasShadow() {
13086        return mRenderNode.hasShadow();
13087    }
13088
13089
13090    /** @hide */
13091    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13092        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13093        invalidateViewProperty(false, false);
13094    }
13095
13096    /**
13097     * Hit rectangle in parent's coordinates
13098     *
13099     * @param outRect The hit rectangle of the view.
13100     */
13101    public void getHitRect(Rect outRect) {
13102        if (hasIdentityMatrix() || mAttachInfo == null) {
13103            outRect.set(mLeft, mTop, mRight, mBottom);
13104        } else {
13105            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13106            tmpRect.set(0, 0, getWidth(), getHeight());
13107            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13108            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13109                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13110        }
13111    }
13112
13113    /**
13114     * Determines whether the given point, in local coordinates is inside the view.
13115     */
13116    /*package*/ final boolean pointInView(float localX, float localY) {
13117        return pointInView(localX, localY, 0);
13118    }
13119
13120    /**
13121     * Utility method to determine whether the given point, in local coordinates,
13122     * is inside the view, where the area of the view is expanded by the slop factor.
13123     * This method is called while processing touch-move events to determine if the event
13124     * is still within the view.
13125     *
13126     * @hide
13127     */
13128    public boolean pointInView(float localX, float localY, float slop) {
13129        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13130                localY < ((mBottom - mTop) + slop);
13131    }
13132
13133    /**
13134     * When a view has focus and the user navigates away from it, the next view is searched for
13135     * starting from the rectangle filled in by this method.
13136     *
13137     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13138     * of the view.  However, if your view maintains some idea of internal selection,
13139     * such as a cursor, or a selected row or column, you should override this method and
13140     * fill in a more specific rectangle.
13141     *
13142     * @param r The rectangle to fill in, in this view's coordinates.
13143     */
13144    public void getFocusedRect(Rect r) {
13145        getDrawingRect(r);
13146    }
13147
13148    /**
13149     * If some part of this view is not clipped by any of its parents, then
13150     * return that area in r in global (root) coordinates. To convert r to local
13151     * coordinates (without taking possible View rotations into account), offset
13152     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13153     * If the view is completely clipped or translated out, return false.
13154     *
13155     * @param r If true is returned, r holds the global coordinates of the
13156     *        visible portion of this view.
13157     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13158     *        between this view and its root. globalOffet may be null.
13159     * @return true if r is non-empty (i.e. part of the view is visible at the
13160     *         root level.
13161     */
13162    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13163        int width = mRight - mLeft;
13164        int height = mBottom - mTop;
13165        if (width > 0 && height > 0) {
13166            r.set(0, 0, width, height);
13167            if (globalOffset != null) {
13168                globalOffset.set(-mScrollX, -mScrollY);
13169            }
13170            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13171        }
13172        return false;
13173    }
13174
13175    public final boolean getGlobalVisibleRect(Rect r) {
13176        return getGlobalVisibleRect(r, null);
13177    }
13178
13179    public final boolean getLocalVisibleRect(Rect r) {
13180        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13181        if (getGlobalVisibleRect(r, offset)) {
13182            r.offset(-offset.x, -offset.y); // make r local
13183            return true;
13184        }
13185        return false;
13186    }
13187
13188    /**
13189     * Offset this view's vertical location by the specified number of pixels.
13190     *
13191     * @param offset the number of pixels to offset the view by
13192     */
13193    public void offsetTopAndBottom(int offset) {
13194        if (offset != 0) {
13195            final boolean matrixIsIdentity = hasIdentityMatrix();
13196            if (matrixIsIdentity) {
13197                if (isHardwareAccelerated()) {
13198                    invalidateViewProperty(false, false);
13199                } else {
13200                    final ViewParent p = mParent;
13201                    if (p != null && mAttachInfo != null) {
13202                        final Rect r = mAttachInfo.mTmpInvalRect;
13203                        int minTop;
13204                        int maxBottom;
13205                        int yLoc;
13206                        if (offset < 0) {
13207                            minTop = mTop + offset;
13208                            maxBottom = mBottom;
13209                            yLoc = offset;
13210                        } else {
13211                            minTop = mTop;
13212                            maxBottom = mBottom + offset;
13213                            yLoc = 0;
13214                        }
13215                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13216                        p.invalidateChild(this, r);
13217                    }
13218                }
13219            } else {
13220                invalidateViewProperty(false, false);
13221            }
13222
13223            mTop += offset;
13224            mBottom += offset;
13225            mRenderNode.offsetTopAndBottom(offset);
13226            if (isHardwareAccelerated()) {
13227                invalidateViewProperty(false, false);
13228                invalidateParentIfNeededAndWasQuickRejected();
13229            } else {
13230                if (!matrixIsIdentity) {
13231                    invalidateViewProperty(false, true);
13232                }
13233                invalidateParentIfNeeded();
13234            }
13235            notifySubtreeAccessibilityStateChangedIfNeeded();
13236        }
13237    }
13238
13239    /**
13240     * Offset this view's horizontal location by the specified amount of pixels.
13241     *
13242     * @param offset the number of pixels to offset the view by
13243     */
13244    public void offsetLeftAndRight(int offset) {
13245        if (offset != 0) {
13246            final boolean matrixIsIdentity = hasIdentityMatrix();
13247            if (matrixIsIdentity) {
13248                if (isHardwareAccelerated()) {
13249                    invalidateViewProperty(false, false);
13250                } else {
13251                    final ViewParent p = mParent;
13252                    if (p != null && mAttachInfo != null) {
13253                        final Rect r = mAttachInfo.mTmpInvalRect;
13254                        int minLeft;
13255                        int maxRight;
13256                        if (offset < 0) {
13257                            minLeft = mLeft + offset;
13258                            maxRight = mRight;
13259                        } else {
13260                            minLeft = mLeft;
13261                            maxRight = mRight + offset;
13262                        }
13263                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13264                        p.invalidateChild(this, r);
13265                    }
13266                }
13267            } else {
13268                invalidateViewProperty(false, false);
13269            }
13270
13271            mLeft += offset;
13272            mRight += offset;
13273            mRenderNode.offsetLeftAndRight(offset);
13274            if (isHardwareAccelerated()) {
13275                invalidateViewProperty(false, false);
13276                invalidateParentIfNeededAndWasQuickRejected();
13277            } else {
13278                if (!matrixIsIdentity) {
13279                    invalidateViewProperty(false, true);
13280                }
13281                invalidateParentIfNeeded();
13282            }
13283            notifySubtreeAccessibilityStateChangedIfNeeded();
13284        }
13285    }
13286
13287    /**
13288     * Get the LayoutParams associated with this view. All views should have
13289     * layout parameters. These supply parameters to the <i>parent</i> of this
13290     * view specifying how it should be arranged. There are many subclasses of
13291     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13292     * of ViewGroup that are responsible for arranging their children.
13293     *
13294     * This method may return null if this View is not attached to a parent
13295     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13296     * was not invoked successfully. When a View is attached to a parent
13297     * ViewGroup, this method must not return null.
13298     *
13299     * @return The LayoutParams associated with this view, or null if no
13300     *         parameters have been set yet
13301     */
13302    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13303    public ViewGroup.LayoutParams getLayoutParams() {
13304        return mLayoutParams;
13305    }
13306
13307    /**
13308     * Set the layout parameters associated with this view. These supply
13309     * parameters to the <i>parent</i> of this view specifying how it should be
13310     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13311     * correspond to the different subclasses of ViewGroup that are responsible
13312     * for arranging their children.
13313     *
13314     * @param params The layout parameters for this view, cannot be null
13315     */
13316    public void setLayoutParams(ViewGroup.LayoutParams params) {
13317        if (params == null) {
13318            throw new NullPointerException("Layout parameters cannot be null");
13319        }
13320        mLayoutParams = params;
13321        resolveLayoutParams();
13322        if (mParent instanceof ViewGroup) {
13323            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13324        }
13325        requestLayout();
13326    }
13327
13328    /**
13329     * Resolve the layout parameters depending on the resolved layout direction
13330     *
13331     * @hide
13332     */
13333    public void resolveLayoutParams() {
13334        if (mLayoutParams != null) {
13335            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13336        }
13337    }
13338
13339    /**
13340     * Set the scrolled position of your view. This will cause a call to
13341     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13342     * invalidated.
13343     * @param x the x position to scroll to
13344     * @param y the y position to scroll to
13345     */
13346    public void scrollTo(int x, int y) {
13347        if (mScrollX != x || mScrollY != y) {
13348            int oldX = mScrollX;
13349            int oldY = mScrollY;
13350            mScrollX = x;
13351            mScrollY = y;
13352            invalidateParentCaches();
13353            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13354            if (!awakenScrollBars()) {
13355                postInvalidateOnAnimation();
13356            }
13357        }
13358    }
13359
13360    /**
13361     * Move the scrolled position of your view. This will cause a call to
13362     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13363     * invalidated.
13364     * @param x the amount of pixels to scroll by horizontally
13365     * @param y the amount of pixels to scroll by vertically
13366     */
13367    public void scrollBy(int x, int y) {
13368        scrollTo(mScrollX + x, mScrollY + y);
13369    }
13370
13371    /**
13372     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13373     * animation to fade the scrollbars out after a default delay. If a subclass
13374     * provides animated scrolling, the start delay should equal the duration
13375     * of the scrolling animation.</p>
13376     *
13377     * <p>The animation starts only if at least one of the scrollbars is
13378     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13379     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13380     * this method returns true, and false otherwise. If the animation is
13381     * started, this method calls {@link #invalidate()}; in that case the
13382     * caller should not call {@link #invalidate()}.</p>
13383     *
13384     * <p>This method should be invoked every time a subclass directly updates
13385     * the scroll parameters.</p>
13386     *
13387     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13388     * and {@link #scrollTo(int, int)}.</p>
13389     *
13390     * @return true if the animation is played, false otherwise
13391     *
13392     * @see #awakenScrollBars(int)
13393     * @see #scrollBy(int, int)
13394     * @see #scrollTo(int, int)
13395     * @see #isHorizontalScrollBarEnabled()
13396     * @see #isVerticalScrollBarEnabled()
13397     * @see #setHorizontalScrollBarEnabled(boolean)
13398     * @see #setVerticalScrollBarEnabled(boolean)
13399     */
13400    protected boolean awakenScrollBars() {
13401        return mScrollCache != null &&
13402                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13403    }
13404
13405    /**
13406     * Trigger the scrollbars to draw.
13407     * This method differs from awakenScrollBars() only in its default duration.
13408     * initialAwakenScrollBars() will show the scroll bars for longer than
13409     * usual to give the user more of a chance to notice them.
13410     *
13411     * @return true if the animation is played, false otherwise.
13412     */
13413    private boolean initialAwakenScrollBars() {
13414        return mScrollCache != null &&
13415                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13416    }
13417
13418    /**
13419     * <p>
13420     * Trigger the scrollbars to draw. When invoked this method starts an
13421     * animation to fade the scrollbars out after a fixed delay. If a subclass
13422     * provides animated scrolling, the start delay should equal the duration of
13423     * the scrolling animation.
13424     * </p>
13425     *
13426     * <p>
13427     * The animation starts only if at least one of the scrollbars is enabled,
13428     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13429     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13430     * this method returns true, and false otherwise. If the animation is
13431     * started, this method calls {@link #invalidate()}; in that case the caller
13432     * should not call {@link #invalidate()}.
13433     * </p>
13434     *
13435     * <p>
13436     * This method should be invoked every time a subclass directly updates the
13437     * scroll parameters.
13438     * </p>
13439     *
13440     * @param startDelay the delay, in milliseconds, after which the animation
13441     *        should start; when the delay is 0, the animation starts
13442     *        immediately
13443     * @return true if the animation is played, false otherwise
13444     *
13445     * @see #scrollBy(int, int)
13446     * @see #scrollTo(int, int)
13447     * @see #isHorizontalScrollBarEnabled()
13448     * @see #isVerticalScrollBarEnabled()
13449     * @see #setHorizontalScrollBarEnabled(boolean)
13450     * @see #setVerticalScrollBarEnabled(boolean)
13451     */
13452    protected boolean awakenScrollBars(int startDelay) {
13453        return awakenScrollBars(startDelay, true);
13454    }
13455
13456    /**
13457     * <p>
13458     * Trigger the scrollbars to draw. When invoked this method starts an
13459     * animation to fade the scrollbars out after a fixed delay. If a subclass
13460     * provides animated scrolling, the start delay should equal the duration of
13461     * the scrolling animation.
13462     * </p>
13463     *
13464     * <p>
13465     * The animation starts only if at least one of the scrollbars is enabled,
13466     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13467     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13468     * this method returns true, and false otherwise. If the animation is
13469     * started, this method calls {@link #invalidate()} if the invalidate parameter
13470     * is set to true; in that case the caller
13471     * should not call {@link #invalidate()}.
13472     * </p>
13473     *
13474     * <p>
13475     * This method should be invoked every time a subclass directly updates the
13476     * scroll parameters.
13477     * </p>
13478     *
13479     * @param startDelay the delay, in milliseconds, after which the animation
13480     *        should start; when the delay is 0, the animation starts
13481     *        immediately
13482     *
13483     * @param invalidate Whether this method should call invalidate
13484     *
13485     * @return true if the animation is played, false otherwise
13486     *
13487     * @see #scrollBy(int, int)
13488     * @see #scrollTo(int, int)
13489     * @see #isHorizontalScrollBarEnabled()
13490     * @see #isVerticalScrollBarEnabled()
13491     * @see #setHorizontalScrollBarEnabled(boolean)
13492     * @see #setVerticalScrollBarEnabled(boolean)
13493     */
13494    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13495        final ScrollabilityCache scrollCache = mScrollCache;
13496
13497        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13498            return false;
13499        }
13500
13501        if (scrollCache.scrollBar == null) {
13502            scrollCache.scrollBar = new ScrollBarDrawable();
13503            scrollCache.scrollBar.setState(getDrawableState());
13504            scrollCache.scrollBar.setCallback(this);
13505        }
13506
13507        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13508
13509            if (invalidate) {
13510                // Invalidate to show the scrollbars
13511                postInvalidateOnAnimation();
13512            }
13513
13514            if (scrollCache.state == ScrollabilityCache.OFF) {
13515                // FIXME: this is copied from WindowManagerService.
13516                // We should get this value from the system when it
13517                // is possible to do so.
13518                final int KEY_REPEAT_FIRST_DELAY = 750;
13519                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13520            }
13521
13522            // Tell mScrollCache when we should start fading. This may
13523            // extend the fade start time if one was already scheduled
13524            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13525            scrollCache.fadeStartTime = fadeStartTime;
13526            scrollCache.state = ScrollabilityCache.ON;
13527
13528            // Schedule our fader to run, unscheduling any old ones first
13529            if (mAttachInfo != null) {
13530                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13531                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13532            }
13533
13534            return true;
13535        }
13536
13537        return false;
13538    }
13539
13540    /**
13541     * Do not invalidate views which are not visible and which are not running an animation. They
13542     * will not get drawn and they should not set dirty flags as if they will be drawn
13543     */
13544    private boolean skipInvalidate() {
13545        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13546                (!(mParent instanceof ViewGroup) ||
13547                        !((ViewGroup) mParent).isViewTransitioning(this));
13548    }
13549
13550    /**
13551     * Mark the area defined by dirty as needing to be drawn. If the view is
13552     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13553     * point in the future.
13554     * <p>
13555     * This must be called from a UI thread. To call from a non-UI thread, call
13556     * {@link #postInvalidate()}.
13557     * <p>
13558     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13559     * {@code dirty}.
13560     *
13561     * @param dirty the rectangle representing the bounds of the dirty region
13562     */
13563    public void invalidate(Rect dirty) {
13564        final int scrollX = mScrollX;
13565        final int scrollY = mScrollY;
13566        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13567                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13568    }
13569
13570    /**
13571     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13572     * coordinates of the dirty rect are relative to the view. If the view is
13573     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13574     * point in the future.
13575     * <p>
13576     * This must be called from a UI thread. To call from a non-UI thread, call
13577     * {@link #postInvalidate()}.
13578     *
13579     * @param l the left position of the dirty region
13580     * @param t the top position of the dirty region
13581     * @param r the right position of the dirty region
13582     * @param b the bottom position of the dirty region
13583     */
13584    public void invalidate(int l, int t, int r, int b) {
13585        final int scrollX = mScrollX;
13586        final int scrollY = mScrollY;
13587        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13588    }
13589
13590    /**
13591     * Invalidate the whole view. If the view is visible,
13592     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13593     * the future.
13594     * <p>
13595     * This must be called from a UI thread. To call from a non-UI thread, call
13596     * {@link #postInvalidate()}.
13597     */
13598    public void invalidate() {
13599        invalidate(true);
13600    }
13601
13602    /**
13603     * This is where the invalidate() work actually happens. A full invalidate()
13604     * causes the drawing cache to be invalidated, but this function can be
13605     * called with invalidateCache set to false to skip that invalidation step
13606     * for cases that do not need it (for example, a component that remains at
13607     * the same dimensions with the same content).
13608     *
13609     * @param invalidateCache Whether the drawing cache for this view should be
13610     *            invalidated as well. This is usually true for a full
13611     *            invalidate, but may be set to false if the View's contents or
13612     *            dimensions have not changed.
13613     */
13614    void invalidate(boolean invalidateCache) {
13615        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13616    }
13617
13618    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
13619            boolean fullInvalidate) {
13620        if (mGhostView != null) {
13621            mGhostView.invalidate(true);
13622            return;
13623        }
13624
13625        if (skipInvalidate()) {
13626            return;
13627        }
13628
13629        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
13630                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
13631                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
13632                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
13633            if (fullInvalidate) {
13634                mLastIsOpaque = isOpaque();
13635                mPrivateFlags &= ~PFLAG_DRAWN;
13636            }
13637
13638            mPrivateFlags |= PFLAG_DIRTY;
13639
13640            if (invalidateCache) {
13641                mPrivateFlags |= PFLAG_INVALIDATED;
13642                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13643            }
13644
13645            // Propagate the damage rectangle to the parent view.
13646            final AttachInfo ai = mAttachInfo;
13647            final ViewParent p = mParent;
13648            if (p != null && ai != null && l < r && t < b) {
13649                final Rect damage = ai.mTmpInvalRect;
13650                damage.set(l, t, r, b);
13651                p.invalidateChild(this, damage);
13652            }
13653
13654            // Damage the entire projection receiver, if necessary.
13655            if (mBackground != null && mBackground.isProjected()) {
13656                final View receiver = getProjectionReceiver();
13657                if (receiver != null) {
13658                    receiver.damageInParent();
13659                }
13660            }
13661
13662            // Damage the entire IsolatedZVolume receiving this view's shadow.
13663            if (isHardwareAccelerated() && getZ() != 0) {
13664                damageShadowReceiver();
13665            }
13666        }
13667    }
13668
13669    /**
13670     * @return this view's projection receiver, or {@code null} if none exists
13671     */
13672    private View getProjectionReceiver() {
13673        ViewParent p = getParent();
13674        while (p != null && p instanceof View) {
13675            final View v = (View) p;
13676            if (v.isProjectionReceiver()) {
13677                return v;
13678            }
13679            p = p.getParent();
13680        }
13681
13682        return null;
13683    }
13684
13685    /**
13686     * @return whether the view is a projection receiver
13687     */
13688    private boolean isProjectionReceiver() {
13689        return mBackground != null;
13690    }
13691
13692    /**
13693     * Damage area of the screen that can be covered by this View's shadow.
13694     *
13695     * This method will guarantee that any changes to shadows cast by a View
13696     * are damaged on the screen for future redraw.
13697     */
13698    private void damageShadowReceiver() {
13699        final AttachInfo ai = mAttachInfo;
13700        if (ai != null) {
13701            ViewParent p = getParent();
13702            if (p != null && p instanceof ViewGroup) {
13703                final ViewGroup vg = (ViewGroup) p;
13704                vg.damageInParent();
13705            }
13706        }
13707    }
13708
13709    /**
13710     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
13711     * set any flags or handle all of the cases handled by the default invalidation methods.
13712     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
13713     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
13714     * walk up the hierarchy, transforming the dirty rect as necessary.
13715     *
13716     * The method also handles normal invalidation logic if display list properties are not
13717     * being used in this view. The invalidateParent and forceRedraw flags are used by that
13718     * backup approach, to handle these cases used in the various property-setting methods.
13719     *
13720     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
13721     * are not being used in this view
13722     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
13723     * list properties are not being used in this view
13724     */
13725    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
13726        if (!isHardwareAccelerated()
13727                || !mRenderNode.isValid()
13728                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
13729            if (invalidateParent) {
13730                invalidateParentCaches();
13731            }
13732            if (forceRedraw) {
13733                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13734            }
13735            invalidate(false);
13736        } else {
13737            damageInParent();
13738        }
13739        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
13740            damageShadowReceiver();
13741        }
13742    }
13743
13744    /**
13745     * Tells the parent view to damage this view's bounds.
13746     *
13747     * @hide
13748     */
13749    protected void damageInParent() {
13750        final AttachInfo ai = mAttachInfo;
13751        final ViewParent p = mParent;
13752        if (p != null && ai != null) {
13753            final Rect r = ai.mTmpInvalRect;
13754            r.set(0, 0, mRight - mLeft, mBottom - mTop);
13755            if (mParent instanceof ViewGroup) {
13756                ((ViewGroup) mParent).damageChild(this, r);
13757            } else {
13758                mParent.invalidateChild(this, r);
13759            }
13760        }
13761    }
13762
13763    /**
13764     * Utility method to transform a given Rect by the current matrix of this view.
13765     */
13766    void transformRect(final Rect rect) {
13767        if (!getMatrix().isIdentity()) {
13768            RectF boundingRect = mAttachInfo.mTmpTransformRect;
13769            boundingRect.set(rect);
13770            getMatrix().mapRect(boundingRect);
13771            rect.set((int) Math.floor(boundingRect.left),
13772                    (int) Math.floor(boundingRect.top),
13773                    (int) Math.ceil(boundingRect.right),
13774                    (int) Math.ceil(boundingRect.bottom));
13775        }
13776    }
13777
13778    /**
13779     * Used to indicate that the parent of this view should clear its caches. This functionality
13780     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13781     * which is necessary when various parent-managed properties of the view change, such as
13782     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
13783     * clears the parent caches and does not causes an invalidate event.
13784     *
13785     * @hide
13786     */
13787    protected void invalidateParentCaches() {
13788        if (mParent instanceof View) {
13789            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
13790        }
13791    }
13792
13793    /**
13794     * Used to indicate that the parent of this view should be invalidated. This functionality
13795     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13796     * which is necessary when various parent-managed properties of the view change, such as
13797     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
13798     * an invalidation event to the parent.
13799     *
13800     * @hide
13801     */
13802    protected void invalidateParentIfNeeded() {
13803        if (isHardwareAccelerated() && mParent instanceof View) {
13804            ((View) mParent).invalidate(true);
13805        }
13806    }
13807
13808    /**
13809     * @hide
13810     */
13811    protected void invalidateParentIfNeededAndWasQuickRejected() {
13812        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
13813            // View was rejected last time it was drawn by its parent; this may have changed
13814            invalidateParentIfNeeded();
13815        }
13816    }
13817
13818    /**
13819     * Indicates whether this View is opaque. An opaque View guarantees that it will
13820     * draw all the pixels overlapping its bounds using a fully opaque color.
13821     *
13822     * Subclasses of View should override this method whenever possible to indicate
13823     * whether an instance is opaque. Opaque Views are treated in a special way by
13824     * the View hierarchy, possibly allowing it to perform optimizations during
13825     * invalidate/draw passes.
13826     *
13827     * @return True if this View is guaranteed to be fully opaque, false otherwise.
13828     */
13829    @ViewDebug.ExportedProperty(category = "drawing")
13830    public boolean isOpaque() {
13831        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
13832                getFinalAlpha() >= 1.0f;
13833    }
13834
13835    /**
13836     * @hide
13837     */
13838    protected void computeOpaqueFlags() {
13839        // Opaque if:
13840        //   - Has a background
13841        //   - Background is opaque
13842        //   - Doesn't have scrollbars or scrollbars overlay
13843
13844        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
13845            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
13846        } else {
13847            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
13848        }
13849
13850        final int flags = mViewFlags;
13851        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
13852                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
13853                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
13854            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
13855        } else {
13856            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
13857        }
13858    }
13859
13860    /**
13861     * @hide
13862     */
13863    protected boolean hasOpaqueScrollbars() {
13864        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
13865    }
13866
13867    /**
13868     * @return A handler associated with the thread running the View. This
13869     * handler can be used to pump events in the UI events queue.
13870     */
13871    public Handler getHandler() {
13872        final AttachInfo attachInfo = mAttachInfo;
13873        if (attachInfo != null) {
13874            return attachInfo.mHandler;
13875        }
13876        return null;
13877    }
13878
13879    /**
13880     * Returns the queue of runnable for this view.
13881     *
13882     * @return the queue of runnables for this view
13883     */
13884    private HandlerActionQueue getRunQueue() {
13885        if (mRunQueue == null) {
13886            mRunQueue = new HandlerActionQueue();
13887        }
13888        return mRunQueue;
13889    }
13890
13891    /**
13892     * Gets the view root associated with the View.
13893     * @return The view root, or null if none.
13894     * @hide
13895     */
13896    public ViewRootImpl getViewRootImpl() {
13897        if (mAttachInfo != null) {
13898            return mAttachInfo.mViewRootImpl;
13899        }
13900        return null;
13901    }
13902
13903    /**
13904     * @hide
13905     */
13906    public ThreadedRenderer getThreadedRenderer() {
13907        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
13908    }
13909
13910    /**
13911     * <p>Causes the Runnable to be added to the message queue.
13912     * The runnable will be run on the user interface thread.</p>
13913     *
13914     * @param action The Runnable that will be executed.
13915     *
13916     * @return Returns true if the Runnable was successfully placed in to the
13917     *         message queue.  Returns false on failure, usually because the
13918     *         looper processing the message queue is exiting.
13919     *
13920     * @see #postDelayed
13921     * @see #removeCallbacks
13922     */
13923    public boolean post(Runnable action) {
13924        final AttachInfo attachInfo = mAttachInfo;
13925        if (attachInfo != null) {
13926            return attachInfo.mHandler.post(action);
13927        }
13928
13929        // Postpone the runnable until we know on which thread it needs to run.
13930        // Assume that the runnable will be successfully placed after attach.
13931        getRunQueue().post(action);
13932        return true;
13933    }
13934
13935    /**
13936     * <p>Causes the Runnable to be added to the message queue, to be run
13937     * after the specified amount of time elapses.
13938     * The runnable will be run on the user interface thread.</p>
13939     *
13940     * @param action The Runnable that will be executed.
13941     * @param delayMillis The delay (in milliseconds) until the Runnable
13942     *        will be executed.
13943     *
13944     * @return true if the Runnable was successfully placed in to the
13945     *         message queue.  Returns false on failure, usually because the
13946     *         looper processing the message queue is exiting.  Note that a
13947     *         result of true does not mean the Runnable will be processed --
13948     *         if the looper is quit before the delivery time of the message
13949     *         occurs then the message will be dropped.
13950     *
13951     * @see #post
13952     * @see #removeCallbacks
13953     */
13954    public boolean postDelayed(Runnable action, long delayMillis) {
13955        final AttachInfo attachInfo = mAttachInfo;
13956        if (attachInfo != null) {
13957            return attachInfo.mHandler.postDelayed(action, delayMillis);
13958        }
13959
13960        // Postpone the runnable until we know on which thread it needs to run.
13961        // Assume that the runnable will be successfully placed after attach.
13962        getRunQueue().postDelayed(action, delayMillis);
13963        return true;
13964    }
13965
13966    /**
13967     * <p>Causes the Runnable to execute on the next animation time step.
13968     * The runnable will be run on the user interface thread.</p>
13969     *
13970     * @param action The Runnable that will be executed.
13971     *
13972     * @see #postOnAnimationDelayed
13973     * @see #removeCallbacks
13974     */
13975    public void postOnAnimation(Runnable action) {
13976        final AttachInfo attachInfo = mAttachInfo;
13977        if (attachInfo != null) {
13978            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13979                    Choreographer.CALLBACK_ANIMATION, action, null);
13980        } else {
13981            // Postpone the runnable until we know
13982            // on which thread it needs to run.
13983            getRunQueue().post(action);
13984        }
13985    }
13986
13987    /**
13988     * <p>Causes the Runnable to execute on the next animation time step,
13989     * after the specified amount of time elapses.
13990     * The runnable will be run on the user interface thread.</p>
13991     *
13992     * @param action The Runnable that will be executed.
13993     * @param delayMillis The delay (in milliseconds) until the Runnable
13994     *        will be executed.
13995     *
13996     * @see #postOnAnimation
13997     * @see #removeCallbacks
13998     */
13999    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
14000        final AttachInfo attachInfo = mAttachInfo;
14001        if (attachInfo != null) {
14002            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14003                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
14004        } else {
14005            // Postpone the runnable until we know
14006            // on which thread it needs to run.
14007            getRunQueue().postDelayed(action, delayMillis);
14008        }
14009    }
14010
14011    /**
14012     * <p>Removes the specified Runnable from the message queue.</p>
14013     *
14014     * @param action The Runnable to remove from the message handling queue
14015     *
14016     * @return true if this view could ask the Handler to remove the Runnable,
14017     *         false otherwise. When the returned value is true, the Runnable
14018     *         may or may not have been actually removed from the message queue
14019     *         (for instance, if the Runnable was not in the queue already.)
14020     *
14021     * @see #post
14022     * @see #postDelayed
14023     * @see #postOnAnimation
14024     * @see #postOnAnimationDelayed
14025     */
14026    public boolean removeCallbacks(Runnable action) {
14027        if (action != null) {
14028            final AttachInfo attachInfo = mAttachInfo;
14029            if (attachInfo != null) {
14030                attachInfo.mHandler.removeCallbacks(action);
14031                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14032                        Choreographer.CALLBACK_ANIMATION, action, null);
14033            }
14034            getRunQueue().removeCallbacks(action);
14035        }
14036        return true;
14037    }
14038
14039    /**
14040     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
14041     * Use this to invalidate the View from a non-UI thread.</p>
14042     *
14043     * <p>This method can be invoked from outside of the UI thread
14044     * only when this View is attached to a window.</p>
14045     *
14046     * @see #invalidate()
14047     * @see #postInvalidateDelayed(long)
14048     */
14049    public void postInvalidate() {
14050        postInvalidateDelayed(0);
14051    }
14052
14053    /**
14054     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14055     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
14056     *
14057     * <p>This method can be invoked from outside of the UI thread
14058     * only when this View is attached to a window.</p>
14059     *
14060     * @param left The left coordinate of the rectangle to invalidate.
14061     * @param top The top coordinate of the rectangle to invalidate.
14062     * @param right The right coordinate of the rectangle to invalidate.
14063     * @param bottom The bottom coordinate of the rectangle to invalidate.
14064     *
14065     * @see #invalidate(int, int, int, int)
14066     * @see #invalidate(Rect)
14067     * @see #postInvalidateDelayed(long, int, int, int, int)
14068     */
14069    public void postInvalidate(int left, int top, int right, int bottom) {
14070        postInvalidateDelayed(0, left, top, right, bottom);
14071    }
14072
14073    /**
14074     * <p>Cause an invalidate to happen on a subsequent cycle through the event
14075     * loop. Waits for the specified amount of time.</p>
14076     *
14077     * <p>This method can be invoked from outside of the UI thread
14078     * only when this View is attached to a window.</p>
14079     *
14080     * @param delayMilliseconds the duration in milliseconds to delay the
14081     *         invalidation by
14082     *
14083     * @see #invalidate()
14084     * @see #postInvalidate()
14085     */
14086    public void postInvalidateDelayed(long delayMilliseconds) {
14087        // We try only with the AttachInfo because there's no point in invalidating
14088        // if we are not attached to our window
14089        final AttachInfo attachInfo = mAttachInfo;
14090        if (attachInfo != null) {
14091            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14092        }
14093    }
14094
14095    /**
14096     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14097     * through the event loop. Waits for the specified amount of time.</p>
14098     *
14099     * <p>This method can be invoked from outside of the UI thread
14100     * only when this View is attached to a window.</p>
14101     *
14102     * @param delayMilliseconds the duration in milliseconds to delay the
14103     *         invalidation by
14104     * @param left The left coordinate of the rectangle to invalidate.
14105     * @param top The top coordinate of the rectangle to invalidate.
14106     * @param right The right coordinate of the rectangle to invalidate.
14107     * @param bottom The bottom coordinate of the rectangle to invalidate.
14108     *
14109     * @see #invalidate(int, int, int, int)
14110     * @see #invalidate(Rect)
14111     * @see #postInvalidate(int, int, int, int)
14112     */
14113    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14114            int right, int bottom) {
14115
14116        // We try only with the AttachInfo because there's no point in invalidating
14117        // if we are not attached to our window
14118        final AttachInfo attachInfo = mAttachInfo;
14119        if (attachInfo != null) {
14120            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14121            info.target = this;
14122            info.left = left;
14123            info.top = top;
14124            info.right = right;
14125            info.bottom = bottom;
14126
14127            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14128        }
14129    }
14130
14131    /**
14132     * <p>Cause an invalidate to happen on the next animation time step, typically the
14133     * next display frame.</p>
14134     *
14135     * <p>This method can be invoked from outside of the UI thread
14136     * only when this View is attached to a window.</p>
14137     *
14138     * @see #invalidate()
14139     */
14140    public void postInvalidateOnAnimation() {
14141        // We try only with the AttachInfo because there's no point in invalidating
14142        // if we are not attached to our window
14143        final AttachInfo attachInfo = mAttachInfo;
14144        if (attachInfo != null) {
14145            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14146        }
14147    }
14148
14149    /**
14150     * <p>Cause an invalidate of the specified area to happen on the next animation
14151     * time step, typically the next display frame.</p>
14152     *
14153     * <p>This method can be invoked from outside of the UI thread
14154     * only when this View is attached to a window.</p>
14155     *
14156     * @param left The left coordinate of the rectangle to invalidate.
14157     * @param top The top coordinate of the rectangle to invalidate.
14158     * @param right The right coordinate of the rectangle to invalidate.
14159     * @param bottom The bottom coordinate of the rectangle to invalidate.
14160     *
14161     * @see #invalidate(int, int, int, int)
14162     * @see #invalidate(Rect)
14163     */
14164    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14165        // We try only with the AttachInfo because there's no point in invalidating
14166        // if we are not attached to our window
14167        final AttachInfo attachInfo = mAttachInfo;
14168        if (attachInfo != null) {
14169            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14170            info.target = this;
14171            info.left = left;
14172            info.top = top;
14173            info.right = right;
14174            info.bottom = bottom;
14175
14176            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14177        }
14178    }
14179
14180    /**
14181     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14182     * This event is sent at most once every
14183     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14184     */
14185    private void postSendViewScrolledAccessibilityEventCallback() {
14186        if (mSendViewScrolledAccessibilityEvent == null) {
14187            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14188        }
14189        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14190            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14191            postDelayed(mSendViewScrolledAccessibilityEvent,
14192                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14193        }
14194    }
14195
14196    /**
14197     * Called by a parent to request that a child update its values for mScrollX
14198     * and mScrollY if necessary. This will typically be done if the child is
14199     * animating a scroll using a {@link android.widget.Scroller Scroller}
14200     * object.
14201     */
14202    public void computeScroll() {
14203    }
14204
14205    /**
14206     * <p>Indicate whether the horizontal edges are faded when the view is
14207     * scrolled horizontally.</p>
14208     *
14209     * @return true if the horizontal edges should are faded on scroll, false
14210     *         otherwise
14211     *
14212     * @see #setHorizontalFadingEdgeEnabled(boolean)
14213     *
14214     * @attr ref android.R.styleable#View_requiresFadingEdge
14215     */
14216    public boolean isHorizontalFadingEdgeEnabled() {
14217        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14218    }
14219
14220    /**
14221     * <p>Define whether the horizontal edges should be faded when this view
14222     * is scrolled horizontally.</p>
14223     *
14224     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14225     *                                    be faded when the view is scrolled
14226     *                                    horizontally
14227     *
14228     * @see #isHorizontalFadingEdgeEnabled()
14229     *
14230     * @attr ref android.R.styleable#View_requiresFadingEdge
14231     */
14232    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14233        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14234            if (horizontalFadingEdgeEnabled) {
14235                initScrollCache();
14236            }
14237
14238            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14239        }
14240    }
14241
14242    /**
14243     * <p>Indicate whether the vertical edges are faded when the view is
14244     * scrolled horizontally.</p>
14245     *
14246     * @return true if the vertical edges should are faded on scroll, false
14247     *         otherwise
14248     *
14249     * @see #setVerticalFadingEdgeEnabled(boolean)
14250     *
14251     * @attr ref android.R.styleable#View_requiresFadingEdge
14252     */
14253    public boolean isVerticalFadingEdgeEnabled() {
14254        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14255    }
14256
14257    /**
14258     * <p>Define whether the vertical edges should be faded when this view
14259     * is scrolled vertically.</p>
14260     *
14261     * @param verticalFadingEdgeEnabled true if the vertical edges should
14262     *                                  be faded when the view is scrolled
14263     *                                  vertically
14264     *
14265     * @see #isVerticalFadingEdgeEnabled()
14266     *
14267     * @attr ref android.R.styleable#View_requiresFadingEdge
14268     */
14269    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14270        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14271            if (verticalFadingEdgeEnabled) {
14272                initScrollCache();
14273            }
14274
14275            mViewFlags ^= FADING_EDGE_VERTICAL;
14276        }
14277    }
14278
14279    /**
14280     * Returns the strength, or intensity, of the top faded edge. The strength is
14281     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14282     * returns 0.0 or 1.0 but no value in between.
14283     *
14284     * Subclasses should override this method to provide a smoother fade transition
14285     * when scrolling occurs.
14286     *
14287     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14288     */
14289    protected float getTopFadingEdgeStrength() {
14290        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14291    }
14292
14293    /**
14294     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14295     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14296     * returns 0.0 or 1.0 but no value in between.
14297     *
14298     * Subclasses should override this method to provide a smoother fade transition
14299     * when scrolling occurs.
14300     *
14301     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14302     */
14303    protected float getBottomFadingEdgeStrength() {
14304        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14305                computeVerticalScrollRange() ? 1.0f : 0.0f;
14306    }
14307
14308    /**
14309     * Returns the strength, or intensity, of the left faded edge. The strength is
14310     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14311     * returns 0.0 or 1.0 but no value in between.
14312     *
14313     * Subclasses should override this method to provide a smoother fade transition
14314     * when scrolling occurs.
14315     *
14316     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14317     */
14318    protected float getLeftFadingEdgeStrength() {
14319        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14320    }
14321
14322    /**
14323     * Returns the strength, or intensity, of the right faded edge. The strength is
14324     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14325     * returns 0.0 or 1.0 but no value in between.
14326     *
14327     * Subclasses should override this method to provide a smoother fade transition
14328     * when scrolling occurs.
14329     *
14330     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14331     */
14332    protected float getRightFadingEdgeStrength() {
14333        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14334                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14335    }
14336
14337    /**
14338     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14339     * scrollbar is not drawn by default.</p>
14340     *
14341     * @return true if the horizontal scrollbar should be painted, false
14342     *         otherwise
14343     *
14344     * @see #setHorizontalScrollBarEnabled(boolean)
14345     */
14346    public boolean isHorizontalScrollBarEnabled() {
14347        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14348    }
14349
14350    /**
14351     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14352     * scrollbar is not drawn by default.</p>
14353     *
14354     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14355     *                                   be painted
14356     *
14357     * @see #isHorizontalScrollBarEnabled()
14358     */
14359    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14360        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14361            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14362            computeOpaqueFlags();
14363            resolvePadding();
14364        }
14365    }
14366
14367    /**
14368     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14369     * scrollbar is not drawn by default.</p>
14370     *
14371     * @return true if the vertical scrollbar should be painted, false
14372     *         otherwise
14373     *
14374     * @see #setVerticalScrollBarEnabled(boolean)
14375     */
14376    public boolean isVerticalScrollBarEnabled() {
14377        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14378    }
14379
14380    /**
14381     * <p>Define whether the vertical scrollbar should be drawn or not. The
14382     * scrollbar is not drawn by default.</p>
14383     *
14384     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14385     *                                 be painted
14386     *
14387     * @see #isVerticalScrollBarEnabled()
14388     */
14389    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14390        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14391            mViewFlags ^= SCROLLBARS_VERTICAL;
14392            computeOpaqueFlags();
14393            resolvePadding();
14394        }
14395    }
14396
14397    /**
14398     * @hide
14399     */
14400    protected void recomputePadding() {
14401        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14402    }
14403
14404    /**
14405     * Define whether scrollbars will fade when the view is not scrolling.
14406     *
14407     * @param fadeScrollbars whether to enable fading
14408     *
14409     * @attr ref android.R.styleable#View_fadeScrollbars
14410     */
14411    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14412        initScrollCache();
14413        final ScrollabilityCache scrollabilityCache = mScrollCache;
14414        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14415        if (fadeScrollbars) {
14416            scrollabilityCache.state = ScrollabilityCache.OFF;
14417        } else {
14418            scrollabilityCache.state = ScrollabilityCache.ON;
14419        }
14420    }
14421
14422    /**
14423     *
14424     * Returns true if scrollbars will fade when this view is not scrolling
14425     *
14426     * @return true if scrollbar fading is enabled
14427     *
14428     * @attr ref android.R.styleable#View_fadeScrollbars
14429     */
14430    public boolean isScrollbarFadingEnabled() {
14431        return mScrollCache != null && mScrollCache.fadeScrollBars;
14432    }
14433
14434    /**
14435     *
14436     * Returns the delay before scrollbars fade.
14437     *
14438     * @return the delay before scrollbars fade
14439     *
14440     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14441     */
14442    public int getScrollBarDefaultDelayBeforeFade() {
14443        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14444                mScrollCache.scrollBarDefaultDelayBeforeFade;
14445    }
14446
14447    /**
14448     * Define the delay before scrollbars fade.
14449     *
14450     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14451     *
14452     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14453     */
14454    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14455        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14456    }
14457
14458    /**
14459     *
14460     * Returns the scrollbar fade duration.
14461     *
14462     * @return the scrollbar fade duration
14463     *
14464     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14465     */
14466    public int getScrollBarFadeDuration() {
14467        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14468                mScrollCache.scrollBarFadeDuration;
14469    }
14470
14471    /**
14472     * Define the scrollbar fade duration.
14473     *
14474     * @param scrollBarFadeDuration - the scrollbar fade duration
14475     *
14476     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14477     */
14478    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14479        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14480    }
14481
14482    /**
14483     *
14484     * Returns the scrollbar size.
14485     *
14486     * @return the scrollbar size
14487     *
14488     * @attr ref android.R.styleable#View_scrollbarSize
14489     */
14490    public int getScrollBarSize() {
14491        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14492                mScrollCache.scrollBarSize;
14493    }
14494
14495    /**
14496     * Define the scrollbar size.
14497     *
14498     * @param scrollBarSize - the scrollbar size
14499     *
14500     * @attr ref android.R.styleable#View_scrollbarSize
14501     */
14502    public void setScrollBarSize(int scrollBarSize) {
14503        getScrollCache().scrollBarSize = scrollBarSize;
14504    }
14505
14506    /**
14507     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14508     * inset. When inset, they add to the padding of the view. And the scrollbars
14509     * can be drawn inside the padding area or on the edge of the view. For example,
14510     * if a view has a background drawable and you want to draw the scrollbars
14511     * inside the padding specified by the drawable, you can use
14512     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14513     * appear at the edge of the view, ignoring the padding, then you can use
14514     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14515     * @param style the style of the scrollbars. Should be one of
14516     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14517     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14518     * @see #SCROLLBARS_INSIDE_OVERLAY
14519     * @see #SCROLLBARS_INSIDE_INSET
14520     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14521     * @see #SCROLLBARS_OUTSIDE_INSET
14522     *
14523     * @attr ref android.R.styleable#View_scrollbarStyle
14524     */
14525    public void setScrollBarStyle(@ScrollBarStyle int style) {
14526        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14527            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14528            computeOpaqueFlags();
14529            resolvePadding();
14530        }
14531    }
14532
14533    /**
14534     * <p>Returns the current scrollbar style.</p>
14535     * @return the current scrollbar style
14536     * @see #SCROLLBARS_INSIDE_OVERLAY
14537     * @see #SCROLLBARS_INSIDE_INSET
14538     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14539     * @see #SCROLLBARS_OUTSIDE_INSET
14540     *
14541     * @attr ref android.R.styleable#View_scrollbarStyle
14542     */
14543    @ViewDebug.ExportedProperty(mapping = {
14544            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14545            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14546            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14547            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14548    })
14549    @ScrollBarStyle
14550    public int getScrollBarStyle() {
14551        return mViewFlags & SCROLLBARS_STYLE_MASK;
14552    }
14553
14554    /**
14555     * <p>Compute the horizontal range that the horizontal scrollbar
14556     * represents.</p>
14557     *
14558     * <p>The range is expressed in arbitrary units that must be the same as the
14559     * units used by {@link #computeHorizontalScrollExtent()} and
14560     * {@link #computeHorizontalScrollOffset()}.</p>
14561     *
14562     * <p>The default range is the drawing width of this view.</p>
14563     *
14564     * @return the total horizontal range represented by the horizontal
14565     *         scrollbar
14566     *
14567     * @see #computeHorizontalScrollExtent()
14568     * @see #computeHorizontalScrollOffset()
14569     * @see android.widget.ScrollBarDrawable
14570     */
14571    protected int computeHorizontalScrollRange() {
14572        return getWidth();
14573    }
14574
14575    /**
14576     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14577     * within the horizontal range. This value is used to compute the position
14578     * of the thumb within the scrollbar's track.</p>
14579     *
14580     * <p>The range is expressed in arbitrary units that must be the same as the
14581     * units used by {@link #computeHorizontalScrollRange()} and
14582     * {@link #computeHorizontalScrollExtent()}.</p>
14583     *
14584     * <p>The default offset is the scroll offset of this view.</p>
14585     *
14586     * @return the horizontal offset of the scrollbar's thumb
14587     *
14588     * @see #computeHorizontalScrollRange()
14589     * @see #computeHorizontalScrollExtent()
14590     * @see android.widget.ScrollBarDrawable
14591     */
14592    protected int computeHorizontalScrollOffset() {
14593        return mScrollX;
14594    }
14595
14596    /**
14597     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14598     * within the horizontal range. This value is used to compute the length
14599     * of the thumb within the scrollbar's track.</p>
14600     *
14601     * <p>The range is expressed in arbitrary units that must be the same as the
14602     * units used by {@link #computeHorizontalScrollRange()} and
14603     * {@link #computeHorizontalScrollOffset()}.</p>
14604     *
14605     * <p>The default extent is the drawing width of this view.</p>
14606     *
14607     * @return the horizontal extent of the scrollbar's thumb
14608     *
14609     * @see #computeHorizontalScrollRange()
14610     * @see #computeHorizontalScrollOffset()
14611     * @see android.widget.ScrollBarDrawable
14612     */
14613    protected int computeHorizontalScrollExtent() {
14614        return getWidth();
14615    }
14616
14617    /**
14618     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14619     *
14620     * <p>The range is expressed in arbitrary units that must be the same as the
14621     * units used by {@link #computeVerticalScrollExtent()} and
14622     * {@link #computeVerticalScrollOffset()}.</p>
14623     *
14624     * @return the total vertical range represented by the vertical scrollbar
14625     *
14626     * <p>The default range is the drawing height of this view.</p>
14627     *
14628     * @see #computeVerticalScrollExtent()
14629     * @see #computeVerticalScrollOffset()
14630     * @see android.widget.ScrollBarDrawable
14631     */
14632    protected int computeVerticalScrollRange() {
14633        return getHeight();
14634    }
14635
14636    /**
14637     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14638     * within the horizontal range. This value is used to compute the position
14639     * of the thumb within the scrollbar's track.</p>
14640     *
14641     * <p>The range is expressed in arbitrary units that must be the same as the
14642     * units used by {@link #computeVerticalScrollRange()} and
14643     * {@link #computeVerticalScrollExtent()}.</p>
14644     *
14645     * <p>The default offset is the scroll offset of this view.</p>
14646     *
14647     * @return the vertical offset of the scrollbar's thumb
14648     *
14649     * @see #computeVerticalScrollRange()
14650     * @see #computeVerticalScrollExtent()
14651     * @see android.widget.ScrollBarDrawable
14652     */
14653    protected int computeVerticalScrollOffset() {
14654        return mScrollY;
14655    }
14656
14657    /**
14658     * <p>Compute the vertical extent of the vertical scrollbar's thumb
14659     * within the vertical range. This value is used to compute the length
14660     * of the thumb within the scrollbar's track.</p>
14661     *
14662     * <p>The range is expressed in arbitrary units that must be the same as the
14663     * units used by {@link #computeVerticalScrollRange()} and
14664     * {@link #computeVerticalScrollOffset()}.</p>
14665     *
14666     * <p>The default extent is the drawing height of this view.</p>
14667     *
14668     * @return the vertical extent of the scrollbar's thumb
14669     *
14670     * @see #computeVerticalScrollRange()
14671     * @see #computeVerticalScrollOffset()
14672     * @see android.widget.ScrollBarDrawable
14673     */
14674    protected int computeVerticalScrollExtent() {
14675        return getHeight();
14676    }
14677
14678    /**
14679     * Check if this view can be scrolled horizontally in a certain direction.
14680     *
14681     * @param direction Negative to check scrolling left, positive to check scrolling right.
14682     * @return true if this view can be scrolled in the specified direction, false otherwise.
14683     */
14684    public boolean canScrollHorizontally(int direction) {
14685        final int offset = computeHorizontalScrollOffset();
14686        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
14687        if (range == 0) return false;
14688        if (direction < 0) {
14689            return offset > 0;
14690        } else {
14691            return offset < range - 1;
14692        }
14693    }
14694
14695    /**
14696     * Check if this view can be scrolled vertically in a certain direction.
14697     *
14698     * @param direction Negative to check scrolling up, positive to check scrolling down.
14699     * @return true if this view can be scrolled in the specified direction, false otherwise.
14700     */
14701    public boolean canScrollVertically(int direction) {
14702        final int offset = computeVerticalScrollOffset();
14703        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
14704        if (range == 0) return false;
14705        if (direction < 0) {
14706            return offset > 0;
14707        } else {
14708            return offset < range - 1;
14709        }
14710    }
14711
14712    void getScrollIndicatorBounds(@NonNull Rect out) {
14713        out.left = mScrollX;
14714        out.right = mScrollX + mRight - mLeft;
14715        out.top = mScrollY;
14716        out.bottom = mScrollY + mBottom - mTop;
14717    }
14718
14719    private void onDrawScrollIndicators(Canvas c) {
14720        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
14721            // No scroll indicators enabled.
14722            return;
14723        }
14724
14725        final Drawable dr = mScrollIndicatorDrawable;
14726        if (dr == null) {
14727            // Scroll indicators aren't supported here.
14728            return;
14729        }
14730
14731        final int h = dr.getIntrinsicHeight();
14732        final int w = dr.getIntrinsicWidth();
14733        final Rect rect = mAttachInfo.mTmpInvalRect;
14734        getScrollIndicatorBounds(rect);
14735
14736        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
14737            final boolean canScrollUp = canScrollVertically(-1);
14738            if (canScrollUp) {
14739                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
14740                dr.draw(c);
14741            }
14742        }
14743
14744        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
14745            final boolean canScrollDown = canScrollVertically(1);
14746            if (canScrollDown) {
14747                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
14748                dr.draw(c);
14749            }
14750        }
14751
14752        final int leftRtl;
14753        final int rightRtl;
14754        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14755            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
14756            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
14757        } else {
14758            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
14759            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
14760        }
14761
14762        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
14763        if ((mPrivateFlags3 & leftMask) != 0) {
14764            final boolean canScrollLeft = canScrollHorizontally(-1);
14765            if (canScrollLeft) {
14766                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
14767                dr.draw(c);
14768            }
14769        }
14770
14771        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
14772        if ((mPrivateFlags3 & rightMask) != 0) {
14773            final boolean canScrollRight = canScrollHorizontally(1);
14774            if (canScrollRight) {
14775                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
14776                dr.draw(c);
14777            }
14778        }
14779    }
14780
14781    private void getHorizontalScrollBarBounds(Rect bounds) {
14782        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14783        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14784                && !isVerticalScrollBarHidden();
14785        final int size = getHorizontalScrollbarHeight();
14786        final int verticalScrollBarGap = drawVerticalScrollBar ?
14787                getVerticalScrollbarWidth() : 0;
14788        final int width = mRight - mLeft;
14789        final int height = mBottom - mTop;
14790        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
14791        bounds.left = mScrollX + (mPaddingLeft & inside);
14792        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
14793        bounds.bottom = bounds.top + size;
14794    }
14795
14796    private void getVerticalScrollBarBounds(Rect bounds) {
14797        if (mRoundScrollbarRenderer == null) {
14798            getStraightVerticalScrollBarBounds(bounds);
14799        } else {
14800            getRoundVerticalScrollBarBounds(bounds);
14801        }
14802    }
14803
14804    private void getRoundVerticalScrollBarBounds(Rect bounds) {
14805        final int width = mRight - mLeft;
14806        final int height = mBottom - mTop;
14807        // Do not take padding into account as we always want the scrollbars
14808        // to hug the screen for round wearable devices.
14809        bounds.left = mScrollX;
14810        bounds.top = mScrollY;
14811        bounds.right = bounds.left + width;
14812        bounds.bottom = mScrollY + height;
14813    }
14814
14815    private void getStraightVerticalScrollBarBounds(Rect bounds) {
14816        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14817        final int size = getVerticalScrollbarWidth();
14818        int verticalScrollbarPosition = mVerticalScrollbarPosition;
14819        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
14820            verticalScrollbarPosition = isLayoutRtl() ?
14821                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
14822        }
14823        final int width = mRight - mLeft;
14824        final int height = mBottom - mTop;
14825        switch (verticalScrollbarPosition) {
14826            default:
14827            case SCROLLBAR_POSITION_RIGHT:
14828                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
14829                break;
14830            case SCROLLBAR_POSITION_LEFT:
14831                bounds.left = mScrollX + (mUserPaddingLeft & inside);
14832                break;
14833        }
14834        bounds.top = mScrollY + (mPaddingTop & inside);
14835        bounds.right = bounds.left + size;
14836        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
14837    }
14838
14839    /**
14840     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
14841     * scrollbars are painted only if they have been awakened first.</p>
14842     *
14843     * @param canvas the canvas on which to draw the scrollbars
14844     *
14845     * @see #awakenScrollBars(int)
14846     */
14847    protected final void onDrawScrollBars(Canvas canvas) {
14848        // scrollbars are drawn only when the animation is running
14849        final ScrollabilityCache cache = mScrollCache;
14850
14851        if (cache != null) {
14852
14853            int state = cache.state;
14854
14855            if (state == ScrollabilityCache.OFF) {
14856                return;
14857            }
14858
14859            boolean invalidate = false;
14860
14861            if (state == ScrollabilityCache.FADING) {
14862                // We're fading -- get our fade interpolation
14863                if (cache.interpolatorValues == null) {
14864                    cache.interpolatorValues = new float[1];
14865                }
14866
14867                float[] values = cache.interpolatorValues;
14868
14869                // Stops the animation if we're done
14870                if (cache.scrollBarInterpolator.timeToValues(values) ==
14871                        Interpolator.Result.FREEZE_END) {
14872                    cache.state = ScrollabilityCache.OFF;
14873                } else {
14874                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
14875                }
14876
14877                // This will make the scroll bars inval themselves after
14878                // drawing. We only want this when we're fading so that
14879                // we prevent excessive redraws
14880                invalidate = true;
14881            } else {
14882                // We're just on -- but we may have been fading before so
14883                // reset alpha
14884                cache.scrollBar.mutate().setAlpha(255);
14885            }
14886
14887            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
14888            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14889                    && !isVerticalScrollBarHidden();
14890
14891            // Fork out the scroll bar drawing for round wearable devices.
14892            if (mRoundScrollbarRenderer != null) {
14893                if (drawVerticalScrollBar) {
14894                    final Rect bounds = cache.mScrollBarBounds;
14895                    getVerticalScrollBarBounds(bounds);
14896                    mRoundScrollbarRenderer.drawRoundScrollbars(
14897                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
14898                    if (invalidate) {
14899                        invalidate();
14900                    }
14901                }
14902                // Do not draw horizontal scroll bars for round wearable devices.
14903            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
14904                final ScrollBarDrawable scrollBar = cache.scrollBar;
14905
14906                if (drawHorizontalScrollBar) {
14907                    scrollBar.setParameters(computeHorizontalScrollRange(),
14908                            computeHorizontalScrollOffset(),
14909                            computeHorizontalScrollExtent(), false);
14910                    final Rect bounds = cache.mScrollBarBounds;
14911                    getHorizontalScrollBarBounds(bounds);
14912                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14913                            bounds.right, bounds.bottom);
14914                    if (invalidate) {
14915                        invalidate(bounds);
14916                    }
14917                }
14918
14919                if (drawVerticalScrollBar) {
14920                    scrollBar.setParameters(computeVerticalScrollRange(),
14921                            computeVerticalScrollOffset(),
14922                            computeVerticalScrollExtent(), true);
14923                    final Rect bounds = cache.mScrollBarBounds;
14924                    getVerticalScrollBarBounds(bounds);
14925                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14926                            bounds.right, bounds.bottom);
14927                    if (invalidate) {
14928                        invalidate(bounds);
14929                    }
14930                }
14931            }
14932        }
14933    }
14934
14935    /**
14936     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
14937     * FastScroller is visible.
14938     * @return whether to temporarily hide the vertical scrollbar
14939     * @hide
14940     */
14941    protected boolean isVerticalScrollBarHidden() {
14942        return false;
14943    }
14944
14945    /**
14946     * <p>Draw the horizontal scrollbar if
14947     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
14948     *
14949     * @param canvas the canvas on which to draw the scrollbar
14950     * @param scrollBar the scrollbar's drawable
14951     *
14952     * @see #isHorizontalScrollBarEnabled()
14953     * @see #computeHorizontalScrollRange()
14954     * @see #computeHorizontalScrollExtent()
14955     * @see #computeHorizontalScrollOffset()
14956     * @see android.widget.ScrollBarDrawable
14957     * @hide
14958     */
14959    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
14960            int l, int t, int r, int b) {
14961        scrollBar.setBounds(l, t, r, b);
14962        scrollBar.draw(canvas);
14963    }
14964
14965    /**
14966     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
14967     * returns true.</p>
14968     *
14969     * @param canvas the canvas on which to draw the scrollbar
14970     * @param scrollBar the scrollbar's drawable
14971     *
14972     * @see #isVerticalScrollBarEnabled()
14973     * @see #computeVerticalScrollRange()
14974     * @see #computeVerticalScrollExtent()
14975     * @see #computeVerticalScrollOffset()
14976     * @see android.widget.ScrollBarDrawable
14977     * @hide
14978     */
14979    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14980            int l, int t, int r, int b) {
14981        scrollBar.setBounds(l, t, r, b);
14982        scrollBar.draw(canvas);
14983    }
14984
14985    /**
14986     * Implement this to do your drawing.
14987     *
14988     * @param canvas the canvas on which the background will be drawn
14989     */
14990    protected void onDraw(Canvas canvas) {
14991    }
14992
14993    /*
14994     * Caller is responsible for calling requestLayout if necessary.
14995     * (This allows addViewInLayout to not request a new layout.)
14996     */
14997    void assignParent(ViewParent parent) {
14998        if (mParent == null) {
14999            mParent = parent;
15000        } else if (parent == null) {
15001            mParent = null;
15002        } else {
15003            throw new RuntimeException("view " + this + " being added, but"
15004                    + " it already has a parent");
15005        }
15006    }
15007
15008    /**
15009     * This is called when the view is attached to a window.  At this point it
15010     * has a Surface and will start drawing.  Note that this function is
15011     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
15012     * however it may be called any time before the first onDraw -- including
15013     * before or after {@link #onMeasure(int, int)}.
15014     *
15015     * @see #onDetachedFromWindow()
15016     */
15017    @CallSuper
15018    protected void onAttachedToWindow() {
15019        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
15020            mParent.requestTransparentRegion(this);
15021        }
15022
15023        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15024
15025        jumpDrawablesToCurrentState();
15026
15027        resetSubtreeAccessibilityStateChanged();
15028
15029        // rebuild, since Outline not maintained while View is detached
15030        rebuildOutline();
15031
15032        if (isFocused()) {
15033            InputMethodManager imm = InputMethodManager.peekInstance();
15034            if (imm != null) {
15035                imm.focusIn(this);
15036            }
15037        }
15038    }
15039
15040    /**
15041     * Resolve all RTL related properties.
15042     *
15043     * @return true if resolution of RTL properties has been done
15044     *
15045     * @hide
15046     */
15047    public boolean resolveRtlPropertiesIfNeeded() {
15048        if (!needRtlPropertiesResolution()) return false;
15049
15050        // Order is important here: LayoutDirection MUST be resolved first
15051        if (!isLayoutDirectionResolved()) {
15052            resolveLayoutDirection();
15053            resolveLayoutParams();
15054        }
15055        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
15056        if (!isTextDirectionResolved()) {
15057            resolveTextDirection();
15058        }
15059        if (!isTextAlignmentResolved()) {
15060            resolveTextAlignment();
15061        }
15062        // Should resolve Drawables before Padding because we need the layout direction of the
15063        // Drawable to correctly resolve Padding.
15064        if (!areDrawablesResolved()) {
15065            resolveDrawables();
15066        }
15067        if (!isPaddingResolved()) {
15068            resolvePadding();
15069        }
15070        onRtlPropertiesChanged(getLayoutDirection());
15071        return true;
15072    }
15073
15074    /**
15075     * Reset resolution of all RTL related properties.
15076     *
15077     * @hide
15078     */
15079    public void resetRtlProperties() {
15080        resetResolvedLayoutDirection();
15081        resetResolvedTextDirection();
15082        resetResolvedTextAlignment();
15083        resetResolvedPadding();
15084        resetResolvedDrawables();
15085    }
15086
15087    /**
15088     * @see #onScreenStateChanged(int)
15089     */
15090    void dispatchScreenStateChanged(int screenState) {
15091        onScreenStateChanged(screenState);
15092    }
15093
15094    /**
15095     * This method is called whenever the state of the screen this view is
15096     * attached to changes. A state change will usually occurs when the screen
15097     * turns on or off (whether it happens automatically or the user does it
15098     * manually.)
15099     *
15100     * @param screenState The new state of the screen. Can be either
15101     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
15102     */
15103    public void onScreenStateChanged(int screenState) {
15104    }
15105
15106    /**
15107     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15108     */
15109    private boolean hasRtlSupport() {
15110        return mContext.getApplicationInfo().hasRtlSupport();
15111    }
15112
15113    /**
15114     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15115     * RTL not supported)
15116     */
15117    private boolean isRtlCompatibilityMode() {
15118        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15119        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15120    }
15121
15122    /**
15123     * @return true if RTL properties need resolution.
15124     *
15125     */
15126    private boolean needRtlPropertiesResolution() {
15127        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15128    }
15129
15130    /**
15131     * Called when any RTL property (layout direction or text direction or text alignment) has
15132     * been changed.
15133     *
15134     * Subclasses need to override this method to take care of cached information that depends on the
15135     * resolved layout direction, or to inform child views that inherit their layout direction.
15136     *
15137     * The default implementation does nothing.
15138     *
15139     * @param layoutDirection the direction of the layout
15140     *
15141     * @see #LAYOUT_DIRECTION_LTR
15142     * @see #LAYOUT_DIRECTION_RTL
15143     */
15144    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15145    }
15146
15147    /**
15148     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15149     * that the parent directionality can and will be resolved before its children.
15150     *
15151     * @return true if resolution has been done, false otherwise.
15152     *
15153     * @hide
15154     */
15155    public boolean resolveLayoutDirection() {
15156        // Clear any previous layout direction resolution
15157        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15158
15159        if (hasRtlSupport()) {
15160            // Set resolved depending on layout direction
15161            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15162                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15163                case LAYOUT_DIRECTION_INHERIT:
15164                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15165                    // later to get the correct resolved value
15166                    if (!canResolveLayoutDirection()) return false;
15167
15168                    // Parent has not yet resolved, LTR is still the default
15169                    try {
15170                        if (!mParent.isLayoutDirectionResolved()) return false;
15171
15172                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15173                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15174                        }
15175                    } catch (AbstractMethodError e) {
15176                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15177                                " does not fully implement ViewParent", e);
15178                    }
15179                    break;
15180                case LAYOUT_DIRECTION_RTL:
15181                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15182                    break;
15183                case LAYOUT_DIRECTION_LOCALE:
15184                    if((LAYOUT_DIRECTION_RTL ==
15185                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15186                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15187                    }
15188                    break;
15189                default:
15190                    // Nothing to do, LTR by default
15191            }
15192        }
15193
15194        // Set to resolved
15195        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15196        return true;
15197    }
15198
15199    /**
15200     * Check if layout direction resolution can be done.
15201     *
15202     * @return true if layout direction resolution can be done otherwise return false.
15203     */
15204    public boolean canResolveLayoutDirection() {
15205        switch (getRawLayoutDirection()) {
15206            case LAYOUT_DIRECTION_INHERIT:
15207                if (mParent != null) {
15208                    try {
15209                        return mParent.canResolveLayoutDirection();
15210                    } catch (AbstractMethodError e) {
15211                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15212                                " does not fully implement ViewParent", e);
15213                    }
15214                }
15215                return false;
15216
15217            default:
15218                return true;
15219        }
15220    }
15221
15222    /**
15223     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15224     * {@link #onMeasure(int, int)}.
15225     *
15226     * @hide
15227     */
15228    public void resetResolvedLayoutDirection() {
15229        // Reset the current resolved bits
15230        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15231    }
15232
15233    /**
15234     * @return true if the layout direction is inherited.
15235     *
15236     * @hide
15237     */
15238    public boolean isLayoutDirectionInherited() {
15239        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15240    }
15241
15242    /**
15243     * @return true if layout direction has been resolved.
15244     */
15245    public boolean isLayoutDirectionResolved() {
15246        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15247    }
15248
15249    /**
15250     * Return if padding has been resolved
15251     *
15252     * @hide
15253     */
15254    boolean isPaddingResolved() {
15255        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15256    }
15257
15258    /**
15259     * Resolves padding depending on layout direction, if applicable, and
15260     * recomputes internal padding values to adjust for scroll bars.
15261     *
15262     * @hide
15263     */
15264    public void resolvePadding() {
15265        final int resolvedLayoutDirection = getLayoutDirection();
15266
15267        if (!isRtlCompatibilityMode()) {
15268            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15269            // If start / end padding are defined, they will be resolved (hence overriding) to
15270            // left / right or right / left depending on the resolved layout direction.
15271            // If start / end padding are not defined, use the left / right ones.
15272            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15273                Rect padding = sThreadLocal.get();
15274                if (padding == null) {
15275                    padding = new Rect();
15276                    sThreadLocal.set(padding);
15277                }
15278                mBackground.getPadding(padding);
15279                if (!mLeftPaddingDefined) {
15280                    mUserPaddingLeftInitial = padding.left;
15281                }
15282                if (!mRightPaddingDefined) {
15283                    mUserPaddingRightInitial = padding.right;
15284                }
15285            }
15286            switch (resolvedLayoutDirection) {
15287                case LAYOUT_DIRECTION_RTL:
15288                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15289                        mUserPaddingRight = mUserPaddingStart;
15290                    } else {
15291                        mUserPaddingRight = mUserPaddingRightInitial;
15292                    }
15293                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15294                        mUserPaddingLeft = mUserPaddingEnd;
15295                    } else {
15296                        mUserPaddingLeft = mUserPaddingLeftInitial;
15297                    }
15298                    break;
15299                case LAYOUT_DIRECTION_LTR:
15300                default:
15301                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15302                        mUserPaddingLeft = mUserPaddingStart;
15303                    } else {
15304                        mUserPaddingLeft = mUserPaddingLeftInitial;
15305                    }
15306                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15307                        mUserPaddingRight = mUserPaddingEnd;
15308                    } else {
15309                        mUserPaddingRight = mUserPaddingRightInitial;
15310                    }
15311            }
15312
15313            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15314        }
15315
15316        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15317        onRtlPropertiesChanged(resolvedLayoutDirection);
15318
15319        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15320    }
15321
15322    /**
15323     * Reset the resolved layout direction.
15324     *
15325     * @hide
15326     */
15327    public void resetResolvedPadding() {
15328        resetResolvedPaddingInternal();
15329    }
15330
15331    /**
15332     * Used when we only want to reset *this* view's padding and not trigger overrides
15333     * in ViewGroup that reset children too.
15334     */
15335    void resetResolvedPaddingInternal() {
15336        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15337    }
15338
15339    /**
15340     * This is called when the view is detached from a window.  At this point it
15341     * no longer has a surface for drawing.
15342     *
15343     * @see #onAttachedToWindow()
15344     */
15345    @CallSuper
15346    protected void onDetachedFromWindow() {
15347    }
15348
15349    /**
15350     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15351     * after onDetachedFromWindow().
15352     *
15353     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15354     * The super method should be called at the end of the overridden method to ensure
15355     * subclasses are destroyed first
15356     *
15357     * @hide
15358     */
15359    @CallSuper
15360    protected void onDetachedFromWindowInternal() {
15361        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15362        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15363        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15364
15365        removeUnsetPressCallback();
15366        removeLongPressCallback();
15367        removePerformClickCallback();
15368        removeSendViewScrolledAccessibilityEventCallback();
15369        stopNestedScroll();
15370
15371        // Anything that started animating right before detach should already
15372        // be in its final state when re-attached.
15373        jumpDrawablesToCurrentState();
15374
15375        destroyDrawingCache();
15376
15377        cleanupDraw();
15378        mCurrentAnimation = null;
15379    }
15380
15381    private void cleanupDraw() {
15382        resetDisplayList();
15383        if (mAttachInfo != null) {
15384            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15385        }
15386    }
15387
15388    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15389    }
15390
15391    /**
15392     * @return The number of times this view has been attached to a window
15393     */
15394    protected int getWindowAttachCount() {
15395        return mWindowAttachCount;
15396    }
15397
15398    /**
15399     * Retrieve a unique token identifying the window this view is attached to.
15400     * @return Return the window's token for use in
15401     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15402     */
15403    public IBinder getWindowToken() {
15404        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15405    }
15406
15407    /**
15408     * Retrieve the {@link WindowId} for the window this view is
15409     * currently attached to.
15410     */
15411    public WindowId getWindowId() {
15412        if (mAttachInfo == null) {
15413            return null;
15414        }
15415        if (mAttachInfo.mWindowId == null) {
15416            try {
15417                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15418                        mAttachInfo.mWindowToken);
15419                mAttachInfo.mWindowId = new WindowId(
15420                        mAttachInfo.mIWindowId);
15421            } catch (RemoteException e) {
15422            }
15423        }
15424        return mAttachInfo.mWindowId;
15425    }
15426
15427    /**
15428     * Retrieve a unique token identifying the top-level "real" window of
15429     * the window that this view is attached to.  That is, this is like
15430     * {@link #getWindowToken}, except if the window this view in is a panel
15431     * window (attached to another containing window), then the token of
15432     * the containing window is returned instead.
15433     *
15434     * @return Returns the associated window token, either
15435     * {@link #getWindowToken()} or the containing window's token.
15436     */
15437    public IBinder getApplicationWindowToken() {
15438        AttachInfo ai = mAttachInfo;
15439        if (ai != null) {
15440            IBinder appWindowToken = ai.mPanelParentWindowToken;
15441            if (appWindowToken == null) {
15442                appWindowToken = ai.mWindowToken;
15443            }
15444            return appWindowToken;
15445        }
15446        return null;
15447    }
15448
15449    /**
15450     * Gets the logical display to which the view's window has been attached.
15451     *
15452     * @return The logical display, or null if the view is not currently attached to a window.
15453     */
15454    public Display getDisplay() {
15455        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15456    }
15457
15458    /**
15459     * Retrieve private session object this view hierarchy is using to
15460     * communicate with the window manager.
15461     * @return the session object to communicate with the window manager
15462     */
15463    /*package*/ IWindowSession getWindowSession() {
15464        return mAttachInfo != null ? mAttachInfo.mSession : null;
15465    }
15466
15467    /**
15468     * Return the visibility value of the least visible component passed.
15469     */
15470    int combineVisibility(int vis1, int vis2) {
15471        // This works because VISIBLE < INVISIBLE < GONE.
15472        return Math.max(vis1, vis2);
15473    }
15474
15475    /**
15476     * @param info the {@link android.view.View.AttachInfo} to associated with
15477     *        this view
15478     */
15479    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15480        mAttachInfo = info;
15481        if (mOverlay != null) {
15482            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15483        }
15484        mWindowAttachCount++;
15485        // We will need to evaluate the drawable state at least once.
15486        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15487        if (mFloatingTreeObserver != null) {
15488            info.mTreeObserver.merge(mFloatingTreeObserver);
15489            mFloatingTreeObserver = null;
15490        }
15491
15492        registerPendingFrameMetricsObservers();
15493
15494        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15495            mAttachInfo.mScrollContainers.add(this);
15496            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15497        }
15498        // Transfer all pending runnables.
15499        if (mRunQueue != null) {
15500            mRunQueue.executeActions(info.mHandler);
15501            mRunQueue = null;
15502        }
15503        performCollectViewAttributes(mAttachInfo, visibility);
15504        onAttachedToWindow();
15505
15506        ListenerInfo li = mListenerInfo;
15507        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15508                li != null ? li.mOnAttachStateChangeListeners : null;
15509        if (listeners != null && listeners.size() > 0) {
15510            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15511            // perform the dispatching. The iterator is a safe guard against listeners that
15512            // could mutate the list by calling the various add/remove methods. This prevents
15513            // the array from being modified while we iterate it.
15514            for (OnAttachStateChangeListener listener : listeners) {
15515                listener.onViewAttachedToWindow(this);
15516            }
15517        }
15518
15519        int vis = info.mWindowVisibility;
15520        if (vis != GONE) {
15521            onWindowVisibilityChanged(vis);
15522            if (isShown()) {
15523                // Calling onVisibilityChanged directly here since the subtree will also
15524                // receive dispatchAttachedToWindow and this same call
15525                onVisibilityAggregated(vis == VISIBLE);
15526            }
15527        }
15528
15529        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15530        // As all views in the subtree will already receive dispatchAttachedToWindow
15531        // traversing the subtree again here is not desired.
15532        onVisibilityChanged(this, visibility);
15533
15534        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15535            // If nobody has evaluated the drawable state yet, then do it now.
15536            refreshDrawableState();
15537        }
15538        needGlobalAttributesUpdate(false);
15539    }
15540
15541    void dispatchDetachedFromWindow() {
15542        AttachInfo info = mAttachInfo;
15543        if (info != null) {
15544            int vis = info.mWindowVisibility;
15545            if (vis != GONE) {
15546                onWindowVisibilityChanged(GONE);
15547                if (isShown()) {
15548                    // Invoking onVisibilityAggregated directly here since the subtree
15549                    // will also receive detached from window
15550                    onVisibilityAggregated(false);
15551                }
15552            }
15553        }
15554
15555        onDetachedFromWindow();
15556        onDetachedFromWindowInternal();
15557
15558        InputMethodManager imm = InputMethodManager.peekInstance();
15559        if (imm != null) {
15560            imm.onViewDetachedFromWindow(this);
15561        }
15562
15563        ListenerInfo li = mListenerInfo;
15564        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15565                li != null ? li.mOnAttachStateChangeListeners : null;
15566        if (listeners != null && listeners.size() > 0) {
15567            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15568            // perform the dispatching. The iterator is a safe guard against listeners that
15569            // could mutate the list by calling the various add/remove methods. This prevents
15570            // the array from being modified while we iterate it.
15571            for (OnAttachStateChangeListener listener : listeners) {
15572                listener.onViewDetachedFromWindow(this);
15573            }
15574        }
15575
15576        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15577            mAttachInfo.mScrollContainers.remove(this);
15578            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15579        }
15580
15581        mAttachInfo = null;
15582        if (mOverlay != null) {
15583            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15584        }
15585    }
15586
15587    /**
15588     * Cancel any deferred high-level input events that were previously posted to the event queue.
15589     *
15590     * <p>Many views post high-level events such as click handlers to the event queue
15591     * to run deferred in order to preserve a desired user experience - clearing visible
15592     * pressed states before executing, etc. This method will abort any events of this nature
15593     * that are currently in flight.</p>
15594     *
15595     * <p>Custom views that generate their own high-level deferred input events should override
15596     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15597     *
15598     * <p>This will also cancel pending input events for any child views.</p>
15599     *
15600     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15601     * This will not impact newer events posted after this call that may occur as a result of
15602     * lower-level input events still waiting in the queue. If you are trying to prevent
15603     * double-submitted  events for the duration of some sort of asynchronous transaction
15604     * you should also take other steps to protect against unexpected double inputs e.g. calling
15605     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15606     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15607     */
15608    public final void cancelPendingInputEvents() {
15609        dispatchCancelPendingInputEvents();
15610    }
15611
15612    /**
15613     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15614     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15615     */
15616    void dispatchCancelPendingInputEvents() {
15617        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15618        onCancelPendingInputEvents();
15619        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15620            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15621                    " did not call through to super.onCancelPendingInputEvents()");
15622        }
15623    }
15624
15625    /**
15626     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15627     * a parent view.
15628     *
15629     * <p>This method is responsible for removing any pending high-level input events that were
15630     * posted to the event queue to run later. Custom view classes that post their own deferred
15631     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15632     * {@link android.os.Handler} should override this method, call
15633     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15634     * </p>
15635     */
15636    public void onCancelPendingInputEvents() {
15637        removePerformClickCallback();
15638        cancelLongPress();
15639        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
15640    }
15641
15642    /**
15643     * Store this view hierarchy's frozen state into the given container.
15644     *
15645     * @param container The SparseArray in which to save the view's state.
15646     *
15647     * @see #restoreHierarchyState(android.util.SparseArray)
15648     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15649     * @see #onSaveInstanceState()
15650     */
15651    public void saveHierarchyState(SparseArray<Parcelable> container) {
15652        dispatchSaveInstanceState(container);
15653    }
15654
15655    /**
15656     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
15657     * this view and its children. May be overridden to modify how freezing happens to a
15658     * view's children; for example, some views may want to not store state for their children.
15659     *
15660     * @param container The SparseArray in which to save the view's state.
15661     *
15662     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15663     * @see #saveHierarchyState(android.util.SparseArray)
15664     * @see #onSaveInstanceState()
15665     */
15666    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
15667        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
15668            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15669            Parcelable state = onSaveInstanceState();
15670            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15671                throw new IllegalStateException(
15672                        "Derived class did not call super.onSaveInstanceState()");
15673            }
15674            if (state != null) {
15675                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
15676                // + ": " + state);
15677                container.put(mID, state);
15678            }
15679        }
15680    }
15681
15682    /**
15683     * Hook allowing a view to generate a representation of its internal state
15684     * that can later be used to create a new instance with that same state.
15685     * This state should only contain information that is not persistent or can
15686     * not be reconstructed later. For example, you will never store your
15687     * current position on screen because that will be computed again when a
15688     * new instance of the view is placed in its view hierarchy.
15689     * <p>
15690     * Some examples of things you may store here: the current cursor position
15691     * in a text view (but usually not the text itself since that is stored in a
15692     * content provider or other persistent storage), the currently selected
15693     * item in a list view.
15694     *
15695     * @return Returns a Parcelable object containing the view's current dynamic
15696     *         state, or null if there is nothing interesting to save. The
15697     *         default implementation returns null.
15698     * @see #onRestoreInstanceState(android.os.Parcelable)
15699     * @see #saveHierarchyState(android.util.SparseArray)
15700     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15701     * @see #setSaveEnabled(boolean)
15702     */
15703    @CallSuper
15704    protected Parcelable onSaveInstanceState() {
15705        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15706        if (mStartActivityRequestWho != null) {
15707            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
15708            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
15709            return state;
15710        }
15711        return BaseSavedState.EMPTY_STATE;
15712    }
15713
15714    /**
15715     * Restore this view hierarchy's frozen state from the given container.
15716     *
15717     * @param container The SparseArray which holds previously frozen states.
15718     *
15719     * @see #saveHierarchyState(android.util.SparseArray)
15720     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15721     * @see #onRestoreInstanceState(android.os.Parcelable)
15722     */
15723    public void restoreHierarchyState(SparseArray<Parcelable> container) {
15724        dispatchRestoreInstanceState(container);
15725    }
15726
15727    /**
15728     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
15729     * state for this view and its children. May be overridden to modify how restoring
15730     * happens to a view's children; for example, some views may want to not store state
15731     * for their children.
15732     *
15733     * @param container The SparseArray which holds previously saved state.
15734     *
15735     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15736     * @see #restoreHierarchyState(android.util.SparseArray)
15737     * @see #onRestoreInstanceState(android.os.Parcelable)
15738     */
15739    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
15740        if (mID != NO_ID) {
15741            Parcelable state = container.get(mID);
15742            if (state != null) {
15743                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
15744                // + ": " + state);
15745                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15746                onRestoreInstanceState(state);
15747                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15748                    throw new IllegalStateException(
15749                            "Derived class did not call super.onRestoreInstanceState()");
15750                }
15751            }
15752        }
15753    }
15754
15755    /**
15756     * Hook allowing a view to re-apply a representation of its internal state that had previously
15757     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
15758     * null state.
15759     *
15760     * @param state The frozen state that had previously been returned by
15761     *        {@link #onSaveInstanceState}.
15762     *
15763     * @see #onSaveInstanceState()
15764     * @see #restoreHierarchyState(android.util.SparseArray)
15765     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15766     */
15767    @CallSuper
15768    protected void onRestoreInstanceState(Parcelable state) {
15769        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15770        if (state != null && !(state instanceof AbsSavedState)) {
15771            throw new IllegalArgumentException("Wrong state class, expecting View State but "
15772                    + "received " + state.getClass().toString() + " instead. This usually happens "
15773                    + "when two views of different type have the same id in the same hierarchy. "
15774                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
15775                    + "other views do not use the same id.");
15776        }
15777        if (state != null && state instanceof BaseSavedState) {
15778            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
15779        }
15780    }
15781
15782    /**
15783     * <p>Return the time at which the drawing of the view hierarchy started.</p>
15784     *
15785     * @return the drawing start time in milliseconds
15786     */
15787    public long getDrawingTime() {
15788        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
15789    }
15790
15791    /**
15792     * <p>Enables or disables the duplication of the parent's state into this view. When
15793     * duplication is enabled, this view gets its drawable state from its parent rather
15794     * than from its own internal properties.</p>
15795     *
15796     * <p>Note: in the current implementation, setting this property to true after the
15797     * view was added to a ViewGroup might have no effect at all. This property should
15798     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
15799     *
15800     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
15801     * property is enabled, an exception will be thrown.</p>
15802     *
15803     * <p>Note: if the child view uses and updates additional states which are unknown to the
15804     * parent, these states should not be affected by this method.</p>
15805     *
15806     * @param enabled True to enable duplication of the parent's drawable state, false
15807     *                to disable it.
15808     *
15809     * @see #getDrawableState()
15810     * @see #isDuplicateParentStateEnabled()
15811     */
15812    public void setDuplicateParentStateEnabled(boolean enabled) {
15813        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
15814    }
15815
15816    /**
15817     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
15818     *
15819     * @return True if this view's drawable state is duplicated from the parent,
15820     *         false otherwise
15821     *
15822     * @see #getDrawableState()
15823     * @see #setDuplicateParentStateEnabled(boolean)
15824     */
15825    public boolean isDuplicateParentStateEnabled() {
15826        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
15827    }
15828
15829    /**
15830     * <p>Specifies the type of layer backing this view. The layer can be
15831     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15832     * {@link #LAYER_TYPE_HARDWARE}.</p>
15833     *
15834     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15835     * instance that controls how the layer is composed on screen. The following
15836     * properties of the paint are taken into account when composing the layer:</p>
15837     * <ul>
15838     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15839     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15840     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15841     * </ul>
15842     *
15843     * <p>If this view has an alpha value set to < 1.0 by calling
15844     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
15845     * by this view's alpha value.</p>
15846     *
15847     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
15848     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
15849     * for more information on when and how to use layers.</p>
15850     *
15851     * @param layerType The type of layer to use with this view, must be one of
15852     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15853     *        {@link #LAYER_TYPE_HARDWARE}
15854     * @param paint The paint used to compose the layer. This argument is optional
15855     *        and can be null. It is ignored when the layer type is
15856     *        {@link #LAYER_TYPE_NONE}
15857     *
15858     * @see #getLayerType()
15859     * @see #LAYER_TYPE_NONE
15860     * @see #LAYER_TYPE_SOFTWARE
15861     * @see #LAYER_TYPE_HARDWARE
15862     * @see #setAlpha(float)
15863     *
15864     * @attr ref android.R.styleable#View_layerType
15865     */
15866    public void setLayerType(int layerType, @Nullable Paint paint) {
15867        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
15868            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
15869                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
15870        }
15871
15872        boolean typeChanged = mRenderNode.setLayerType(layerType);
15873
15874        if (!typeChanged) {
15875            setLayerPaint(paint);
15876            return;
15877        }
15878
15879        if (layerType != LAYER_TYPE_SOFTWARE) {
15880            // Destroy any previous software drawing cache if present
15881            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
15882            // drawing cache created in View#draw when drawing to a SW canvas.
15883            destroyDrawingCache();
15884        }
15885
15886        mLayerType = layerType;
15887        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
15888        mRenderNode.setLayerPaint(mLayerPaint);
15889
15890        // draw() behaves differently if we are on a layer, so we need to
15891        // invalidate() here
15892        invalidateParentCaches();
15893        invalidate(true);
15894    }
15895
15896    /**
15897     * Updates the {@link Paint} object used with the current layer (used only if the current
15898     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
15899     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
15900     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
15901     * ensure that the view gets redrawn immediately.
15902     *
15903     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15904     * instance that controls how the layer is composed on screen. The following
15905     * properties of the paint are taken into account when composing the layer:</p>
15906     * <ul>
15907     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15908     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15909     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15910     * </ul>
15911     *
15912     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
15913     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
15914     *
15915     * @param paint The paint used to compose the layer. This argument is optional
15916     *        and can be null. It is ignored when the layer type is
15917     *        {@link #LAYER_TYPE_NONE}
15918     *
15919     * @see #setLayerType(int, android.graphics.Paint)
15920     */
15921    public void setLayerPaint(@Nullable Paint paint) {
15922        int layerType = getLayerType();
15923        if (layerType != LAYER_TYPE_NONE) {
15924            mLayerPaint = paint;
15925            if (layerType == LAYER_TYPE_HARDWARE) {
15926                if (mRenderNode.setLayerPaint(paint)) {
15927                    invalidateViewProperty(false, false);
15928                }
15929            } else {
15930                invalidate();
15931            }
15932        }
15933    }
15934
15935    /**
15936     * Indicates what type of layer is currently associated with this view. By default
15937     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
15938     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
15939     * for more information on the different types of layers.
15940     *
15941     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15942     *         {@link #LAYER_TYPE_HARDWARE}
15943     *
15944     * @see #setLayerType(int, android.graphics.Paint)
15945     * @see #buildLayer()
15946     * @see #LAYER_TYPE_NONE
15947     * @see #LAYER_TYPE_SOFTWARE
15948     * @see #LAYER_TYPE_HARDWARE
15949     */
15950    public int getLayerType() {
15951        return mLayerType;
15952    }
15953
15954    /**
15955     * Forces this view's layer to be created and this view to be rendered
15956     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
15957     * invoking this method will have no effect.
15958     *
15959     * This method can for instance be used to render a view into its layer before
15960     * starting an animation. If this view is complex, rendering into the layer
15961     * before starting the animation will avoid skipping frames.
15962     *
15963     * @throws IllegalStateException If this view is not attached to a window
15964     *
15965     * @see #setLayerType(int, android.graphics.Paint)
15966     */
15967    public void buildLayer() {
15968        if (mLayerType == LAYER_TYPE_NONE) return;
15969
15970        final AttachInfo attachInfo = mAttachInfo;
15971        if (attachInfo == null) {
15972            throw new IllegalStateException("This view must be attached to a window first");
15973        }
15974
15975        if (getWidth() == 0 || getHeight() == 0) {
15976            return;
15977        }
15978
15979        switch (mLayerType) {
15980            case LAYER_TYPE_HARDWARE:
15981                updateDisplayListIfDirty();
15982                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
15983                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
15984                }
15985                break;
15986            case LAYER_TYPE_SOFTWARE:
15987                buildDrawingCache(true);
15988                break;
15989        }
15990    }
15991
15992    /**
15993     * Destroys all hardware rendering resources. This method is invoked
15994     * when the system needs to reclaim resources. Upon execution of this
15995     * method, you should free any OpenGL resources created by the view.
15996     *
15997     * Note: you <strong>must</strong> call
15998     * <code>super.destroyHardwareResources()</code> when overriding
15999     * this method.
16000     *
16001     * @hide
16002     */
16003    @CallSuper
16004    protected void destroyHardwareResources() {
16005        // Although the Layer will be destroyed by RenderNode, we want to release
16006        // the staging display list, which is also a signal to RenderNode that it's
16007        // safe to free its copy of the display list as it knows that we will
16008        // push an updated DisplayList if we try to draw again
16009        resetDisplayList();
16010    }
16011
16012    /**
16013     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
16014     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
16015     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
16016     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
16017     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
16018     * null.</p>
16019     *
16020     * <p>Enabling the drawing cache is similar to
16021     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
16022     * acceleration is turned off. When hardware acceleration is turned on, enabling the
16023     * drawing cache has no effect on rendering because the system uses a different mechanism
16024     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
16025     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
16026     * for information on how to enable software and hardware layers.</p>
16027     *
16028     * <p>This API can be used to manually generate
16029     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
16030     * {@link #getDrawingCache()}.</p>
16031     *
16032     * @param enabled true to enable the drawing cache, false otherwise
16033     *
16034     * @see #isDrawingCacheEnabled()
16035     * @see #getDrawingCache()
16036     * @see #buildDrawingCache()
16037     * @see #setLayerType(int, android.graphics.Paint)
16038     */
16039    public void setDrawingCacheEnabled(boolean enabled) {
16040        mCachingFailed = false;
16041        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
16042    }
16043
16044    /**
16045     * <p>Indicates whether the drawing cache is enabled for this view.</p>
16046     *
16047     * @return true if the drawing cache is enabled
16048     *
16049     * @see #setDrawingCacheEnabled(boolean)
16050     * @see #getDrawingCache()
16051     */
16052    @ViewDebug.ExportedProperty(category = "drawing")
16053    public boolean isDrawingCacheEnabled() {
16054        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
16055    }
16056
16057    /**
16058     * Debugging utility which recursively outputs the dirty state of a view and its
16059     * descendants.
16060     *
16061     * @hide
16062     */
16063    @SuppressWarnings({"UnusedDeclaration"})
16064    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
16065        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
16066                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
16067                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
16068                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
16069        if (clear) {
16070            mPrivateFlags &= clearMask;
16071        }
16072        if (this instanceof ViewGroup) {
16073            ViewGroup parent = (ViewGroup) this;
16074            final int count = parent.getChildCount();
16075            for (int i = 0; i < count; i++) {
16076                final View child = parent.getChildAt(i);
16077                child.outputDirtyFlags(indent + "  ", clear, clearMask);
16078            }
16079        }
16080    }
16081
16082    /**
16083     * This method is used by ViewGroup to cause its children to restore or recreate their
16084     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
16085     * to recreate its own display list, which would happen if it went through the normal
16086     * draw/dispatchDraw mechanisms.
16087     *
16088     * @hide
16089     */
16090    protected void dispatchGetDisplayList() {}
16091
16092    /**
16093     * A view that is not attached or hardware accelerated cannot create a display list.
16094     * This method checks these conditions and returns the appropriate result.
16095     *
16096     * @return true if view has the ability to create a display list, false otherwise.
16097     *
16098     * @hide
16099     */
16100    public boolean canHaveDisplayList() {
16101        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
16102    }
16103
16104    /**
16105     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
16106     * @hide
16107     */
16108    @NonNull
16109    public RenderNode updateDisplayListIfDirty() {
16110        final RenderNode renderNode = mRenderNode;
16111        if (!canHaveDisplayList()) {
16112            // can't populate RenderNode, don't try
16113            return renderNode;
16114        }
16115
16116        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16117                || !renderNode.isValid()
16118                || (mRecreateDisplayList)) {
16119            // Don't need to recreate the display list, just need to tell our
16120            // children to restore/recreate theirs
16121            if (renderNode.isValid()
16122                    && !mRecreateDisplayList) {
16123                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16124                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16125                dispatchGetDisplayList();
16126
16127                return renderNode; // no work needed
16128            }
16129
16130            // If we got here, we're recreating it. Mark it as such to ensure that
16131            // we copy in child display lists into ours in drawChild()
16132            mRecreateDisplayList = true;
16133
16134            int width = mRight - mLeft;
16135            int height = mBottom - mTop;
16136            int layerType = getLayerType();
16137
16138            final DisplayListCanvas canvas = renderNode.start(width, height);
16139            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16140
16141            try {
16142                if (layerType == LAYER_TYPE_SOFTWARE) {
16143                    buildDrawingCache(true);
16144                    Bitmap cache = getDrawingCache(true);
16145                    if (cache != null) {
16146                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16147                    }
16148                } else {
16149                    computeScroll();
16150
16151                    canvas.translate(-mScrollX, -mScrollY);
16152                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16153                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16154
16155                    // Fast path for layouts with no backgrounds
16156                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16157                        dispatchDraw(canvas);
16158                        if (mOverlay != null && !mOverlay.isEmpty()) {
16159                            mOverlay.getOverlayView().draw(canvas);
16160                        }
16161                    } else {
16162                        draw(canvas);
16163                    }
16164                }
16165            } finally {
16166                renderNode.end(canvas);
16167                setDisplayListProperties(renderNode);
16168            }
16169        } else {
16170            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16171            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16172        }
16173        return renderNode;
16174    }
16175
16176    private void resetDisplayList() {
16177        if (mRenderNode.isValid()) {
16178            mRenderNode.discardDisplayList();
16179        }
16180
16181        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16182            mBackgroundRenderNode.discardDisplayList();
16183        }
16184    }
16185
16186    /**
16187     * Called when the passed RenderNode is removed from the draw tree
16188     * @hide
16189     */
16190    public void onRenderNodeDetached(RenderNode renderNode) {
16191    }
16192
16193    /**
16194     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16195     *
16196     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16197     *
16198     * @see #getDrawingCache(boolean)
16199     */
16200    public Bitmap getDrawingCache() {
16201        return getDrawingCache(false);
16202    }
16203
16204    /**
16205     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16206     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16207     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16208     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16209     * request the drawing cache by calling this method and draw it on screen if the
16210     * returned bitmap is not null.</p>
16211     *
16212     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16213     * this method will create a bitmap of the same size as this view. Because this bitmap
16214     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16215     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16216     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16217     * size than the view. This implies that your application must be able to handle this
16218     * size.</p>
16219     *
16220     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16221     *        the current density of the screen when the application is in compatibility
16222     *        mode.
16223     *
16224     * @return A bitmap representing this view or null if cache is disabled.
16225     *
16226     * @see #setDrawingCacheEnabled(boolean)
16227     * @see #isDrawingCacheEnabled()
16228     * @see #buildDrawingCache(boolean)
16229     * @see #destroyDrawingCache()
16230     */
16231    public Bitmap getDrawingCache(boolean autoScale) {
16232        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16233            return null;
16234        }
16235        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16236            buildDrawingCache(autoScale);
16237        }
16238        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16239    }
16240
16241    /**
16242     * <p>Frees the resources used by the drawing cache. If you call
16243     * {@link #buildDrawingCache()} manually without calling
16244     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16245     * should cleanup the cache with this method afterwards.</p>
16246     *
16247     * @see #setDrawingCacheEnabled(boolean)
16248     * @see #buildDrawingCache()
16249     * @see #getDrawingCache()
16250     */
16251    public void destroyDrawingCache() {
16252        if (mDrawingCache != null) {
16253            mDrawingCache.recycle();
16254            mDrawingCache = null;
16255        }
16256        if (mUnscaledDrawingCache != null) {
16257            mUnscaledDrawingCache.recycle();
16258            mUnscaledDrawingCache = null;
16259        }
16260    }
16261
16262    /**
16263     * Setting a solid background color for the drawing cache's bitmaps will improve
16264     * performance and memory usage. Note, though that this should only be used if this
16265     * view will always be drawn on top of a solid color.
16266     *
16267     * @param color The background color to use for the drawing cache's bitmap
16268     *
16269     * @see #setDrawingCacheEnabled(boolean)
16270     * @see #buildDrawingCache()
16271     * @see #getDrawingCache()
16272     */
16273    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16274        if (color != mDrawingCacheBackgroundColor) {
16275            mDrawingCacheBackgroundColor = color;
16276            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16277        }
16278    }
16279
16280    /**
16281     * @see #setDrawingCacheBackgroundColor(int)
16282     *
16283     * @return The background color to used for the drawing cache's bitmap
16284     */
16285    @ColorInt
16286    public int getDrawingCacheBackgroundColor() {
16287        return mDrawingCacheBackgroundColor;
16288    }
16289
16290    /**
16291     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16292     *
16293     * @see #buildDrawingCache(boolean)
16294     */
16295    public void buildDrawingCache() {
16296        buildDrawingCache(false);
16297    }
16298
16299    /**
16300     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16301     *
16302     * <p>If you call {@link #buildDrawingCache()} manually without calling
16303     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16304     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16305     *
16306     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16307     * this method will create a bitmap of the same size as this view. Because this bitmap
16308     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16309     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16310     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16311     * size than the view. This implies that your application must be able to handle this
16312     * size.</p>
16313     *
16314     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16315     * you do not need the drawing cache bitmap, calling this method will increase memory
16316     * usage and cause the view to be rendered in software once, thus negatively impacting
16317     * performance.</p>
16318     *
16319     * @see #getDrawingCache()
16320     * @see #destroyDrawingCache()
16321     */
16322    public void buildDrawingCache(boolean autoScale) {
16323        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16324                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16325            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16326                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16327                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16328            }
16329            try {
16330                buildDrawingCacheImpl(autoScale);
16331            } finally {
16332                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16333            }
16334        }
16335    }
16336
16337    /**
16338     * private, internal implementation of buildDrawingCache, used to enable tracing
16339     */
16340    private void buildDrawingCacheImpl(boolean autoScale) {
16341        mCachingFailed = false;
16342
16343        int width = mRight - mLeft;
16344        int height = mBottom - mTop;
16345
16346        final AttachInfo attachInfo = mAttachInfo;
16347        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16348
16349        if (autoScale && scalingRequired) {
16350            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16351            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16352        }
16353
16354        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16355        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16356        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16357
16358        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16359        final long drawingCacheSize =
16360                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16361        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16362            if (width > 0 && height > 0) {
16363                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16364                        + " too large to fit into a software layer (or drawing cache), needs "
16365                        + projectedBitmapSize + " bytes, only "
16366                        + drawingCacheSize + " available");
16367            }
16368            destroyDrawingCache();
16369            mCachingFailed = true;
16370            return;
16371        }
16372
16373        boolean clear = true;
16374        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16375
16376        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16377            Bitmap.Config quality;
16378            if (!opaque) {
16379                // Never pick ARGB_4444 because it looks awful
16380                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16381                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16382                    case DRAWING_CACHE_QUALITY_AUTO:
16383                    case DRAWING_CACHE_QUALITY_LOW:
16384                    case DRAWING_CACHE_QUALITY_HIGH:
16385                    default:
16386                        quality = Bitmap.Config.ARGB_8888;
16387                        break;
16388                }
16389            } else {
16390                // Optimization for translucent windows
16391                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16392                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16393            }
16394
16395            // Try to cleanup memory
16396            if (bitmap != null) bitmap.recycle();
16397
16398            try {
16399                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16400                        width, height, quality);
16401                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16402                if (autoScale) {
16403                    mDrawingCache = bitmap;
16404                } else {
16405                    mUnscaledDrawingCache = bitmap;
16406                }
16407                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16408            } catch (OutOfMemoryError e) {
16409                // If there is not enough memory to create the bitmap cache, just
16410                // ignore the issue as bitmap caches are not required to draw the
16411                // view hierarchy
16412                if (autoScale) {
16413                    mDrawingCache = null;
16414                } else {
16415                    mUnscaledDrawingCache = null;
16416                }
16417                mCachingFailed = true;
16418                return;
16419            }
16420
16421            clear = drawingCacheBackgroundColor != 0;
16422        }
16423
16424        Canvas canvas;
16425        if (attachInfo != null) {
16426            canvas = attachInfo.mCanvas;
16427            if (canvas == null) {
16428                canvas = new Canvas();
16429            }
16430            canvas.setBitmap(bitmap);
16431            // Temporarily clobber the cached Canvas in case one of our children
16432            // is also using a drawing cache. Without this, the children would
16433            // steal the canvas by attaching their own bitmap to it and bad, bad
16434            // thing would happen (invisible views, corrupted drawings, etc.)
16435            attachInfo.mCanvas = null;
16436        } else {
16437            // This case should hopefully never or seldom happen
16438            canvas = new Canvas(bitmap);
16439        }
16440
16441        if (clear) {
16442            bitmap.eraseColor(drawingCacheBackgroundColor);
16443        }
16444
16445        computeScroll();
16446        final int restoreCount = canvas.save();
16447
16448        if (autoScale && scalingRequired) {
16449            final float scale = attachInfo.mApplicationScale;
16450            canvas.scale(scale, scale);
16451        }
16452
16453        canvas.translate(-mScrollX, -mScrollY);
16454
16455        mPrivateFlags |= PFLAG_DRAWN;
16456        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16457                mLayerType != LAYER_TYPE_NONE) {
16458            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16459        }
16460
16461        // Fast path for layouts with no backgrounds
16462        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16463            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16464            dispatchDraw(canvas);
16465            if (mOverlay != null && !mOverlay.isEmpty()) {
16466                mOverlay.getOverlayView().draw(canvas);
16467            }
16468        } else {
16469            draw(canvas);
16470        }
16471
16472        canvas.restoreToCount(restoreCount);
16473        canvas.setBitmap(null);
16474
16475        if (attachInfo != null) {
16476            // Restore the cached Canvas for our siblings
16477            attachInfo.mCanvas = canvas;
16478        }
16479    }
16480
16481    /**
16482     * Create a snapshot of the view into a bitmap.  We should probably make
16483     * some form of this public, but should think about the API.
16484     *
16485     * @hide
16486     */
16487    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16488        int width = mRight - mLeft;
16489        int height = mBottom - mTop;
16490
16491        final AttachInfo attachInfo = mAttachInfo;
16492        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16493        width = (int) ((width * scale) + 0.5f);
16494        height = (int) ((height * scale) + 0.5f);
16495
16496        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16497                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16498        if (bitmap == null) {
16499            throw new OutOfMemoryError();
16500        }
16501
16502        Resources resources = getResources();
16503        if (resources != null) {
16504            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16505        }
16506
16507        Canvas canvas;
16508        if (attachInfo != null) {
16509            canvas = attachInfo.mCanvas;
16510            if (canvas == null) {
16511                canvas = new Canvas();
16512            }
16513            canvas.setBitmap(bitmap);
16514            // Temporarily clobber the cached Canvas in case one of our children
16515            // is also using a drawing cache. Without this, the children would
16516            // steal the canvas by attaching their own bitmap to it and bad, bad
16517            // things would happen (invisible views, corrupted drawings, etc.)
16518            attachInfo.mCanvas = null;
16519        } else {
16520            // This case should hopefully never or seldom happen
16521            canvas = new Canvas(bitmap);
16522        }
16523
16524        if ((backgroundColor & 0xff000000) != 0) {
16525            bitmap.eraseColor(backgroundColor);
16526        }
16527
16528        computeScroll();
16529        final int restoreCount = canvas.save();
16530        canvas.scale(scale, scale);
16531        canvas.translate(-mScrollX, -mScrollY);
16532
16533        // Temporarily remove the dirty mask
16534        int flags = mPrivateFlags;
16535        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16536
16537        // Fast path for layouts with no backgrounds
16538        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16539            dispatchDraw(canvas);
16540            if (mOverlay != null && !mOverlay.isEmpty()) {
16541                mOverlay.getOverlayView().draw(canvas);
16542            }
16543        } else {
16544            draw(canvas);
16545        }
16546
16547        mPrivateFlags = flags;
16548
16549        canvas.restoreToCount(restoreCount);
16550        canvas.setBitmap(null);
16551
16552        if (attachInfo != null) {
16553            // Restore the cached Canvas for our siblings
16554            attachInfo.mCanvas = canvas;
16555        }
16556
16557        return bitmap;
16558    }
16559
16560    /**
16561     * Indicates whether this View is currently in edit mode. A View is usually
16562     * in edit mode when displayed within a developer tool. For instance, if
16563     * this View is being drawn by a visual user interface builder, this method
16564     * should return true.
16565     *
16566     * Subclasses should check the return value of this method to provide
16567     * different behaviors if their normal behavior might interfere with the
16568     * host environment. For instance: the class spawns a thread in its
16569     * constructor, the drawing code relies on device-specific features, etc.
16570     *
16571     * This method is usually checked in the drawing code of custom widgets.
16572     *
16573     * @return True if this View is in edit mode, false otherwise.
16574     */
16575    public boolean isInEditMode() {
16576        return false;
16577    }
16578
16579    /**
16580     * If the View draws content inside its padding and enables fading edges,
16581     * it needs to support padding offsets. Padding offsets are added to the
16582     * fading edges to extend the length of the fade so that it covers pixels
16583     * drawn inside the padding.
16584     *
16585     * Subclasses of this class should override this method if they need
16586     * to draw content inside the padding.
16587     *
16588     * @return True if padding offset must be applied, false otherwise.
16589     *
16590     * @see #getLeftPaddingOffset()
16591     * @see #getRightPaddingOffset()
16592     * @see #getTopPaddingOffset()
16593     * @see #getBottomPaddingOffset()
16594     *
16595     * @since CURRENT
16596     */
16597    protected boolean isPaddingOffsetRequired() {
16598        return false;
16599    }
16600
16601    /**
16602     * Amount by which to extend the left fading region. Called only when
16603     * {@link #isPaddingOffsetRequired()} returns true.
16604     *
16605     * @return The left padding offset in pixels.
16606     *
16607     * @see #isPaddingOffsetRequired()
16608     *
16609     * @since CURRENT
16610     */
16611    protected int getLeftPaddingOffset() {
16612        return 0;
16613    }
16614
16615    /**
16616     * Amount by which to extend the right fading region. Called only when
16617     * {@link #isPaddingOffsetRequired()} returns true.
16618     *
16619     * @return The right padding offset in pixels.
16620     *
16621     * @see #isPaddingOffsetRequired()
16622     *
16623     * @since CURRENT
16624     */
16625    protected int getRightPaddingOffset() {
16626        return 0;
16627    }
16628
16629    /**
16630     * Amount by which to extend the top fading region. Called only when
16631     * {@link #isPaddingOffsetRequired()} returns true.
16632     *
16633     * @return The top padding offset in pixels.
16634     *
16635     * @see #isPaddingOffsetRequired()
16636     *
16637     * @since CURRENT
16638     */
16639    protected int getTopPaddingOffset() {
16640        return 0;
16641    }
16642
16643    /**
16644     * Amount by which to extend the bottom fading region. Called only when
16645     * {@link #isPaddingOffsetRequired()} returns true.
16646     *
16647     * @return The bottom padding offset in pixels.
16648     *
16649     * @see #isPaddingOffsetRequired()
16650     *
16651     * @since CURRENT
16652     */
16653    protected int getBottomPaddingOffset() {
16654        return 0;
16655    }
16656
16657    /**
16658     * @hide
16659     * @param offsetRequired
16660     */
16661    protected int getFadeTop(boolean offsetRequired) {
16662        int top = mPaddingTop;
16663        if (offsetRequired) top += getTopPaddingOffset();
16664        return top;
16665    }
16666
16667    /**
16668     * @hide
16669     * @param offsetRequired
16670     */
16671    protected int getFadeHeight(boolean offsetRequired) {
16672        int padding = mPaddingTop;
16673        if (offsetRequired) padding += getTopPaddingOffset();
16674        return mBottom - mTop - mPaddingBottom - padding;
16675    }
16676
16677    /**
16678     * <p>Indicates whether this view is attached to a hardware accelerated
16679     * window or not.</p>
16680     *
16681     * <p>Even if this method returns true, it does not mean that every call
16682     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
16683     * accelerated {@link android.graphics.Canvas}. For instance, if this view
16684     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
16685     * window is hardware accelerated,
16686     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
16687     * return false, and this method will return true.</p>
16688     *
16689     * @return True if the view is attached to a window and the window is
16690     *         hardware accelerated; false in any other case.
16691     */
16692    @ViewDebug.ExportedProperty(category = "drawing")
16693    public boolean isHardwareAccelerated() {
16694        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
16695    }
16696
16697    /**
16698     * Sets a rectangular area on this view to which the view will be clipped
16699     * when it is drawn. Setting the value to null will remove the clip bounds
16700     * and the view will draw normally, using its full bounds.
16701     *
16702     * @param clipBounds The rectangular area, in the local coordinates of
16703     * this view, to which future drawing operations will be clipped.
16704     */
16705    public void setClipBounds(Rect clipBounds) {
16706        if (clipBounds == mClipBounds
16707                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
16708            return;
16709        }
16710        if (clipBounds != null) {
16711            if (mClipBounds == null) {
16712                mClipBounds = new Rect(clipBounds);
16713            } else {
16714                mClipBounds.set(clipBounds);
16715            }
16716        } else {
16717            mClipBounds = null;
16718        }
16719        mRenderNode.setClipBounds(mClipBounds);
16720        invalidateViewProperty(false, false);
16721    }
16722
16723    /**
16724     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
16725     *
16726     * @return A copy of the current clip bounds if clip bounds are set,
16727     * otherwise null.
16728     */
16729    public Rect getClipBounds() {
16730        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
16731    }
16732
16733
16734    /**
16735     * Populates an output rectangle with the clip bounds of the view,
16736     * returning {@code true} if successful or {@code false} if the view's
16737     * clip bounds are {@code null}.
16738     *
16739     * @param outRect rectangle in which to place the clip bounds of the view
16740     * @return {@code true} if successful or {@code false} if the view's
16741     *         clip bounds are {@code null}
16742     */
16743    public boolean getClipBounds(Rect outRect) {
16744        if (mClipBounds != null) {
16745            outRect.set(mClipBounds);
16746            return true;
16747        }
16748        return false;
16749    }
16750
16751    /**
16752     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
16753     * case of an active Animation being run on the view.
16754     */
16755    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
16756            Animation a, boolean scalingRequired) {
16757        Transformation invalidationTransform;
16758        final int flags = parent.mGroupFlags;
16759        final boolean initialized = a.isInitialized();
16760        if (!initialized) {
16761            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
16762            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
16763            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
16764            onAnimationStart();
16765        }
16766
16767        final Transformation t = parent.getChildTransformation();
16768        boolean more = a.getTransformation(drawingTime, t, 1f);
16769        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
16770            if (parent.mInvalidationTransformation == null) {
16771                parent.mInvalidationTransformation = new Transformation();
16772            }
16773            invalidationTransform = parent.mInvalidationTransformation;
16774            a.getTransformation(drawingTime, invalidationTransform, 1f);
16775        } else {
16776            invalidationTransform = t;
16777        }
16778
16779        if (more) {
16780            if (!a.willChangeBounds()) {
16781                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
16782                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
16783                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
16784                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
16785                    // The child need to draw an animation, potentially offscreen, so
16786                    // make sure we do not cancel invalidate requests
16787                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16788                    parent.invalidate(mLeft, mTop, mRight, mBottom);
16789                }
16790            } else {
16791                if (parent.mInvalidateRegion == null) {
16792                    parent.mInvalidateRegion = new RectF();
16793                }
16794                final RectF region = parent.mInvalidateRegion;
16795                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
16796                        invalidationTransform);
16797
16798                // The child need to draw an animation, potentially offscreen, so
16799                // make sure we do not cancel invalidate requests
16800                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16801
16802                final int left = mLeft + (int) region.left;
16803                final int top = mTop + (int) region.top;
16804                parent.invalidate(left, top, left + (int) (region.width() + .5f),
16805                        top + (int) (region.height() + .5f));
16806            }
16807        }
16808        return more;
16809    }
16810
16811    /**
16812     * This method is called by getDisplayList() when a display list is recorded for a View.
16813     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
16814     */
16815    void setDisplayListProperties(RenderNode renderNode) {
16816        if (renderNode != null) {
16817            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
16818            renderNode.setClipToBounds(mParent instanceof ViewGroup
16819                    && ((ViewGroup) mParent).getClipChildren());
16820
16821            float alpha = 1;
16822            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
16823                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16824                ViewGroup parentVG = (ViewGroup) mParent;
16825                final Transformation t = parentVG.getChildTransformation();
16826                if (parentVG.getChildStaticTransformation(this, t)) {
16827                    final int transformType = t.getTransformationType();
16828                    if (transformType != Transformation.TYPE_IDENTITY) {
16829                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
16830                            alpha = t.getAlpha();
16831                        }
16832                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
16833                            renderNode.setStaticMatrix(t.getMatrix());
16834                        }
16835                    }
16836                }
16837            }
16838            if (mTransformationInfo != null) {
16839                alpha *= getFinalAlpha();
16840                if (alpha < 1) {
16841                    final int multipliedAlpha = (int) (255 * alpha);
16842                    if (onSetAlpha(multipliedAlpha)) {
16843                        alpha = 1;
16844                    }
16845                }
16846                renderNode.setAlpha(alpha);
16847            } else if (alpha < 1) {
16848                renderNode.setAlpha(alpha);
16849            }
16850        }
16851    }
16852
16853    /**
16854     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
16855     *
16856     * This is where the View specializes rendering behavior based on layer type,
16857     * and hardware acceleration.
16858     */
16859    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
16860        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
16861        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
16862         *
16863         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
16864         * HW accelerated, it can't handle drawing RenderNodes.
16865         */
16866        boolean drawingWithRenderNode = mAttachInfo != null
16867                && mAttachInfo.mHardwareAccelerated
16868                && hardwareAcceleratedCanvas;
16869
16870        boolean more = false;
16871        final boolean childHasIdentityMatrix = hasIdentityMatrix();
16872        final int parentFlags = parent.mGroupFlags;
16873
16874        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
16875            parent.getChildTransformation().clear();
16876            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16877        }
16878
16879        Transformation transformToApply = null;
16880        boolean concatMatrix = false;
16881        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
16882        final Animation a = getAnimation();
16883        if (a != null) {
16884            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
16885            concatMatrix = a.willChangeTransformationMatrix();
16886            if (concatMatrix) {
16887                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16888            }
16889            transformToApply = parent.getChildTransformation();
16890        } else {
16891            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
16892                // No longer animating: clear out old animation matrix
16893                mRenderNode.setAnimationMatrix(null);
16894                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16895            }
16896            if (!drawingWithRenderNode
16897                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16898                final Transformation t = parent.getChildTransformation();
16899                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
16900                if (hasTransform) {
16901                    final int transformType = t.getTransformationType();
16902                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
16903                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
16904                }
16905            }
16906        }
16907
16908        concatMatrix |= !childHasIdentityMatrix;
16909
16910        // Sets the flag as early as possible to allow draw() implementations
16911        // to call invalidate() successfully when doing animations
16912        mPrivateFlags |= PFLAG_DRAWN;
16913
16914        if (!concatMatrix &&
16915                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
16916                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
16917                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
16918                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
16919            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
16920            return more;
16921        }
16922        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
16923
16924        if (hardwareAcceleratedCanvas) {
16925            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
16926            // retain the flag's value temporarily in the mRecreateDisplayList flag
16927            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
16928            mPrivateFlags &= ~PFLAG_INVALIDATED;
16929        }
16930
16931        RenderNode renderNode = null;
16932        Bitmap cache = null;
16933        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
16934        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
16935             if (layerType != LAYER_TYPE_NONE) {
16936                 // If not drawing with RenderNode, treat HW layers as SW
16937                 layerType = LAYER_TYPE_SOFTWARE;
16938                 buildDrawingCache(true);
16939            }
16940            cache = getDrawingCache(true);
16941        }
16942
16943        if (drawingWithRenderNode) {
16944            // Delay getting the display list until animation-driven alpha values are
16945            // set up and possibly passed on to the view
16946            renderNode = updateDisplayListIfDirty();
16947            if (!renderNode.isValid()) {
16948                // Uncommon, but possible. If a view is removed from the hierarchy during the call
16949                // to getDisplayList(), the display list will be marked invalid and we should not
16950                // try to use it again.
16951                renderNode = null;
16952                drawingWithRenderNode = false;
16953            }
16954        }
16955
16956        int sx = 0;
16957        int sy = 0;
16958        if (!drawingWithRenderNode) {
16959            computeScroll();
16960            sx = mScrollX;
16961            sy = mScrollY;
16962        }
16963
16964        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
16965        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
16966
16967        int restoreTo = -1;
16968        if (!drawingWithRenderNode || transformToApply != null) {
16969            restoreTo = canvas.save();
16970        }
16971        if (offsetForScroll) {
16972            canvas.translate(mLeft - sx, mTop - sy);
16973        } else {
16974            if (!drawingWithRenderNode) {
16975                canvas.translate(mLeft, mTop);
16976            }
16977            if (scalingRequired) {
16978                if (drawingWithRenderNode) {
16979                    // TODO: Might not need this if we put everything inside the DL
16980                    restoreTo = canvas.save();
16981                }
16982                // mAttachInfo cannot be null, otherwise scalingRequired == false
16983                final float scale = 1.0f / mAttachInfo.mApplicationScale;
16984                canvas.scale(scale, scale);
16985            }
16986        }
16987
16988        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
16989        if (transformToApply != null
16990                || alpha < 1
16991                || !hasIdentityMatrix()
16992                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16993            if (transformToApply != null || !childHasIdentityMatrix) {
16994                int transX = 0;
16995                int transY = 0;
16996
16997                if (offsetForScroll) {
16998                    transX = -sx;
16999                    transY = -sy;
17000                }
17001
17002                if (transformToApply != null) {
17003                    if (concatMatrix) {
17004                        if (drawingWithRenderNode) {
17005                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
17006                        } else {
17007                            // Undo the scroll translation, apply the transformation matrix,
17008                            // then redo the scroll translate to get the correct result.
17009                            canvas.translate(-transX, -transY);
17010                            canvas.concat(transformToApply.getMatrix());
17011                            canvas.translate(transX, transY);
17012                        }
17013                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17014                    }
17015
17016                    float transformAlpha = transformToApply.getAlpha();
17017                    if (transformAlpha < 1) {
17018                        alpha *= transformAlpha;
17019                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17020                    }
17021                }
17022
17023                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
17024                    canvas.translate(-transX, -transY);
17025                    canvas.concat(getMatrix());
17026                    canvas.translate(transX, transY);
17027                }
17028            }
17029
17030            // Deal with alpha if it is or used to be <1
17031            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
17032                if (alpha < 1) {
17033                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17034                } else {
17035                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
17036                }
17037                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
17038                if (!drawingWithDrawingCache) {
17039                    final int multipliedAlpha = (int) (255 * alpha);
17040                    if (!onSetAlpha(multipliedAlpha)) {
17041                        if (drawingWithRenderNode) {
17042                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
17043                        } else if (layerType == LAYER_TYPE_NONE) {
17044                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
17045                                    multipliedAlpha);
17046                        }
17047                    } else {
17048                        // Alpha is handled by the child directly, clobber the layer's alpha
17049                        mPrivateFlags |= PFLAG_ALPHA_SET;
17050                    }
17051                }
17052            }
17053        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17054            onSetAlpha(255);
17055            mPrivateFlags &= ~PFLAG_ALPHA_SET;
17056        }
17057
17058        if (!drawingWithRenderNode) {
17059            // apply clips directly, since RenderNode won't do it for this draw
17060            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
17061                if (offsetForScroll) {
17062                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
17063                } else {
17064                    if (!scalingRequired || cache == null) {
17065                        canvas.clipRect(0, 0, getWidth(), getHeight());
17066                    } else {
17067                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
17068                    }
17069                }
17070            }
17071
17072            if (mClipBounds != null) {
17073                // clip bounds ignore scroll
17074                canvas.clipRect(mClipBounds);
17075            }
17076        }
17077
17078        if (!drawingWithDrawingCache) {
17079            if (drawingWithRenderNode) {
17080                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17081                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17082            } else {
17083                // Fast path for layouts with no backgrounds
17084                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17085                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17086                    dispatchDraw(canvas);
17087                } else {
17088                    draw(canvas);
17089                }
17090            }
17091        } else if (cache != null) {
17092            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17093            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
17094                // no layer paint, use temporary paint to draw bitmap
17095                Paint cachePaint = parent.mCachePaint;
17096                if (cachePaint == null) {
17097                    cachePaint = new Paint();
17098                    cachePaint.setDither(false);
17099                    parent.mCachePaint = cachePaint;
17100                }
17101                cachePaint.setAlpha((int) (alpha * 255));
17102                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
17103            } else {
17104                // use layer paint to draw the bitmap, merging the two alphas, but also restore
17105                int layerPaintAlpha = mLayerPaint.getAlpha();
17106                if (alpha < 1) {
17107                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17108                }
17109                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17110                if (alpha < 1) {
17111                    mLayerPaint.setAlpha(layerPaintAlpha);
17112                }
17113            }
17114        }
17115
17116        if (restoreTo >= 0) {
17117            canvas.restoreToCount(restoreTo);
17118        }
17119
17120        if (a != null && !more) {
17121            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17122                onSetAlpha(255);
17123            }
17124            parent.finishAnimatingView(this, a);
17125        }
17126
17127        if (more && hardwareAcceleratedCanvas) {
17128            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17129                // alpha animations should cause the child to recreate its display list
17130                invalidate(true);
17131            }
17132        }
17133
17134        mRecreateDisplayList = false;
17135
17136        return more;
17137    }
17138
17139    /**
17140     * Manually render this view (and all of its children) to the given Canvas.
17141     * The view must have already done a full layout before this function is
17142     * called.  When implementing a view, implement
17143     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17144     * If you do need to override this method, call the superclass version.
17145     *
17146     * @param canvas The Canvas to which the View is rendered.
17147     */
17148    @CallSuper
17149    public void draw(Canvas canvas) {
17150        final int privateFlags = mPrivateFlags;
17151        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17152                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17153        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17154
17155        /*
17156         * Draw traversal performs several drawing steps which must be executed
17157         * in the appropriate order:
17158         *
17159         *      1. Draw the background
17160         *      2. If necessary, save the canvas' layers to prepare for fading
17161         *      3. Draw view's content
17162         *      4. Draw children
17163         *      5. If necessary, draw the fading edges and restore layers
17164         *      6. Draw decorations (scrollbars for instance)
17165         */
17166
17167        // Step 1, draw the background, if needed
17168        int saveCount;
17169
17170        if (!dirtyOpaque) {
17171            drawBackground(canvas);
17172        }
17173
17174        // skip step 2 & 5 if possible (common case)
17175        final int viewFlags = mViewFlags;
17176        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17177        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17178        if (!verticalEdges && !horizontalEdges) {
17179            // Step 3, draw the content
17180            if (!dirtyOpaque) onDraw(canvas);
17181
17182            // Step 4, draw the children
17183            dispatchDraw(canvas);
17184
17185            // Overlay is part of the content and draws beneath Foreground
17186            if (mOverlay != null && !mOverlay.isEmpty()) {
17187                mOverlay.getOverlayView().dispatchDraw(canvas);
17188            }
17189
17190            // Step 6, draw decorations (foreground, scrollbars)
17191            onDrawForeground(canvas);
17192
17193            // we're done...
17194            return;
17195        }
17196
17197        /*
17198         * Here we do the full fledged routine...
17199         * (this is an uncommon case where speed matters less,
17200         * this is why we repeat some of the tests that have been
17201         * done above)
17202         */
17203
17204        boolean drawTop = false;
17205        boolean drawBottom = false;
17206        boolean drawLeft = false;
17207        boolean drawRight = false;
17208
17209        float topFadeStrength = 0.0f;
17210        float bottomFadeStrength = 0.0f;
17211        float leftFadeStrength = 0.0f;
17212        float rightFadeStrength = 0.0f;
17213
17214        // Step 2, save the canvas' layers
17215        int paddingLeft = mPaddingLeft;
17216
17217        final boolean offsetRequired = isPaddingOffsetRequired();
17218        if (offsetRequired) {
17219            paddingLeft += getLeftPaddingOffset();
17220        }
17221
17222        int left = mScrollX + paddingLeft;
17223        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17224        int top = mScrollY + getFadeTop(offsetRequired);
17225        int bottom = top + getFadeHeight(offsetRequired);
17226
17227        if (offsetRequired) {
17228            right += getRightPaddingOffset();
17229            bottom += getBottomPaddingOffset();
17230        }
17231
17232        final ScrollabilityCache scrollabilityCache = mScrollCache;
17233        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17234        int length = (int) fadeHeight;
17235
17236        // clip the fade length if top and bottom fades overlap
17237        // overlapping fades produce odd-looking artifacts
17238        if (verticalEdges && (top + length > bottom - length)) {
17239            length = (bottom - top) / 2;
17240        }
17241
17242        // also clip horizontal fades if necessary
17243        if (horizontalEdges && (left + length > right - length)) {
17244            length = (right - left) / 2;
17245        }
17246
17247        if (verticalEdges) {
17248            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17249            drawTop = topFadeStrength * fadeHeight > 1.0f;
17250            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17251            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17252        }
17253
17254        if (horizontalEdges) {
17255            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17256            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17257            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17258            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17259        }
17260
17261        saveCount = canvas.getSaveCount();
17262
17263        int solidColor = getSolidColor();
17264        if (solidColor == 0) {
17265            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17266
17267            if (drawTop) {
17268                canvas.saveLayer(left, top, right, top + length, null, flags);
17269            }
17270
17271            if (drawBottom) {
17272                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17273            }
17274
17275            if (drawLeft) {
17276                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17277            }
17278
17279            if (drawRight) {
17280                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17281            }
17282        } else {
17283            scrollabilityCache.setFadeColor(solidColor);
17284        }
17285
17286        // Step 3, draw the content
17287        if (!dirtyOpaque) onDraw(canvas);
17288
17289        // Step 4, draw the children
17290        dispatchDraw(canvas);
17291
17292        // Step 5, draw the fade effect and restore layers
17293        final Paint p = scrollabilityCache.paint;
17294        final Matrix matrix = scrollabilityCache.matrix;
17295        final Shader fade = scrollabilityCache.shader;
17296
17297        if (drawTop) {
17298            matrix.setScale(1, fadeHeight * topFadeStrength);
17299            matrix.postTranslate(left, top);
17300            fade.setLocalMatrix(matrix);
17301            p.setShader(fade);
17302            canvas.drawRect(left, top, right, top + length, p);
17303        }
17304
17305        if (drawBottom) {
17306            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17307            matrix.postRotate(180);
17308            matrix.postTranslate(left, bottom);
17309            fade.setLocalMatrix(matrix);
17310            p.setShader(fade);
17311            canvas.drawRect(left, bottom - length, right, bottom, p);
17312        }
17313
17314        if (drawLeft) {
17315            matrix.setScale(1, fadeHeight * leftFadeStrength);
17316            matrix.postRotate(-90);
17317            matrix.postTranslate(left, top);
17318            fade.setLocalMatrix(matrix);
17319            p.setShader(fade);
17320            canvas.drawRect(left, top, left + length, bottom, p);
17321        }
17322
17323        if (drawRight) {
17324            matrix.setScale(1, fadeHeight * rightFadeStrength);
17325            matrix.postRotate(90);
17326            matrix.postTranslate(right, top);
17327            fade.setLocalMatrix(matrix);
17328            p.setShader(fade);
17329            canvas.drawRect(right - length, top, right, bottom, p);
17330        }
17331
17332        canvas.restoreToCount(saveCount);
17333
17334        // Overlay is part of the content and draws beneath Foreground
17335        if (mOverlay != null && !mOverlay.isEmpty()) {
17336            mOverlay.getOverlayView().dispatchDraw(canvas);
17337        }
17338
17339        // Step 6, draw decorations (foreground, scrollbars)
17340        onDrawForeground(canvas);
17341    }
17342
17343    /**
17344     * Draws the background onto the specified canvas.
17345     *
17346     * @param canvas Canvas on which to draw the background
17347     */
17348    private void drawBackground(Canvas canvas) {
17349        final Drawable background = mBackground;
17350        if (background == null) {
17351            return;
17352        }
17353
17354        setBackgroundBounds();
17355
17356        // Attempt to use a display list if requested.
17357        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17358                && mAttachInfo.mThreadedRenderer != null) {
17359            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17360
17361            final RenderNode renderNode = mBackgroundRenderNode;
17362            if (renderNode != null && renderNode.isValid()) {
17363                setBackgroundRenderNodeProperties(renderNode);
17364                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17365                return;
17366            }
17367        }
17368
17369        final int scrollX = mScrollX;
17370        final int scrollY = mScrollY;
17371        if ((scrollX | scrollY) == 0) {
17372            background.draw(canvas);
17373        } else {
17374            canvas.translate(scrollX, scrollY);
17375            background.draw(canvas);
17376            canvas.translate(-scrollX, -scrollY);
17377        }
17378    }
17379
17380    /**
17381     * Sets the correct background bounds and rebuilds the outline, if needed.
17382     * <p/>
17383     * This is called by LayoutLib.
17384     */
17385    void setBackgroundBounds() {
17386        if (mBackgroundSizeChanged && mBackground != null) {
17387            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17388            mBackgroundSizeChanged = false;
17389            rebuildOutline();
17390        }
17391    }
17392
17393    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17394        renderNode.setTranslationX(mScrollX);
17395        renderNode.setTranslationY(mScrollY);
17396    }
17397
17398    /**
17399     * Creates a new display list or updates the existing display list for the
17400     * specified Drawable.
17401     *
17402     * @param drawable Drawable for which to create a display list
17403     * @param renderNode Existing RenderNode, or {@code null}
17404     * @return A valid display list for the specified drawable
17405     */
17406    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17407        if (renderNode == null) {
17408            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17409        }
17410
17411        final Rect bounds = drawable.getBounds();
17412        final int width = bounds.width();
17413        final int height = bounds.height();
17414        final DisplayListCanvas canvas = renderNode.start(width, height);
17415
17416        // Reverse left/top translation done by drawable canvas, which will
17417        // instead be applied by rendernode's LTRB bounds below. This way, the
17418        // drawable's bounds match with its rendernode bounds and its content
17419        // will lie within those bounds in the rendernode tree.
17420        canvas.translate(-bounds.left, -bounds.top);
17421
17422        try {
17423            drawable.draw(canvas);
17424        } finally {
17425            renderNode.end(canvas);
17426        }
17427
17428        // Set up drawable properties that are view-independent.
17429        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17430        renderNode.setProjectBackwards(drawable.isProjected());
17431        renderNode.setProjectionReceiver(true);
17432        renderNode.setClipToBounds(false);
17433        return renderNode;
17434    }
17435
17436    /**
17437     * Returns the overlay for this view, creating it if it does not yet exist.
17438     * Adding drawables to the overlay will cause them to be displayed whenever
17439     * the view itself is redrawn. Objects in the overlay should be actively
17440     * managed: remove them when they should not be displayed anymore. The
17441     * overlay will always have the same size as its host view.
17442     *
17443     * <p>Note: Overlays do not currently work correctly with {@link
17444     * SurfaceView} or {@link TextureView}; contents in overlays for these
17445     * types of views may not display correctly.</p>
17446     *
17447     * @return The ViewOverlay object for this view.
17448     * @see ViewOverlay
17449     */
17450    public ViewOverlay getOverlay() {
17451        if (mOverlay == null) {
17452            mOverlay = new ViewOverlay(mContext, this);
17453        }
17454        return mOverlay;
17455    }
17456
17457    /**
17458     * Override this if your view is known to always be drawn on top of a solid color background,
17459     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17460     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17461     * should be set to 0xFF.
17462     *
17463     * @see #setVerticalFadingEdgeEnabled(boolean)
17464     * @see #setHorizontalFadingEdgeEnabled(boolean)
17465     *
17466     * @return The known solid color background for this view, or 0 if the color may vary
17467     */
17468    @ViewDebug.ExportedProperty(category = "drawing")
17469    @ColorInt
17470    public int getSolidColor() {
17471        return 0;
17472    }
17473
17474    /**
17475     * Build a human readable string representation of the specified view flags.
17476     *
17477     * @param flags the view flags to convert to a string
17478     * @return a String representing the supplied flags
17479     */
17480    private static String printFlags(int flags) {
17481        String output = "";
17482        int numFlags = 0;
17483        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17484            output += "TAKES_FOCUS";
17485            numFlags++;
17486        }
17487
17488        switch (flags & VISIBILITY_MASK) {
17489        case INVISIBLE:
17490            if (numFlags > 0) {
17491                output += " ";
17492            }
17493            output += "INVISIBLE";
17494            // USELESS HERE numFlags++;
17495            break;
17496        case GONE:
17497            if (numFlags > 0) {
17498                output += " ";
17499            }
17500            output += "GONE";
17501            // USELESS HERE numFlags++;
17502            break;
17503        default:
17504            break;
17505        }
17506        return output;
17507    }
17508
17509    /**
17510     * Build a human readable string representation of the specified private
17511     * view flags.
17512     *
17513     * @param privateFlags the private view flags to convert to a string
17514     * @return a String representing the supplied flags
17515     */
17516    private static String printPrivateFlags(int privateFlags) {
17517        String output = "";
17518        int numFlags = 0;
17519
17520        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17521            output += "WANTS_FOCUS";
17522            numFlags++;
17523        }
17524
17525        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17526            if (numFlags > 0) {
17527                output += " ";
17528            }
17529            output += "FOCUSED";
17530            numFlags++;
17531        }
17532
17533        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17534            if (numFlags > 0) {
17535                output += " ";
17536            }
17537            output += "SELECTED";
17538            numFlags++;
17539        }
17540
17541        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17542            if (numFlags > 0) {
17543                output += " ";
17544            }
17545            output += "IS_ROOT_NAMESPACE";
17546            numFlags++;
17547        }
17548
17549        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17550            if (numFlags > 0) {
17551                output += " ";
17552            }
17553            output += "HAS_BOUNDS";
17554            numFlags++;
17555        }
17556
17557        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17558            if (numFlags > 0) {
17559                output += " ";
17560            }
17561            output += "DRAWN";
17562            // USELESS HERE numFlags++;
17563        }
17564        return output;
17565    }
17566
17567    /**
17568     * <p>Indicates whether or not this view's layout will be requested during
17569     * the next hierarchy layout pass.</p>
17570     *
17571     * @return true if the layout will be forced during next layout pass
17572     */
17573    public boolean isLayoutRequested() {
17574        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17575    }
17576
17577    /**
17578     * Return true if o is a ViewGroup that is laying out using optical bounds.
17579     * @hide
17580     */
17581    public static boolean isLayoutModeOptical(Object o) {
17582        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17583    }
17584
17585    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17586        Insets parentInsets = mParent instanceof View ?
17587                ((View) mParent).getOpticalInsets() : Insets.NONE;
17588        Insets childInsets = getOpticalInsets();
17589        return setFrame(
17590                left   + parentInsets.left - childInsets.left,
17591                top    + parentInsets.top  - childInsets.top,
17592                right  + parentInsets.left + childInsets.right,
17593                bottom + parentInsets.top  + childInsets.bottom);
17594    }
17595
17596    /**
17597     * Assign a size and position to a view and all of its
17598     * descendants
17599     *
17600     * <p>This is the second phase of the layout mechanism.
17601     * (The first is measuring). In this phase, each parent calls
17602     * layout on all of its children to position them.
17603     * This is typically done using the child measurements
17604     * that were stored in the measure pass().</p>
17605     *
17606     * <p>Derived classes should not override this method.
17607     * Derived classes with children should override
17608     * onLayout. In that method, they should
17609     * call layout on each of their children.</p>
17610     *
17611     * @param l Left position, relative to parent
17612     * @param t Top position, relative to parent
17613     * @param r Right position, relative to parent
17614     * @param b Bottom position, relative to parent
17615     */
17616    @SuppressWarnings({"unchecked"})
17617    public void layout(int l, int t, int r, int b) {
17618        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
17619            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
17620            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17621        }
17622
17623        int oldL = mLeft;
17624        int oldT = mTop;
17625        int oldB = mBottom;
17626        int oldR = mRight;
17627
17628        boolean changed = isLayoutModeOptical(mParent) ?
17629                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
17630
17631        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17632            onLayout(changed, l, t, r, b);
17633
17634            if (shouldDrawRoundScrollbar()) {
17635                if(mRoundScrollbarRenderer == null) {
17636                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
17637                }
17638            } else {
17639                mRoundScrollbarRenderer = null;
17640            }
17641
17642            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
17643
17644            ListenerInfo li = mListenerInfo;
17645            if (li != null && li.mOnLayoutChangeListeners != null) {
17646                ArrayList<OnLayoutChangeListener> listenersCopy =
17647                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
17648                int numListeners = listenersCopy.size();
17649                for (int i = 0; i < numListeners; ++i) {
17650                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
17651                }
17652            }
17653        }
17654
17655        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
17656        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
17657    }
17658
17659    /**
17660     * Called from layout when this view should
17661     * assign a size and position to each of its children.
17662     *
17663     * Derived classes with children should override
17664     * this method and call layout on each of
17665     * their children.
17666     * @param changed This is a new size or position for this view
17667     * @param left Left position, relative to parent
17668     * @param top Top position, relative to parent
17669     * @param right Right position, relative to parent
17670     * @param bottom Bottom position, relative to parent
17671     */
17672    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
17673    }
17674
17675    /**
17676     * Assign a size and position to this view.
17677     *
17678     * This is called from layout.
17679     *
17680     * @param left Left position, relative to parent
17681     * @param top Top position, relative to parent
17682     * @param right Right position, relative to parent
17683     * @param bottom Bottom position, relative to parent
17684     * @return true if the new size and position are different than the
17685     *         previous ones
17686     * {@hide}
17687     */
17688    protected boolean setFrame(int left, int top, int right, int bottom) {
17689        boolean changed = false;
17690
17691        if (DBG) {
17692            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
17693                    + right + "," + bottom + ")");
17694        }
17695
17696        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
17697            changed = true;
17698
17699            // Remember our drawn bit
17700            int drawn = mPrivateFlags & PFLAG_DRAWN;
17701
17702            int oldWidth = mRight - mLeft;
17703            int oldHeight = mBottom - mTop;
17704            int newWidth = right - left;
17705            int newHeight = bottom - top;
17706            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
17707
17708            // Invalidate our old position
17709            invalidate(sizeChanged);
17710
17711            mLeft = left;
17712            mTop = top;
17713            mRight = right;
17714            mBottom = bottom;
17715            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
17716
17717            mPrivateFlags |= PFLAG_HAS_BOUNDS;
17718
17719
17720            if (sizeChanged) {
17721                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
17722            }
17723
17724            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
17725                // If we are visible, force the DRAWN bit to on so that
17726                // this invalidate will go through (at least to our parent).
17727                // This is because someone may have invalidated this view
17728                // before this call to setFrame came in, thereby clearing
17729                // the DRAWN bit.
17730                mPrivateFlags |= PFLAG_DRAWN;
17731                invalidate(sizeChanged);
17732                // parent display list may need to be recreated based on a change in the bounds
17733                // of any child
17734                invalidateParentCaches();
17735            }
17736
17737            // Reset drawn bit to original value (invalidate turns it off)
17738            mPrivateFlags |= drawn;
17739
17740            mBackgroundSizeChanged = true;
17741            if (mForegroundInfo != null) {
17742                mForegroundInfo.mBoundsChanged = true;
17743            }
17744
17745            notifySubtreeAccessibilityStateChangedIfNeeded();
17746        }
17747        return changed;
17748    }
17749
17750    /**
17751     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
17752     * @hide
17753     */
17754    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
17755        setFrame(left, top, right, bottom);
17756    }
17757
17758    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
17759        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
17760        if (mOverlay != null) {
17761            mOverlay.getOverlayView().setRight(newWidth);
17762            mOverlay.getOverlayView().setBottom(newHeight);
17763        }
17764        rebuildOutline();
17765    }
17766
17767    /**
17768     * Finalize inflating a view from XML.  This is called as the last phase
17769     * of inflation, after all child views have been added.
17770     *
17771     * <p>Even if the subclass overrides onFinishInflate, they should always be
17772     * sure to call the super method, so that we get called.
17773     */
17774    @CallSuper
17775    protected void onFinishInflate() {
17776    }
17777
17778    /**
17779     * Returns the resources associated with this view.
17780     *
17781     * @return Resources object.
17782     */
17783    public Resources getResources() {
17784        return mResources;
17785    }
17786
17787    /**
17788     * Invalidates the specified Drawable.
17789     *
17790     * @param drawable the drawable to invalidate
17791     */
17792    @Override
17793    public void invalidateDrawable(@NonNull Drawable drawable) {
17794        if (verifyDrawable(drawable)) {
17795            final Rect dirty = drawable.getDirtyBounds();
17796            final int scrollX = mScrollX;
17797            final int scrollY = mScrollY;
17798
17799            invalidate(dirty.left + scrollX, dirty.top + scrollY,
17800                    dirty.right + scrollX, dirty.bottom + scrollY);
17801            rebuildOutline();
17802        }
17803    }
17804
17805    /**
17806     * Schedules an action on a drawable to occur at a specified time.
17807     *
17808     * @param who the recipient of the action
17809     * @param what the action to run on the drawable
17810     * @param when the time at which the action must occur. Uses the
17811     *        {@link SystemClock#uptimeMillis} timebase.
17812     */
17813    @Override
17814    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
17815        if (verifyDrawable(who) && what != null) {
17816            final long delay = when - SystemClock.uptimeMillis();
17817            if (mAttachInfo != null) {
17818                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
17819                        Choreographer.CALLBACK_ANIMATION, what, who,
17820                        Choreographer.subtractFrameDelay(delay));
17821            } else {
17822                // Postpone the runnable until we know
17823                // on which thread it needs to run.
17824                getRunQueue().postDelayed(what, delay);
17825            }
17826        }
17827    }
17828
17829    /**
17830     * Cancels a scheduled action on a drawable.
17831     *
17832     * @param who the recipient of the action
17833     * @param what the action to cancel
17834     */
17835    @Override
17836    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
17837        if (verifyDrawable(who) && what != null) {
17838            if (mAttachInfo != null) {
17839                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17840                        Choreographer.CALLBACK_ANIMATION, what, who);
17841            }
17842            getRunQueue().removeCallbacks(what);
17843        }
17844    }
17845
17846    /**
17847     * Unschedule any events associated with the given Drawable.  This can be
17848     * used when selecting a new Drawable into a view, so that the previous
17849     * one is completely unscheduled.
17850     *
17851     * @param who The Drawable to unschedule.
17852     *
17853     * @see #drawableStateChanged
17854     */
17855    public void unscheduleDrawable(Drawable who) {
17856        if (mAttachInfo != null && who != null) {
17857            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17858                    Choreographer.CALLBACK_ANIMATION, null, who);
17859        }
17860    }
17861
17862    /**
17863     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
17864     * that the View directionality can and will be resolved before its Drawables.
17865     *
17866     * Will call {@link View#onResolveDrawables} when resolution is done.
17867     *
17868     * @hide
17869     */
17870    protected void resolveDrawables() {
17871        // Drawables resolution may need to happen before resolving the layout direction (which is
17872        // done only during the measure() call).
17873        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
17874        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
17875        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
17876        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
17877        // direction to be resolved as its resolved value will be the same as its raw value.
17878        if (!isLayoutDirectionResolved() &&
17879                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
17880            return;
17881        }
17882
17883        final int layoutDirection = isLayoutDirectionResolved() ?
17884                getLayoutDirection() : getRawLayoutDirection();
17885
17886        if (mBackground != null) {
17887            mBackground.setLayoutDirection(layoutDirection);
17888        }
17889        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17890            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
17891        }
17892        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
17893        onResolveDrawables(layoutDirection);
17894    }
17895
17896    boolean areDrawablesResolved() {
17897        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
17898    }
17899
17900    /**
17901     * Called when layout direction has been resolved.
17902     *
17903     * The default implementation does nothing.
17904     *
17905     * @param layoutDirection The resolved layout direction.
17906     *
17907     * @see #LAYOUT_DIRECTION_LTR
17908     * @see #LAYOUT_DIRECTION_RTL
17909     *
17910     * @hide
17911     */
17912    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
17913    }
17914
17915    /**
17916     * @hide
17917     */
17918    protected void resetResolvedDrawables() {
17919        resetResolvedDrawablesInternal();
17920    }
17921
17922    void resetResolvedDrawablesInternal() {
17923        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
17924    }
17925
17926    /**
17927     * If your view subclass is displaying its own Drawable objects, it should
17928     * override this function and return true for any Drawable it is
17929     * displaying.  This allows animations for those drawables to be
17930     * scheduled.
17931     *
17932     * <p>Be sure to call through to the super class when overriding this
17933     * function.
17934     *
17935     * @param who The Drawable to verify.  Return true if it is one you are
17936     *            displaying, else return the result of calling through to the
17937     *            super class.
17938     *
17939     * @return boolean If true than the Drawable is being displayed in the
17940     *         view; else false and it is not allowed to animate.
17941     *
17942     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
17943     * @see #drawableStateChanged()
17944     */
17945    @CallSuper
17946    protected boolean verifyDrawable(@NonNull Drawable who) {
17947        // Avoid verifying the scroll bar drawable so that we don't end up in
17948        // an invalidation loop. This effectively prevents the scroll bar
17949        // drawable from triggering invalidations and scheduling runnables.
17950        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
17951    }
17952
17953    /**
17954     * This function is called whenever the state of the view changes in such
17955     * a way that it impacts the state of drawables being shown.
17956     * <p>
17957     * If the View has a StateListAnimator, it will also be called to run necessary state
17958     * change animations.
17959     * <p>
17960     * Be sure to call through to the superclass when overriding this function.
17961     *
17962     * @see Drawable#setState(int[])
17963     */
17964    @CallSuper
17965    protected void drawableStateChanged() {
17966        final int[] state = getDrawableState();
17967        boolean changed = false;
17968
17969        final Drawable bg = mBackground;
17970        if (bg != null && bg.isStateful()) {
17971            changed |= bg.setState(state);
17972        }
17973
17974        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17975        if (fg != null && fg.isStateful()) {
17976            changed |= fg.setState(state);
17977        }
17978
17979        if (mScrollCache != null) {
17980            final Drawable scrollBar = mScrollCache.scrollBar;
17981            if (scrollBar != null && scrollBar.isStateful()) {
17982                changed |= scrollBar.setState(state)
17983                        && mScrollCache.state != ScrollabilityCache.OFF;
17984            }
17985        }
17986
17987        if (mStateListAnimator != null) {
17988            mStateListAnimator.setState(state);
17989        }
17990
17991        if (changed) {
17992            invalidate();
17993        }
17994    }
17995
17996    /**
17997     * This function is called whenever the view hotspot changes and needs to
17998     * be propagated to drawables or child views managed by the view.
17999     * <p>
18000     * Dispatching to child views is handled by
18001     * {@link #dispatchDrawableHotspotChanged(float, float)}.
18002     * <p>
18003     * Be sure to call through to the superclass when overriding this function.
18004     *
18005     * @param x hotspot x coordinate
18006     * @param y hotspot y coordinate
18007     */
18008    @CallSuper
18009    public void drawableHotspotChanged(float x, float y) {
18010        if (mBackground != null) {
18011            mBackground.setHotspot(x, y);
18012        }
18013        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18014            mForegroundInfo.mDrawable.setHotspot(x, y);
18015        }
18016
18017        dispatchDrawableHotspotChanged(x, y);
18018    }
18019
18020    /**
18021     * Dispatches drawableHotspotChanged to all of this View's children.
18022     *
18023     * @param x hotspot x coordinate
18024     * @param y hotspot y coordinate
18025     * @see #drawableHotspotChanged(float, float)
18026     */
18027    public void dispatchDrawableHotspotChanged(float x, float y) {
18028    }
18029
18030    /**
18031     * Call this to force a view to update its drawable state. This will cause
18032     * drawableStateChanged to be called on this view. Views that are interested
18033     * in the new state should call getDrawableState.
18034     *
18035     * @see #drawableStateChanged
18036     * @see #getDrawableState
18037     */
18038    public void refreshDrawableState() {
18039        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18040        drawableStateChanged();
18041
18042        ViewParent parent = mParent;
18043        if (parent != null) {
18044            parent.childDrawableStateChanged(this);
18045        }
18046    }
18047
18048    /**
18049     * Return an array of resource IDs of the drawable states representing the
18050     * current state of the view.
18051     *
18052     * @return The current drawable state
18053     *
18054     * @see Drawable#setState(int[])
18055     * @see #drawableStateChanged()
18056     * @see #onCreateDrawableState(int)
18057     */
18058    public final int[] getDrawableState() {
18059        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
18060            return mDrawableState;
18061        } else {
18062            mDrawableState = onCreateDrawableState(0);
18063            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
18064            return mDrawableState;
18065        }
18066    }
18067
18068    /**
18069     * Generate the new {@link android.graphics.drawable.Drawable} state for
18070     * this view. This is called by the view
18071     * system when the cached Drawable state is determined to be invalid.  To
18072     * retrieve the current state, you should use {@link #getDrawableState}.
18073     *
18074     * @param extraSpace if non-zero, this is the number of extra entries you
18075     * would like in the returned array in which you can place your own
18076     * states.
18077     *
18078     * @return Returns an array holding the current {@link Drawable} state of
18079     * the view.
18080     *
18081     * @see #mergeDrawableStates(int[], int[])
18082     */
18083    protected int[] onCreateDrawableState(int extraSpace) {
18084        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
18085                mParent instanceof View) {
18086            return ((View) mParent).onCreateDrawableState(extraSpace);
18087        }
18088
18089        int[] drawableState;
18090
18091        int privateFlags = mPrivateFlags;
18092
18093        int viewStateIndex = 0;
18094        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
18095        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
18096        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
18097        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
18098        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
18099        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
18100        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
18101                ThreadedRenderer.isAvailable()) {
18102            // This is set if HW acceleration is requested, even if the current
18103            // process doesn't allow it.  This is just to allow app preview
18104            // windows to better match their app.
18105            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
18106        }
18107        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
18108
18109        final int privateFlags2 = mPrivateFlags2;
18110        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
18111            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
18112        }
18113        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
18114            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
18115        }
18116
18117        drawableState = StateSet.get(viewStateIndex);
18118
18119        //noinspection ConstantIfStatement
18120        if (false) {
18121            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18122            Log.i("View", toString()
18123                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18124                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18125                    + " fo=" + hasFocus()
18126                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18127                    + " wf=" + hasWindowFocus()
18128                    + ": " + Arrays.toString(drawableState));
18129        }
18130
18131        if (extraSpace == 0) {
18132            return drawableState;
18133        }
18134
18135        final int[] fullState;
18136        if (drawableState != null) {
18137            fullState = new int[drawableState.length + extraSpace];
18138            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18139        } else {
18140            fullState = new int[extraSpace];
18141        }
18142
18143        return fullState;
18144    }
18145
18146    /**
18147     * Merge your own state values in <var>additionalState</var> into the base
18148     * state values <var>baseState</var> that were returned by
18149     * {@link #onCreateDrawableState(int)}.
18150     *
18151     * @param baseState The base state values returned by
18152     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18153     * own additional state values.
18154     *
18155     * @param additionalState The additional state values you would like
18156     * added to <var>baseState</var>; this array is not modified.
18157     *
18158     * @return As a convenience, the <var>baseState</var> array you originally
18159     * passed into the function is returned.
18160     *
18161     * @see #onCreateDrawableState(int)
18162     */
18163    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18164        final int N = baseState.length;
18165        int i = N - 1;
18166        while (i >= 0 && baseState[i] == 0) {
18167            i--;
18168        }
18169        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18170        return baseState;
18171    }
18172
18173    /**
18174     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18175     * on all Drawable objects associated with this view.
18176     * <p>
18177     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18178     * attached to this view.
18179     */
18180    @CallSuper
18181    public void jumpDrawablesToCurrentState() {
18182        if (mBackground != null) {
18183            mBackground.jumpToCurrentState();
18184        }
18185        if (mStateListAnimator != null) {
18186            mStateListAnimator.jumpToCurrentState();
18187        }
18188        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18189            mForegroundInfo.mDrawable.jumpToCurrentState();
18190        }
18191    }
18192
18193    /**
18194     * Sets the background color for this view.
18195     * @param color the color of the background
18196     */
18197    @RemotableViewMethod
18198    public void setBackgroundColor(@ColorInt int color) {
18199        if (mBackground instanceof ColorDrawable) {
18200            ((ColorDrawable) mBackground.mutate()).setColor(color);
18201            computeOpaqueFlags();
18202            mBackgroundResource = 0;
18203        } else {
18204            setBackground(new ColorDrawable(color));
18205        }
18206    }
18207
18208    /**
18209     * Set the background to a given resource. The resource should refer to
18210     * a Drawable object or 0 to remove the background.
18211     * @param resid The identifier of the resource.
18212     *
18213     * @attr ref android.R.styleable#View_background
18214     */
18215    @RemotableViewMethod
18216    public void setBackgroundResource(@DrawableRes int resid) {
18217        if (resid != 0 && resid == mBackgroundResource) {
18218            return;
18219        }
18220
18221        Drawable d = null;
18222        if (resid != 0) {
18223            d = mContext.getDrawable(resid);
18224        }
18225        setBackground(d);
18226
18227        mBackgroundResource = resid;
18228    }
18229
18230    /**
18231     * Set the background to a given Drawable, or remove the background. If the
18232     * background has padding, this View's padding is set to the background's
18233     * padding. However, when a background is removed, this View's padding isn't
18234     * touched. If setting the padding is desired, please use
18235     * {@link #setPadding(int, int, int, int)}.
18236     *
18237     * @param background The Drawable to use as the background, or null to remove the
18238     *        background
18239     */
18240    public void setBackground(Drawable background) {
18241        //noinspection deprecation
18242        setBackgroundDrawable(background);
18243    }
18244
18245    /**
18246     * @deprecated use {@link #setBackground(Drawable)} instead
18247     */
18248    @Deprecated
18249    public void setBackgroundDrawable(Drawable background) {
18250        computeOpaqueFlags();
18251
18252        if (background == mBackground) {
18253            return;
18254        }
18255
18256        boolean requestLayout = false;
18257
18258        mBackgroundResource = 0;
18259
18260        /*
18261         * Regardless of whether we're setting a new background or not, we want
18262         * to clear the previous drawable. setVisible first while we still have the callback set.
18263         */
18264        if (mBackground != null) {
18265            if (isAttachedToWindow()) {
18266                mBackground.setVisible(false, false);
18267            }
18268            mBackground.setCallback(null);
18269            unscheduleDrawable(mBackground);
18270        }
18271
18272        if (background != null) {
18273            Rect padding = sThreadLocal.get();
18274            if (padding == null) {
18275                padding = new Rect();
18276                sThreadLocal.set(padding);
18277            }
18278            resetResolvedDrawablesInternal();
18279            background.setLayoutDirection(getLayoutDirection());
18280            if (background.getPadding(padding)) {
18281                resetResolvedPaddingInternal();
18282                switch (background.getLayoutDirection()) {
18283                    case LAYOUT_DIRECTION_RTL:
18284                        mUserPaddingLeftInitial = padding.right;
18285                        mUserPaddingRightInitial = padding.left;
18286                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18287                        break;
18288                    case LAYOUT_DIRECTION_LTR:
18289                    default:
18290                        mUserPaddingLeftInitial = padding.left;
18291                        mUserPaddingRightInitial = padding.right;
18292                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18293                }
18294                mLeftPaddingDefined = false;
18295                mRightPaddingDefined = false;
18296            }
18297
18298            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18299            // if it has a different minimum size, we should layout again
18300            if (mBackground == null
18301                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18302                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18303                requestLayout = true;
18304            }
18305
18306            // Set mBackground before we set this as the callback and start making other
18307            // background drawable state change calls. In particular, the setVisible call below
18308            // can result in drawables attempting to start animations or otherwise invalidate,
18309            // which requires the view set as the callback (us) to recognize the drawable as
18310            // belonging to it as per verifyDrawable.
18311            mBackground = background;
18312            if (background.isStateful()) {
18313                background.setState(getDrawableState());
18314            }
18315            if (isAttachedToWindow()) {
18316                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18317            }
18318
18319            applyBackgroundTint();
18320
18321            // Set callback last, since the view may still be initializing.
18322            background.setCallback(this);
18323
18324            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18325                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18326                requestLayout = true;
18327            }
18328        } else {
18329            /* Remove the background */
18330            mBackground = null;
18331            if ((mViewFlags & WILL_NOT_DRAW) != 0
18332                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18333                mPrivateFlags |= PFLAG_SKIP_DRAW;
18334            }
18335
18336            /*
18337             * When the background is set, we try to apply its padding to this
18338             * View. When the background is removed, we don't touch this View's
18339             * padding. This is noted in the Javadocs. Hence, we don't need to
18340             * requestLayout(), the invalidate() below is sufficient.
18341             */
18342
18343            // The old background's minimum size could have affected this
18344            // View's layout, so let's requestLayout
18345            requestLayout = true;
18346        }
18347
18348        computeOpaqueFlags();
18349
18350        if (requestLayout) {
18351            requestLayout();
18352        }
18353
18354        mBackgroundSizeChanged = true;
18355        invalidate(true);
18356        invalidateOutline();
18357    }
18358
18359    /**
18360     * Gets the background drawable
18361     *
18362     * @return The drawable used as the background for this view, if any.
18363     *
18364     * @see #setBackground(Drawable)
18365     *
18366     * @attr ref android.R.styleable#View_background
18367     */
18368    public Drawable getBackground() {
18369        return mBackground;
18370    }
18371
18372    /**
18373     * Applies a tint to the background drawable. Does not modify the current tint
18374     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18375     * <p>
18376     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18377     * mutate the drawable and apply the specified tint and tint mode using
18378     * {@link Drawable#setTintList(ColorStateList)}.
18379     *
18380     * @param tint the tint to apply, may be {@code null} to clear tint
18381     *
18382     * @attr ref android.R.styleable#View_backgroundTint
18383     * @see #getBackgroundTintList()
18384     * @see Drawable#setTintList(ColorStateList)
18385     */
18386    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18387        if (mBackgroundTint == null) {
18388            mBackgroundTint = new TintInfo();
18389        }
18390        mBackgroundTint.mTintList = tint;
18391        mBackgroundTint.mHasTintList = true;
18392
18393        applyBackgroundTint();
18394    }
18395
18396    /**
18397     * Return the tint applied to the background drawable, if specified.
18398     *
18399     * @return the tint applied to the background drawable
18400     * @attr ref android.R.styleable#View_backgroundTint
18401     * @see #setBackgroundTintList(ColorStateList)
18402     */
18403    @Nullable
18404    public ColorStateList getBackgroundTintList() {
18405        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18406    }
18407
18408    /**
18409     * Specifies the blending mode used to apply the tint specified by
18410     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18411     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18412     *
18413     * @param tintMode the blending mode used to apply the tint, may be
18414     *                 {@code null} to clear tint
18415     * @attr ref android.R.styleable#View_backgroundTintMode
18416     * @see #getBackgroundTintMode()
18417     * @see Drawable#setTintMode(PorterDuff.Mode)
18418     */
18419    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18420        if (mBackgroundTint == null) {
18421            mBackgroundTint = new TintInfo();
18422        }
18423        mBackgroundTint.mTintMode = tintMode;
18424        mBackgroundTint.mHasTintMode = true;
18425
18426        applyBackgroundTint();
18427    }
18428
18429    /**
18430     * Return the blending mode used to apply the tint to the background
18431     * drawable, if specified.
18432     *
18433     * @return the blending mode used to apply the tint to the background
18434     *         drawable
18435     * @attr ref android.R.styleable#View_backgroundTintMode
18436     * @see #setBackgroundTintMode(PorterDuff.Mode)
18437     */
18438    @Nullable
18439    public PorterDuff.Mode getBackgroundTintMode() {
18440        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18441    }
18442
18443    private void applyBackgroundTint() {
18444        if (mBackground != null && mBackgroundTint != null) {
18445            final TintInfo tintInfo = mBackgroundTint;
18446            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18447                mBackground = mBackground.mutate();
18448
18449                if (tintInfo.mHasTintList) {
18450                    mBackground.setTintList(tintInfo.mTintList);
18451                }
18452
18453                if (tintInfo.mHasTintMode) {
18454                    mBackground.setTintMode(tintInfo.mTintMode);
18455                }
18456
18457                // The drawable (or one of its children) may not have been
18458                // stateful before applying the tint, so let's try again.
18459                if (mBackground.isStateful()) {
18460                    mBackground.setState(getDrawableState());
18461                }
18462            }
18463        }
18464    }
18465
18466    /**
18467     * Returns the drawable used as the foreground of this View. The
18468     * foreground drawable, if non-null, is always drawn on top of the view's content.
18469     *
18470     * @return a Drawable or null if no foreground was set
18471     *
18472     * @see #onDrawForeground(Canvas)
18473     */
18474    public Drawable getForeground() {
18475        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18476    }
18477
18478    /**
18479     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18480     *
18481     * @param foreground the Drawable to be drawn on top of the children
18482     *
18483     * @attr ref android.R.styleable#View_foreground
18484     */
18485    public void setForeground(Drawable foreground) {
18486        if (mForegroundInfo == null) {
18487            if (foreground == null) {
18488                // Nothing to do.
18489                return;
18490            }
18491            mForegroundInfo = new ForegroundInfo();
18492        }
18493
18494        if (foreground == mForegroundInfo.mDrawable) {
18495            // Nothing to do
18496            return;
18497        }
18498
18499        if (mForegroundInfo.mDrawable != null) {
18500            if (isAttachedToWindow()) {
18501                mForegroundInfo.mDrawable.setVisible(false, false);
18502            }
18503            mForegroundInfo.mDrawable.setCallback(null);
18504            unscheduleDrawable(mForegroundInfo.mDrawable);
18505        }
18506
18507        mForegroundInfo.mDrawable = foreground;
18508        mForegroundInfo.mBoundsChanged = true;
18509        if (foreground != null) {
18510            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18511                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18512            }
18513            foreground.setLayoutDirection(getLayoutDirection());
18514            if (foreground.isStateful()) {
18515                foreground.setState(getDrawableState());
18516            }
18517            applyForegroundTint();
18518            if (isAttachedToWindow()) {
18519                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18520            }
18521            // Set callback last, since the view may still be initializing.
18522            foreground.setCallback(this);
18523        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18524            mPrivateFlags |= PFLAG_SKIP_DRAW;
18525        }
18526        requestLayout();
18527        invalidate();
18528    }
18529
18530    /**
18531     * Magic bit used to support features of framework-internal window decor implementation details.
18532     * This used to live exclusively in FrameLayout.
18533     *
18534     * @return true if the foreground should draw inside the padding region or false
18535     *         if it should draw inset by the view's padding
18536     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18537     */
18538    public boolean isForegroundInsidePadding() {
18539        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18540    }
18541
18542    /**
18543     * Describes how the foreground is positioned.
18544     *
18545     * @return foreground gravity.
18546     *
18547     * @see #setForegroundGravity(int)
18548     *
18549     * @attr ref android.R.styleable#View_foregroundGravity
18550     */
18551    public int getForegroundGravity() {
18552        return mForegroundInfo != null ? mForegroundInfo.mGravity
18553                : Gravity.START | Gravity.TOP;
18554    }
18555
18556    /**
18557     * Describes how the foreground is positioned. Defaults to START and TOP.
18558     *
18559     * @param gravity see {@link android.view.Gravity}
18560     *
18561     * @see #getForegroundGravity()
18562     *
18563     * @attr ref android.R.styleable#View_foregroundGravity
18564     */
18565    public void setForegroundGravity(int gravity) {
18566        if (mForegroundInfo == null) {
18567            mForegroundInfo = new ForegroundInfo();
18568        }
18569
18570        if (mForegroundInfo.mGravity != gravity) {
18571            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18572                gravity |= Gravity.START;
18573            }
18574
18575            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18576                gravity |= Gravity.TOP;
18577            }
18578
18579            mForegroundInfo.mGravity = gravity;
18580            requestLayout();
18581        }
18582    }
18583
18584    /**
18585     * Applies a tint to the foreground drawable. Does not modify the current tint
18586     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18587     * <p>
18588     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18589     * mutate the drawable and apply the specified tint and tint mode using
18590     * {@link Drawable#setTintList(ColorStateList)}.
18591     *
18592     * @param tint the tint to apply, may be {@code null} to clear tint
18593     *
18594     * @attr ref android.R.styleable#View_foregroundTint
18595     * @see #getForegroundTintList()
18596     * @see Drawable#setTintList(ColorStateList)
18597     */
18598    public void setForegroundTintList(@Nullable ColorStateList tint) {
18599        if (mForegroundInfo == null) {
18600            mForegroundInfo = new ForegroundInfo();
18601        }
18602        if (mForegroundInfo.mTintInfo == null) {
18603            mForegroundInfo.mTintInfo = new TintInfo();
18604        }
18605        mForegroundInfo.mTintInfo.mTintList = tint;
18606        mForegroundInfo.mTintInfo.mHasTintList = true;
18607
18608        applyForegroundTint();
18609    }
18610
18611    /**
18612     * Return the tint applied to the foreground drawable, if specified.
18613     *
18614     * @return the tint applied to the foreground drawable
18615     * @attr ref android.R.styleable#View_foregroundTint
18616     * @see #setForegroundTintList(ColorStateList)
18617     */
18618    @Nullable
18619    public ColorStateList getForegroundTintList() {
18620        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18621                ? mForegroundInfo.mTintInfo.mTintList : null;
18622    }
18623
18624    /**
18625     * Specifies the blending mode used to apply the tint specified by
18626     * {@link #setForegroundTintList(ColorStateList)}} to the background
18627     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18628     *
18629     * @param tintMode the blending mode used to apply the tint, may be
18630     *                 {@code null} to clear tint
18631     * @attr ref android.R.styleable#View_foregroundTintMode
18632     * @see #getForegroundTintMode()
18633     * @see Drawable#setTintMode(PorterDuff.Mode)
18634     */
18635    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18636        if (mForegroundInfo == null) {
18637            mForegroundInfo = new ForegroundInfo();
18638        }
18639        if (mForegroundInfo.mTintInfo == null) {
18640            mForegroundInfo.mTintInfo = new TintInfo();
18641        }
18642        mForegroundInfo.mTintInfo.mTintMode = tintMode;
18643        mForegroundInfo.mTintInfo.mHasTintMode = true;
18644
18645        applyForegroundTint();
18646    }
18647
18648    /**
18649     * Return the blending mode used to apply the tint to the foreground
18650     * drawable, if specified.
18651     *
18652     * @return the blending mode used to apply the tint to the foreground
18653     *         drawable
18654     * @attr ref android.R.styleable#View_foregroundTintMode
18655     * @see #setForegroundTintMode(PorterDuff.Mode)
18656     */
18657    @Nullable
18658    public PorterDuff.Mode getForegroundTintMode() {
18659        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18660                ? mForegroundInfo.mTintInfo.mTintMode : null;
18661    }
18662
18663    private void applyForegroundTint() {
18664        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
18665                && mForegroundInfo.mTintInfo != null) {
18666            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
18667            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18668                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
18669
18670                if (tintInfo.mHasTintList) {
18671                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
18672                }
18673
18674                if (tintInfo.mHasTintMode) {
18675                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
18676                }
18677
18678                // The drawable (or one of its children) may not have been
18679                // stateful before applying the tint, so let's try again.
18680                if (mForegroundInfo.mDrawable.isStateful()) {
18681                    mForegroundInfo.mDrawable.setState(getDrawableState());
18682                }
18683            }
18684        }
18685    }
18686
18687    /**
18688     * Draw any foreground content for this view.
18689     *
18690     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
18691     * drawable or other view-specific decorations. The foreground is drawn on top of the
18692     * primary view content.</p>
18693     *
18694     * @param canvas canvas to draw into
18695     */
18696    public void onDrawForeground(Canvas canvas) {
18697        onDrawScrollIndicators(canvas);
18698        onDrawScrollBars(canvas);
18699
18700        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18701        if (foreground != null) {
18702            if (mForegroundInfo.mBoundsChanged) {
18703                mForegroundInfo.mBoundsChanged = false;
18704                final Rect selfBounds = mForegroundInfo.mSelfBounds;
18705                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
18706
18707                if (mForegroundInfo.mInsidePadding) {
18708                    selfBounds.set(0, 0, getWidth(), getHeight());
18709                } else {
18710                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
18711                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
18712                }
18713
18714                final int ld = getLayoutDirection();
18715                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
18716                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
18717                foreground.setBounds(overlayBounds);
18718            }
18719
18720            foreground.draw(canvas);
18721        }
18722    }
18723
18724    /**
18725     * Sets the padding. The view may add on the space required to display
18726     * the scrollbars, depending on the style and visibility of the scrollbars.
18727     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
18728     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
18729     * from the values set in this call.
18730     *
18731     * @attr ref android.R.styleable#View_padding
18732     * @attr ref android.R.styleable#View_paddingBottom
18733     * @attr ref android.R.styleable#View_paddingLeft
18734     * @attr ref android.R.styleable#View_paddingRight
18735     * @attr ref android.R.styleable#View_paddingTop
18736     * @param left the left padding in pixels
18737     * @param top the top padding in pixels
18738     * @param right the right padding in pixels
18739     * @param bottom the bottom padding in pixels
18740     */
18741    public void setPadding(int left, int top, int right, int bottom) {
18742        resetResolvedPaddingInternal();
18743
18744        mUserPaddingStart = UNDEFINED_PADDING;
18745        mUserPaddingEnd = UNDEFINED_PADDING;
18746
18747        mUserPaddingLeftInitial = left;
18748        mUserPaddingRightInitial = right;
18749
18750        mLeftPaddingDefined = true;
18751        mRightPaddingDefined = true;
18752
18753        internalSetPadding(left, top, right, bottom);
18754    }
18755
18756    /**
18757     * @hide
18758     */
18759    protected void internalSetPadding(int left, int top, int right, int bottom) {
18760        mUserPaddingLeft = left;
18761        mUserPaddingRight = right;
18762        mUserPaddingBottom = bottom;
18763
18764        final int viewFlags = mViewFlags;
18765        boolean changed = false;
18766
18767        // Common case is there are no scroll bars.
18768        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
18769            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
18770                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
18771                        ? 0 : getVerticalScrollbarWidth();
18772                switch (mVerticalScrollbarPosition) {
18773                    case SCROLLBAR_POSITION_DEFAULT:
18774                        if (isLayoutRtl()) {
18775                            left += offset;
18776                        } else {
18777                            right += offset;
18778                        }
18779                        break;
18780                    case SCROLLBAR_POSITION_RIGHT:
18781                        right += offset;
18782                        break;
18783                    case SCROLLBAR_POSITION_LEFT:
18784                        left += offset;
18785                        break;
18786                }
18787            }
18788            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
18789                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
18790                        ? 0 : getHorizontalScrollbarHeight();
18791            }
18792        }
18793
18794        if (mPaddingLeft != left) {
18795            changed = true;
18796            mPaddingLeft = left;
18797        }
18798        if (mPaddingTop != top) {
18799            changed = true;
18800            mPaddingTop = top;
18801        }
18802        if (mPaddingRight != right) {
18803            changed = true;
18804            mPaddingRight = right;
18805        }
18806        if (mPaddingBottom != bottom) {
18807            changed = true;
18808            mPaddingBottom = bottom;
18809        }
18810
18811        if (changed) {
18812            requestLayout();
18813            invalidateOutline();
18814        }
18815    }
18816
18817    /**
18818     * Sets the relative padding. The view may add on the space required to display
18819     * the scrollbars, depending on the style and visibility of the scrollbars.
18820     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
18821     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
18822     * from the values set in this call.
18823     *
18824     * @attr ref android.R.styleable#View_padding
18825     * @attr ref android.R.styleable#View_paddingBottom
18826     * @attr ref android.R.styleable#View_paddingStart
18827     * @attr ref android.R.styleable#View_paddingEnd
18828     * @attr ref android.R.styleable#View_paddingTop
18829     * @param start the start padding in pixels
18830     * @param top the top padding in pixels
18831     * @param end the end padding in pixels
18832     * @param bottom the bottom padding in pixels
18833     */
18834    public void setPaddingRelative(int start, int top, int end, int bottom) {
18835        resetResolvedPaddingInternal();
18836
18837        mUserPaddingStart = start;
18838        mUserPaddingEnd = end;
18839        mLeftPaddingDefined = true;
18840        mRightPaddingDefined = true;
18841
18842        switch(getLayoutDirection()) {
18843            case LAYOUT_DIRECTION_RTL:
18844                mUserPaddingLeftInitial = end;
18845                mUserPaddingRightInitial = start;
18846                internalSetPadding(end, top, start, bottom);
18847                break;
18848            case LAYOUT_DIRECTION_LTR:
18849            default:
18850                mUserPaddingLeftInitial = start;
18851                mUserPaddingRightInitial = end;
18852                internalSetPadding(start, top, end, bottom);
18853        }
18854    }
18855
18856    /**
18857     * Returns the top padding of this view.
18858     *
18859     * @return the top padding in pixels
18860     */
18861    public int getPaddingTop() {
18862        return mPaddingTop;
18863    }
18864
18865    /**
18866     * Returns the bottom padding of this view. If there are inset and enabled
18867     * scrollbars, this value may include the space required to display the
18868     * scrollbars as well.
18869     *
18870     * @return the bottom padding in pixels
18871     */
18872    public int getPaddingBottom() {
18873        return mPaddingBottom;
18874    }
18875
18876    /**
18877     * Returns the left padding of this view. If there are inset and enabled
18878     * scrollbars, this value may include the space required to display the
18879     * scrollbars as well.
18880     *
18881     * @return the left padding in pixels
18882     */
18883    public int getPaddingLeft() {
18884        if (!isPaddingResolved()) {
18885            resolvePadding();
18886        }
18887        return mPaddingLeft;
18888    }
18889
18890    /**
18891     * Returns the start padding of this view depending on its resolved layout direction.
18892     * If there are inset and enabled scrollbars, this value may include the space
18893     * required to display the scrollbars as well.
18894     *
18895     * @return the start padding in pixels
18896     */
18897    public int getPaddingStart() {
18898        if (!isPaddingResolved()) {
18899            resolvePadding();
18900        }
18901        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18902                mPaddingRight : mPaddingLeft;
18903    }
18904
18905    /**
18906     * Returns the right padding of this view. If there are inset and enabled
18907     * scrollbars, this value may include the space required to display the
18908     * scrollbars as well.
18909     *
18910     * @return the right padding in pixels
18911     */
18912    public int getPaddingRight() {
18913        if (!isPaddingResolved()) {
18914            resolvePadding();
18915        }
18916        return mPaddingRight;
18917    }
18918
18919    /**
18920     * Returns the end padding of this view depending on its resolved layout direction.
18921     * If there are inset and enabled scrollbars, this value may include the space
18922     * required to display the scrollbars as well.
18923     *
18924     * @return the end padding in pixels
18925     */
18926    public int getPaddingEnd() {
18927        if (!isPaddingResolved()) {
18928            resolvePadding();
18929        }
18930        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18931                mPaddingLeft : mPaddingRight;
18932    }
18933
18934    /**
18935     * Return if the padding has been set through relative values
18936     * {@link #setPaddingRelative(int, int, int, int)} or through
18937     * @attr ref android.R.styleable#View_paddingStart or
18938     * @attr ref android.R.styleable#View_paddingEnd
18939     *
18940     * @return true if the padding is relative or false if it is not.
18941     */
18942    public boolean isPaddingRelative() {
18943        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
18944    }
18945
18946    Insets computeOpticalInsets() {
18947        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
18948    }
18949
18950    /**
18951     * @hide
18952     */
18953    public void resetPaddingToInitialValues() {
18954        if (isRtlCompatibilityMode()) {
18955            mPaddingLeft = mUserPaddingLeftInitial;
18956            mPaddingRight = mUserPaddingRightInitial;
18957            return;
18958        }
18959        if (isLayoutRtl()) {
18960            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
18961            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
18962        } else {
18963            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
18964            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
18965        }
18966    }
18967
18968    /**
18969     * @hide
18970     */
18971    public Insets getOpticalInsets() {
18972        if (mLayoutInsets == null) {
18973            mLayoutInsets = computeOpticalInsets();
18974        }
18975        return mLayoutInsets;
18976    }
18977
18978    /**
18979     * Set this view's optical insets.
18980     *
18981     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
18982     * property. Views that compute their own optical insets should call it as part of measurement.
18983     * This method does not request layout. If you are setting optical insets outside of
18984     * measure/layout itself you will want to call requestLayout() yourself.
18985     * </p>
18986     * @hide
18987     */
18988    public void setOpticalInsets(Insets insets) {
18989        mLayoutInsets = insets;
18990    }
18991
18992    /**
18993     * Changes the selection state of this view. A view can be selected or not.
18994     * Note that selection is not the same as focus. Views are typically
18995     * selected in the context of an AdapterView like ListView or GridView;
18996     * the selected view is the view that is highlighted.
18997     *
18998     * @param selected true if the view must be selected, false otherwise
18999     */
19000    public void setSelected(boolean selected) {
19001        //noinspection DoubleNegation
19002        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
19003            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
19004            if (!selected) resetPressedState();
19005            invalidate(true);
19006            refreshDrawableState();
19007            dispatchSetSelected(selected);
19008            if (selected) {
19009                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
19010            } else {
19011                notifyViewAccessibilityStateChangedIfNeeded(
19012                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
19013            }
19014        }
19015    }
19016
19017    /**
19018     * Dispatch setSelected to all of this View's children.
19019     *
19020     * @see #setSelected(boolean)
19021     *
19022     * @param selected The new selected state
19023     */
19024    protected void dispatchSetSelected(boolean selected) {
19025    }
19026
19027    /**
19028     * Indicates the selection state of this view.
19029     *
19030     * @return true if the view is selected, false otherwise
19031     */
19032    @ViewDebug.ExportedProperty
19033    public boolean isSelected() {
19034        return (mPrivateFlags & PFLAG_SELECTED) != 0;
19035    }
19036
19037    /**
19038     * Changes the activated state of this view. A view can be activated or not.
19039     * Note that activation is not the same as selection.  Selection is
19040     * a transient property, representing the view (hierarchy) the user is
19041     * currently interacting with.  Activation is a longer-term state that the
19042     * user can move views in and out of.  For example, in a list view with
19043     * single or multiple selection enabled, the views in the current selection
19044     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
19045     * here.)  The activated state is propagated down to children of the view it
19046     * is set on.
19047     *
19048     * @param activated true if the view must be activated, false otherwise
19049     */
19050    public void setActivated(boolean activated) {
19051        //noinspection DoubleNegation
19052        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
19053            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
19054            invalidate(true);
19055            refreshDrawableState();
19056            dispatchSetActivated(activated);
19057        }
19058    }
19059
19060    /**
19061     * Dispatch setActivated to all of this View's children.
19062     *
19063     * @see #setActivated(boolean)
19064     *
19065     * @param activated The new activated state
19066     */
19067    protected void dispatchSetActivated(boolean activated) {
19068    }
19069
19070    /**
19071     * Indicates the activation state of this view.
19072     *
19073     * @return true if the view is activated, false otherwise
19074     */
19075    @ViewDebug.ExportedProperty
19076    public boolean isActivated() {
19077        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
19078    }
19079
19080    /**
19081     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
19082     * observer can be used to get notifications when global events, like
19083     * layout, happen.
19084     *
19085     * The returned ViewTreeObserver observer is not guaranteed to remain
19086     * valid for the lifetime of this View. If the caller of this method keeps
19087     * a long-lived reference to ViewTreeObserver, it should always check for
19088     * the return value of {@link ViewTreeObserver#isAlive()}.
19089     *
19090     * @return The ViewTreeObserver for this view's hierarchy.
19091     */
19092    public ViewTreeObserver getViewTreeObserver() {
19093        if (mAttachInfo != null) {
19094            return mAttachInfo.mTreeObserver;
19095        }
19096        if (mFloatingTreeObserver == null) {
19097            mFloatingTreeObserver = new ViewTreeObserver();
19098        }
19099        return mFloatingTreeObserver;
19100    }
19101
19102    /**
19103     * <p>Finds the topmost view in the current view hierarchy.</p>
19104     *
19105     * @return the topmost view containing this view
19106     */
19107    public View getRootView() {
19108        if (mAttachInfo != null) {
19109            final View v = mAttachInfo.mRootView;
19110            if (v != null) {
19111                return v;
19112            }
19113        }
19114
19115        View parent = this;
19116
19117        while (parent.mParent != null && parent.mParent instanceof View) {
19118            parent = (View) parent.mParent;
19119        }
19120
19121        return parent;
19122    }
19123
19124    /**
19125     * Transforms a motion event from view-local coordinates to on-screen
19126     * coordinates.
19127     *
19128     * @param ev the view-local motion event
19129     * @return false if the transformation could not be applied
19130     * @hide
19131     */
19132    public boolean toGlobalMotionEvent(MotionEvent ev) {
19133        final AttachInfo info = mAttachInfo;
19134        if (info == null) {
19135            return false;
19136        }
19137
19138        final Matrix m = info.mTmpMatrix;
19139        m.set(Matrix.IDENTITY_MATRIX);
19140        transformMatrixToGlobal(m);
19141        ev.transform(m);
19142        return true;
19143    }
19144
19145    /**
19146     * Transforms a motion event from on-screen coordinates to view-local
19147     * coordinates.
19148     *
19149     * @param ev the on-screen motion event
19150     * @return false if the transformation could not be applied
19151     * @hide
19152     */
19153    public boolean toLocalMotionEvent(MotionEvent ev) {
19154        final AttachInfo info = mAttachInfo;
19155        if (info == null) {
19156            return false;
19157        }
19158
19159        final Matrix m = info.mTmpMatrix;
19160        m.set(Matrix.IDENTITY_MATRIX);
19161        transformMatrixToLocal(m);
19162        ev.transform(m);
19163        return true;
19164    }
19165
19166    /**
19167     * Modifies the input matrix such that it maps view-local coordinates to
19168     * on-screen coordinates.
19169     *
19170     * @param m input matrix to modify
19171     * @hide
19172     */
19173    public void transformMatrixToGlobal(Matrix m) {
19174        final ViewParent parent = mParent;
19175        if (parent instanceof View) {
19176            final View vp = (View) parent;
19177            vp.transformMatrixToGlobal(m);
19178            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19179        } else if (parent instanceof ViewRootImpl) {
19180            final ViewRootImpl vr = (ViewRootImpl) parent;
19181            vr.transformMatrixToGlobal(m);
19182            m.preTranslate(0, -vr.mCurScrollY);
19183        }
19184
19185        m.preTranslate(mLeft, mTop);
19186
19187        if (!hasIdentityMatrix()) {
19188            m.preConcat(getMatrix());
19189        }
19190    }
19191
19192    /**
19193     * Modifies the input matrix such that it maps on-screen coordinates to
19194     * view-local coordinates.
19195     *
19196     * @param m input matrix to modify
19197     * @hide
19198     */
19199    public void transformMatrixToLocal(Matrix m) {
19200        final ViewParent parent = mParent;
19201        if (parent instanceof View) {
19202            final View vp = (View) parent;
19203            vp.transformMatrixToLocal(m);
19204            m.postTranslate(vp.mScrollX, vp.mScrollY);
19205        } else if (parent instanceof ViewRootImpl) {
19206            final ViewRootImpl vr = (ViewRootImpl) parent;
19207            vr.transformMatrixToLocal(m);
19208            m.postTranslate(0, vr.mCurScrollY);
19209        }
19210
19211        m.postTranslate(-mLeft, -mTop);
19212
19213        if (!hasIdentityMatrix()) {
19214            m.postConcat(getInverseMatrix());
19215        }
19216    }
19217
19218    /**
19219     * @hide
19220     */
19221    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19222            @ViewDebug.IntToString(from = 0, to = "x"),
19223            @ViewDebug.IntToString(from = 1, to = "y")
19224    })
19225    public int[] getLocationOnScreen() {
19226        int[] location = new int[2];
19227        getLocationOnScreen(location);
19228        return location;
19229    }
19230
19231    /**
19232     * <p>Computes the coordinates of this view on the screen. The argument
19233     * must be an array of two integers. After the method returns, the array
19234     * contains the x and y location in that order.</p>
19235     *
19236     * @param outLocation an array of two integers in which to hold the coordinates
19237     */
19238    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19239        getLocationInWindow(outLocation);
19240
19241        final AttachInfo info = mAttachInfo;
19242        if (info != null) {
19243            outLocation[0] += info.mWindowLeft;
19244            outLocation[1] += info.mWindowTop;
19245        }
19246    }
19247
19248    /**
19249     * <p>Computes the coordinates of this view in its window. The argument
19250     * must be an array of two integers. After the method returns, the array
19251     * contains the x and y location in that order.</p>
19252     *
19253     * @param outLocation an array of two integers in which to hold the coordinates
19254     */
19255    public void getLocationInWindow(@Size(2) int[] outLocation) {
19256        if (outLocation == null || outLocation.length < 2) {
19257            throw new IllegalArgumentException("outLocation must be an array of two integers");
19258        }
19259
19260        outLocation[0] = 0;
19261        outLocation[1] = 0;
19262
19263        transformFromViewToWindowSpace(outLocation);
19264    }
19265
19266    /** @hide */
19267    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19268        if (inOutLocation == null || inOutLocation.length < 2) {
19269            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19270        }
19271
19272        if (mAttachInfo == null) {
19273            // When the view is not attached to a window, this method does not make sense
19274            inOutLocation[0] = inOutLocation[1] = 0;
19275            return;
19276        }
19277
19278        float position[] = mAttachInfo.mTmpTransformLocation;
19279        position[0] = inOutLocation[0];
19280        position[1] = inOutLocation[1];
19281
19282        if (!hasIdentityMatrix()) {
19283            getMatrix().mapPoints(position);
19284        }
19285
19286        position[0] += mLeft;
19287        position[1] += mTop;
19288
19289        ViewParent viewParent = mParent;
19290        while (viewParent instanceof View) {
19291            final View view = (View) viewParent;
19292
19293            position[0] -= view.mScrollX;
19294            position[1] -= view.mScrollY;
19295
19296            if (!view.hasIdentityMatrix()) {
19297                view.getMatrix().mapPoints(position);
19298            }
19299
19300            position[0] += view.mLeft;
19301            position[1] += view.mTop;
19302
19303            viewParent = view.mParent;
19304         }
19305
19306        if (viewParent instanceof ViewRootImpl) {
19307            // *cough*
19308            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19309            position[1] -= vr.mCurScrollY;
19310        }
19311
19312        inOutLocation[0] = Math.round(position[0]);
19313        inOutLocation[1] = Math.round(position[1]);
19314    }
19315
19316    /**
19317     * {@hide}
19318     * @param id the id of the view to be found
19319     * @return the view of the specified id, null if cannot be found
19320     */
19321    protected View findViewTraversal(@IdRes int id) {
19322        if (id == mID) {
19323            return this;
19324        }
19325        return null;
19326    }
19327
19328    /**
19329     * {@hide}
19330     * @param tag the tag of the view to be found
19331     * @return the view of specified tag, null if cannot be found
19332     */
19333    protected View findViewWithTagTraversal(Object tag) {
19334        if (tag != null && tag.equals(mTag)) {
19335            return this;
19336        }
19337        return null;
19338    }
19339
19340    /**
19341     * {@hide}
19342     * @param predicate The predicate to evaluate.
19343     * @param childToSkip If not null, ignores this child during the recursive traversal.
19344     * @return The first view that matches the predicate or null.
19345     */
19346    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19347        if (predicate.apply(this)) {
19348            return this;
19349        }
19350        return null;
19351    }
19352
19353    /**
19354     * Look for a child view with the given id.  If this view has the given
19355     * id, return this view.
19356     *
19357     * @param id The id to search for.
19358     * @return The view that has the given id in the hierarchy or null
19359     */
19360    @Nullable
19361    public final View findViewById(@IdRes int id) {
19362        if (id < 0) {
19363            return null;
19364        }
19365        return findViewTraversal(id);
19366    }
19367
19368    /**
19369     * Finds a view by its unuque and stable accessibility id.
19370     *
19371     * @param accessibilityId The searched accessibility id.
19372     * @return The found view.
19373     */
19374    final View findViewByAccessibilityId(int accessibilityId) {
19375        if (accessibilityId < 0) {
19376            return null;
19377        }
19378        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19379        if (view != null) {
19380            return view.includeForAccessibility() ? view : null;
19381        }
19382        return null;
19383    }
19384
19385    /**
19386     * Performs the traversal to find a view by its unuque and stable accessibility id.
19387     *
19388     * <strong>Note:</strong>This method does not stop at the root namespace
19389     * boundary since the user can touch the screen at an arbitrary location
19390     * potentially crossing the root namespace bounday which will send an
19391     * accessibility event to accessibility services and they should be able
19392     * to obtain the event source. Also accessibility ids are guaranteed to be
19393     * unique in the window.
19394     *
19395     * @param accessibilityId The accessibility id.
19396     * @return The found view.
19397     *
19398     * @hide
19399     */
19400    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19401        if (getAccessibilityViewId() == accessibilityId) {
19402            return this;
19403        }
19404        return null;
19405    }
19406
19407    /**
19408     * Look for a child view with the given tag.  If this view has the given
19409     * tag, return this view.
19410     *
19411     * @param tag The tag to search for, using "tag.equals(getTag())".
19412     * @return The View that has the given tag in the hierarchy or null
19413     */
19414    public final View findViewWithTag(Object tag) {
19415        if (tag == null) {
19416            return null;
19417        }
19418        return findViewWithTagTraversal(tag);
19419    }
19420
19421    /**
19422     * {@hide}
19423     * Look for a child view that matches the specified predicate.
19424     * If this view matches the predicate, return this view.
19425     *
19426     * @param predicate The predicate to evaluate.
19427     * @return The first view that matches the predicate or null.
19428     */
19429    public final View findViewByPredicate(Predicate<View> predicate) {
19430        return findViewByPredicateTraversal(predicate, null);
19431    }
19432
19433    /**
19434     * {@hide}
19435     * Look for a child view that matches the specified predicate,
19436     * starting with the specified view and its descendents and then
19437     * recusively searching the ancestors and siblings of that view
19438     * until this view is reached.
19439     *
19440     * This method is useful in cases where the predicate does not match
19441     * a single unique view (perhaps multiple views use the same id)
19442     * and we are trying to find the view that is "closest" in scope to the
19443     * starting view.
19444     *
19445     * @param start The view to start from.
19446     * @param predicate The predicate to evaluate.
19447     * @return The first view that matches the predicate or null.
19448     */
19449    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19450        View childToSkip = null;
19451        for (;;) {
19452            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19453            if (view != null || start == this) {
19454                return view;
19455            }
19456
19457            ViewParent parent = start.getParent();
19458            if (parent == null || !(parent instanceof View)) {
19459                return null;
19460            }
19461
19462            childToSkip = start;
19463            start = (View) parent;
19464        }
19465    }
19466
19467    /**
19468     * Sets the identifier for this view. The identifier does not have to be
19469     * unique in this view's hierarchy. The identifier should be a positive
19470     * number.
19471     *
19472     * @see #NO_ID
19473     * @see #getId()
19474     * @see #findViewById(int)
19475     *
19476     * @param id a number used to identify the view
19477     *
19478     * @attr ref android.R.styleable#View_id
19479     */
19480    public void setId(@IdRes int id) {
19481        mID = id;
19482        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19483            mID = generateViewId();
19484        }
19485    }
19486
19487    /**
19488     * {@hide}
19489     *
19490     * @param isRoot true if the view belongs to the root namespace, false
19491     *        otherwise
19492     */
19493    public void setIsRootNamespace(boolean isRoot) {
19494        if (isRoot) {
19495            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19496        } else {
19497            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19498        }
19499    }
19500
19501    /**
19502     * {@hide}
19503     *
19504     * @return true if the view belongs to the root namespace, false otherwise
19505     */
19506    public boolean isRootNamespace() {
19507        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19508    }
19509
19510    /**
19511     * Returns this view's identifier.
19512     *
19513     * @return a positive integer used to identify the view or {@link #NO_ID}
19514     *         if the view has no ID
19515     *
19516     * @see #setId(int)
19517     * @see #findViewById(int)
19518     * @attr ref android.R.styleable#View_id
19519     */
19520    @IdRes
19521    @ViewDebug.CapturedViewProperty
19522    public int getId() {
19523        return mID;
19524    }
19525
19526    /**
19527     * Returns this view's tag.
19528     *
19529     * @return the Object stored in this view as a tag, or {@code null} if not
19530     *         set
19531     *
19532     * @see #setTag(Object)
19533     * @see #getTag(int)
19534     */
19535    @ViewDebug.ExportedProperty
19536    public Object getTag() {
19537        return mTag;
19538    }
19539
19540    /**
19541     * Sets the tag associated with this view. A tag can be used to mark
19542     * a view in its hierarchy and does not have to be unique within the
19543     * hierarchy. Tags can also be used to store data within a view without
19544     * resorting to another data structure.
19545     *
19546     * @param tag an Object to tag the view with
19547     *
19548     * @see #getTag()
19549     * @see #setTag(int, Object)
19550     */
19551    public void setTag(final Object tag) {
19552        mTag = tag;
19553    }
19554
19555    /**
19556     * Returns the tag associated with this view and the specified key.
19557     *
19558     * @param key The key identifying the tag
19559     *
19560     * @return the Object stored in this view as a tag, or {@code null} if not
19561     *         set
19562     *
19563     * @see #setTag(int, Object)
19564     * @see #getTag()
19565     */
19566    public Object getTag(int key) {
19567        if (mKeyedTags != null) return mKeyedTags.get(key);
19568        return null;
19569    }
19570
19571    /**
19572     * Sets a tag associated with this view and a key. A tag can be used
19573     * to mark a view in its hierarchy and does not have to be unique within
19574     * the hierarchy. Tags can also be used to store data within a view
19575     * without resorting to another data structure.
19576     *
19577     * The specified key should be an id declared in the resources of the
19578     * application to ensure it is unique (see the <a
19579     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19580     * Keys identified as belonging to
19581     * the Android framework or not associated with any package will cause
19582     * an {@link IllegalArgumentException} to be thrown.
19583     *
19584     * @param key The key identifying the tag
19585     * @param tag An Object to tag the view with
19586     *
19587     * @throws IllegalArgumentException If they specified key is not valid
19588     *
19589     * @see #setTag(Object)
19590     * @see #getTag(int)
19591     */
19592    public void setTag(int key, final Object tag) {
19593        // If the package id is 0x00 or 0x01, it's either an undefined package
19594        // or a framework id
19595        if ((key >>> 24) < 2) {
19596            throw new IllegalArgumentException("The key must be an application-specific "
19597                    + "resource id.");
19598        }
19599
19600        setKeyedTag(key, tag);
19601    }
19602
19603    /**
19604     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
19605     * framework id.
19606     *
19607     * @hide
19608     */
19609    public void setTagInternal(int key, Object tag) {
19610        if ((key >>> 24) != 0x1) {
19611            throw new IllegalArgumentException("The key must be a framework-specific "
19612                    + "resource id.");
19613        }
19614
19615        setKeyedTag(key, tag);
19616    }
19617
19618    private void setKeyedTag(int key, Object tag) {
19619        if (mKeyedTags == null) {
19620            mKeyedTags = new SparseArray<Object>(2);
19621        }
19622
19623        mKeyedTags.put(key, tag);
19624    }
19625
19626    /**
19627     * Prints information about this view in the log output, with the tag
19628     * {@link #VIEW_LOG_TAG}.
19629     *
19630     * @hide
19631     */
19632    public void debug() {
19633        debug(0);
19634    }
19635
19636    /**
19637     * Prints information about this view in the log output, with the tag
19638     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
19639     * indentation defined by the <code>depth</code>.
19640     *
19641     * @param depth the indentation level
19642     *
19643     * @hide
19644     */
19645    protected void debug(int depth) {
19646        String output = debugIndent(depth - 1);
19647
19648        output += "+ " + this;
19649        int id = getId();
19650        if (id != -1) {
19651            output += " (id=" + id + ")";
19652        }
19653        Object tag = getTag();
19654        if (tag != null) {
19655            output += " (tag=" + tag + ")";
19656        }
19657        Log.d(VIEW_LOG_TAG, output);
19658
19659        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
19660            output = debugIndent(depth) + " FOCUSED";
19661            Log.d(VIEW_LOG_TAG, output);
19662        }
19663
19664        output = debugIndent(depth);
19665        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
19666                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
19667                + "} ";
19668        Log.d(VIEW_LOG_TAG, output);
19669
19670        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
19671                || mPaddingBottom != 0) {
19672            output = debugIndent(depth);
19673            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
19674                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
19675            Log.d(VIEW_LOG_TAG, output);
19676        }
19677
19678        output = debugIndent(depth);
19679        output += "mMeasureWidth=" + mMeasuredWidth +
19680                " mMeasureHeight=" + mMeasuredHeight;
19681        Log.d(VIEW_LOG_TAG, output);
19682
19683        output = debugIndent(depth);
19684        if (mLayoutParams == null) {
19685            output += "BAD! no layout params";
19686        } else {
19687            output = mLayoutParams.debug(output);
19688        }
19689        Log.d(VIEW_LOG_TAG, output);
19690
19691        output = debugIndent(depth);
19692        output += "flags={";
19693        output += View.printFlags(mViewFlags);
19694        output += "}";
19695        Log.d(VIEW_LOG_TAG, output);
19696
19697        output = debugIndent(depth);
19698        output += "privateFlags={";
19699        output += View.printPrivateFlags(mPrivateFlags);
19700        output += "}";
19701        Log.d(VIEW_LOG_TAG, output);
19702    }
19703
19704    /**
19705     * Creates a string of whitespaces used for indentation.
19706     *
19707     * @param depth the indentation level
19708     * @return a String containing (depth * 2 + 3) * 2 white spaces
19709     *
19710     * @hide
19711     */
19712    protected static String debugIndent(int depth) {
19713        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
19714        for (int i = 0; i < (depth * 2) + 3; i++) {
19715            spaces.append(' ').append(' ');
19716        }
19717        return spaces.toString();
19718    }
19719
19720    /**
19721     * <p>Return the offset of the widget's text baseline from the widget's top
19722     * boundary. If this widget does not support baseline alignment, this
19723     * method returns -1. </p>
19724     *
19725     * @return the offset of the baseline within the widget's bounds or -1
19726     *         if baseline alignment is not supported
19727     */
19728    @ViewDebug.ExportedProperty(category = "layout")
19729    public int getBaseline() {
19730        return -1;
19731    }
19732
19733    /**
19734     * Returns whether the view hierarchy is currently undergoing a layout pass. This
19735     * information is useful to avoid situations such as calling {@link #requestLayout()} during
19736     * a layout pass.
19737     *
19738     * @return whether the view hierarchy is currently undergoing a layout pass
19739     */
19740    public boolean isInLayout() {
19741        ViewRootImpl viewRoot = getViewRootImpl();
19742        return (viewRoot != null && viewRoot.isInLayout());
19743    }
19744
19745    /**
19746     * Call this when something has changed which has invalidated the
19747     * layout of this view. This will schedule a layout pass of the view
19748     * tree. This should not be called while the view hierarchy is currently in a layout
19749     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
19750     * end of the current layout pass (and then layout will run again) or after the current
19751     * frame is drawn and the next layout occurs.
19752     *
19753     * <p>Subclasses which override this method should call the superclass method to
19754     * handle possible request-during-layout errors correctly.</p>
19755     */
19756    @CallSuper
19757    public void requestLayout() {
19758        if (mMeasureCache != null) mMeasureCache.clear();
19759
19760        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
19761            // Only trigger request-during-layout logic if this is the view requesting it,
19762            // not the views in its parent hierarchy
19763            ViewRootImpl viewRoot = getViewRootImpl();
19764            if (viewRoot != null && viewRoot.isInLayout()) {
19765                if (!viewRoot.requestLayoutDuringLayout(this)) {
19766                    return;
19767                }
19768            }
19769            mAttachInfo.mViewRequestingLayout = this;
19770        }
19771
19772        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19773        mPrivateFlags |= PFLAG_INVALIDATED;
19774
19775        if (mParent != null && !mParent.isLayoutRequested()) {
19776            mParent.requestLayout();
19777        }
19778        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
19779            mAttachInfo.mViewRequestingLayout = null;
19780        }
19781    }
19782
19783    /**
19784     * Forces this view to be laid out during the next layout pass.
19785     * This method does not call requestLayout() or forceLayout()
19786     * on the parent.
19787     */
19788    public void forceLayout() {
19789        if (mMeasureCache != null) mMeasureCache.clear();
19790
19791        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19792        mPrivateFlags |= PFLAG_INVALIDATED;
19793    }
19794
19795    /**
19796     * <p>
19797     * This is called to find out how big a view should be. The parent
19798     * supplies constraint information in the width and height parameters.
19799     * </p>
19800     *
19801     * <p>
19802     * The actual measurement work of a view is performed in
19803     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
19804     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
19805     * </p>
19806     *
19807     *
19808     * @param widthMeasureSpec Horizontal space requirements as imposed by the
19809     *        parent
19810     * @param heightMeasureSpec Vertical space requirements as imposed by the
19811     *        parent
19812     *
19813     * @see #onMeasure(int, int)
19814     */
19815    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
19816        boolean optical = isLayoutModeOptical(this);
19817        if (optical != isLayoutModeOptical(mParent)) {
19818            Insets insets = getOpticalInsets();
19819            int oWidth  = insets.left + insets.right;
19820            int oHeight = insets.top  + insets.bottom;
19821            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
19822            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
19823        }
19824
19825        // Suppress sign extension for the low bytes
19826        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
19827        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
19828
19829        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19830
19831        // Optimize layout by avoiding an extra EXACTLY pass when the view is
19832        // already measured as the correct size. In API 23 and below, this
19833        // extra pass is required to make LinearLayout re-distribute weight.
19834        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
19835                || heightMeasureSpec != mOldHeightMeasureSpec;
19836        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
19837                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
19838        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
19839                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
19840        final boolean needsLayout = specChanged
19841                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
19842
19843        if (forceLayout || needsLayout) {
19844            // first clears the measured dimension flag
19845            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
19846
19847            resolveRtlPropertiesIfNeeded();
19848
19849            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
19850            if (cacheIndex < 0 || sIgnoreMeasureCache) {
19851                // measure ourselves, this should set the measured dimension flag back
19852                onMeasure(widthMeasureSpec, heightMeasureSpec);
19853                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19854            } else {
19855                long value = mMeasureCache.valueAt(cacheIndex);
19856                // Casting a long to int drops the high 32 bits, no mask needed
19857                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
19858                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19859            }
19860
19861            // flag not set, setMeasuredDimension() was not invoked, we raise
19862            // an exception to warn the developer
19863            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
19864                throw new IllegalStateException("View with id " + getId() + ": "
19865                        + getClass().getName() + "#onMeasure() did not set the"
19866                        + " measured dimension by calling"
19867                        + " setMeasuredDimension()");
19868            }
19869
19870            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
19871        }
19872
19873        mOldWidthMeasureSpec = widthMeasureSpec;
19874        mOldHeightMeasureSpec = heightMeasureSpec;
19875
19876        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
19877                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
19878    }
19879
19880    /**
19881     * <p>
19882     * Measure the view and its content to determine the measured width and the
19883     * measured height. This method is invoked by {@link #measure(int, int)} and
19884     * should be overridden by subclasses to provide accurate and efficient
19885     * measurement of their contents.
19886     * </p>
19887     *
19888     * <p>
19889     * <strong>CONTRACT:</strong> When overriding this method, you
19890     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
19891     * measured width and height of this view. Failure to do so will trigger an
19892     * <code>IllegalStateException</code>, thrown by
19893     * {@link #measure(int, int)}. Calling the superclass'
19894     * {@link #onMeasure(int, int)} is a valid use.
19895     * </p>
19896     *
19897     * <p>
19898     * The base class implementation of measure defaults to the background size,
19899     * unless a larger size is allowed by the MeasureSpec. Subclasses should
19900     * override {@link #onMeasure(int, int)} to provide better measurements of
19901     * their content.
19902     * </p>
19903     *
19904     * <p>
19905     * If this method is overridden, it is the subclass's responsibility to make
19906     * sure the measured height and width are at least the view's minimum height
19907     * and width ({@link #getSuggestedMinimumHeight()} and
19908     * {@link #getSuggestedMinimumWidth()}).
19909     * </p>
19910     *
19911     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
19912     *                         The requirements are encoded with
19913     *                         {@link android.view.View.MeasureSpec}.
19914     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
19915     *                         The requirements are encoded with
19916     *                         {@link android.view.View.MeasureSpec}.
19917     *
19918     * @see #getMeasuredWidth()
19919     * @see #getMeasuredHeight()
19920     * @see #setMeasuredDimension(int, int)
19921     * @see #getSuggestedMinimumHeight()
19922     * @see #getSuggestedMinimumWidth()
19923     * @see android.view.View.MeasureSpec#getMode(int)
19924     * @see android.view.View.MeasureSpec#getSize(int)
19925     */
19926    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19927        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
19928                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
19929    }
19930
19931    /**
19932     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
19933     * measured width and measured height. Failing to do so will trigger an
19934     * exception at measurement time.</p>
19935     *
19936     * @param measuredWidth The measured width of this view.  May be a complex
19937     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19938     * {@link #MEASURED_STATE_TOO_SMALL}.
19939     * @param measuredHeight The measured height of this view.  May be a complex
19940     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19941     * {@link #MEASURED_STATE_TOO_SMALL}.
19942     */
19943    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
19944        boolean optical = isLayoutModeOptical(this);
19945        if (optical != isLayoutModeOptical(mParent)) {
19946            Insets insets = getOpticalInsets();
19947            int opticalWidth  = insets.left + insets.right;
19948            int opticalHeight = insets.top  + insets.bottom;
19949
19950            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
19951            measuredHeight += optical ? opticalHeight : -opticalHeight;
19952        }
19953        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
19954    }
19955
19956    /**
19957     * Sets the measured dimension without extra processing for things like optical bounds.
19958     * Useful for reapplying consistent values that have already been cooked with adjustments
19959     * for optical bounds, etc. such as those from the measurement cache.
19960     *
19961     * @param measuredWidth The measured width of this view.  May be a complex
19962     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19963     * {@link #MEASURED_STATE_TOO_SMALL}.
19964     * @param measuredHeight The measured height of this view.  May be a complex
19965     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19966     * {@link #MEASURED_STATE_TOO_SMALL}.
19967     */
19968    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
19969        mMeasuredWidth = measuredWidth;
19970        mMeasuredHeight = measuredHeight;
19971
19972        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
19973    }
19974
19975    /**
19976     * Merge two states as returned by {@link #getMeasuredState()}.
19977     * @param curState The current state as returned from a view or the result
19978     * of combining multiple views.
19979     * @param newState The new view state to combine.
19980     * @return Returns a new integer reflecting the combination of the two
19981     * states.
19982     */
19983    public static int combineMeasuredStates(int curState, int newState) {
19984        return curState | newState;
19985    }
19986
19987    /**
19988     * Version of {@link #resolveSizeAndState(int, int, int)}
19989     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
19990     */
19991    public static int resolveSize(int size, int measureSpec) {
19992        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
19993    }
19994
19995    /**
19996     * Utility to reconcile a desired size and state, with constraints imposed
19997     * by a MeasureSpec. Will take the desired size, unless a different size
19998     * is imposed by the constraints. The returned value is a compound integer,
19999     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
20000     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
20001     * resulting size is smaller than the size the view wants to be.
20002     *
20003     * @param size How big the view wants to be.
20004     * @param measureSpec Constraints imposed by the parent.
20005     * @param childMeasuredState Size information bit mask for the view's
20006     *                           children.
20007     * @return Size information bit mask as defined by
20008     *         {@link #MEASURED_SIZE_MASK} and
20009     *         {@link #MEASURED_STATE_TOO_SMALL}.
20010     */
20011    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
20012        final int specMode = MeasureSpec.getMode(measureSpec);
20013        final int specSize = MeasureSpec.getSize(measureSpec);
20014        final int result;
20015        switch (specMode) {
20016            case MeasureSpec.AT_MOST:
20017                if (specSize < size) {
20018                    result = specSize | MEASURED_STATE_TOO_SMALL;
20019                } else {
20020                    result = size;
20021                }
20022                break;
20023            case MeasureSpec.EXACTLY:
20024                result = specSize;
20025                break;
20026            case MeasureSpec.UNSPECIFIED:
20027            default:
20028                result = size;
20029        }
20030        return result | (childMeasuredState & MEASURED_STATE_MASK);
20031    }
20032
20033    /**
20034     * Utility to return a default size. Uses the supplied size if the
20035     * MeasureSpec imposed no constraints. Will get larger if allowed
20036     * by the MeasureSpec.
20037     *
20038     * @param size Default size for this view
20039     * @param measureSpec Constraints imposed by the parent
20040     * @return The size this view should be.
20041     */
20042    public static int getDefaultSize(int size, int measureSpec) {
20043        int result = size;
20044        int specMode = MeasureSpec.getMode(measureSpec);
20045        int specSize = MeasureSpec.getSize(measureSpec);
20046
20047        switch (specMode) {
20048        case MeasureSpec.UNSPECIFIED:
20049            result = size;
20050            break;
20051        case MeasureSpec.AT_MOST:
20052        case MeasureSpec.EXACTLY:
20053            result = specSize;
20054            break;
20055        }
20056        return result;
20057    }
20058
20059    /**
20060     * Returns the suggested minimum height that the view should use. This
20061     * returns the maximum of the view's minimum height
20062     * and the background's minimum height
20063     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
20064     * <p>
20065     * When being used in {@link #onMeasure(int, int)}, the caller should still
20066     * ensure the returned height is within the requirements of the parent.
20067     *
20068     * @return The suggested minimum height of the view.
20069     */
20070    protected int getSuggestedMinimumHeight() {
20071        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
20072
20073    }
20074
20075    /**
20076     * Returns the suggested minimum width that the view should use. This
20077     * returns the maximum of the view's minimum width
20078     * and the background's minimum width
20079     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
20080     * <p>
20081     * When being used in {@link #onMeasure(int, int)}, the caller should still
20082     * ensure the returned width is within the requirements of the parent.
20083     *
20084     * @return The suggested minimum width of the view.
20085     */
20086    protected int getSuggestedMinimumWidth() {
20087        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
20088    }
20089
20090    /**
20091     * Returns the minimum height of the view.
20092     *
20093     * @return the minimum height the view will try to be.
20094     *
20095     * @see #setMinimumHeight(int)
20096     *
20097     * @attr ref android.R.styleable#View_minHeight
20098     */
20099    public int getMinimumHeight() {
20100        return mMinHeight;
20101    }
20102
20103    /**
20104     * Sets the minimum height of the view. It is not guaranteed the view will
20105     * be able to achieve this minimum height (for example, if its parent layout
20106     * constrains it with less available height).
20107     *
20108     * @param minHeight The minimum height the view will try to be.
20109     *
20110     * @see #getMinimumHeight()
20111     *
20112     * @attr ref android.R.styleable#View_minHeight
20113     */
20114    @RemotableViewMethod
20115    public void setMinimumHeight(int minHeight) {
20116        mMinHeight = minHeight;
20117        requestLayout();
20118    }
20119
20120    /**
20121     * Returns the minimum width of the view.
20122     *
20123     * @return the minimum width the view will try to be.
20124     *
20125     * @see #setMinimumWidth(int)
20126     *
20127     * @attr ref android.R.styleable#View_minWidth
20128     */
20129    public int getMinimumWidth() {
20130        return mMinWidth;
20131    }
20132
20133    /**
20134     * Sets the minimum width of the view. It is not guaranteed the view will
20135     * be able to achieve this minimum width (for example, if its parent layout
20136     * constrains it with less available width).
20137     *
20138     * @param minWidth The minimum width the view will try to be.
20139     *
20140     * @see #getMinimumWidth()
20141     *
20142     * @attr ref android.R.styleable#View_minWidth
20143     */
20144    public void setMinimumWidth(int minWidth) {
20145        mMinWidth = minWidth;
20146        requestLayout();
20147
20148    }
20149
20150    /**
20151     * Get the animation currently associated with this view.
20152     *
20153     * @return The animation that is currently playing or
20154     *         scheduled to play for this view.
20155     */
20156    public Animation getAnimation() {
20157        return mCurrentAnimation;
20158    }
20159
20160    /**
20161     * Start the specified animation now.
20162     *
20163     * @param animation the animation to start now
20164     */
20165    public void startAnimation(Animation animation) {
20166        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20167        setAnimation(animation);
20168        invalidateParentCaches();
20169        invalidate(true);
20170    }
20171
20172    /**
20173     * Cancels any animations for this view.
20174     */
20175    public void clearAnimation() {
20176        if (mCurrentAnimation != null) {
20177            mCurrentAnimation.detach();
20178        }
20179        mCurrentAnimation = null;
20180        invalidateParentIfNeeded();
20181    }
20182
20183    /**
20184     * Sets the next animation to play for this view.
20185     * If you want the animation to play immediately, use
20186     * {@link #startAnimation(android.view.animation.Animation)} instead.
20187     * This method provides allows fine-grained
20188     * control over the start time and invalidation, but you
20189     * must make sure that 1) the animation has a start time set, and
20190     * 2) the view's parent (which controls animations on its children)
20191     * will be invalidated when the animation is supposed to
20192     * start.
20193     *
20194     * @param animation The next animation, or null.
20195     */
20196    public void setAnimation(Animation animation) {
20197        mCurrentAnimation = animation;
20198
20199        if (animation != null) {
20200            // If the screen is off assume the animation start time is now instead of
20201            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20202            // would cause the animation to start when the screen turns back on
20203            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20204                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20205                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20206            }
20207            animation.reset();
20208        }
20209    }
20210
20211    /**
20212     * Invoked by a parent ViewGroup to notify the start of the animation
20213     * currently associated with this view. If you override this method,
20214     * always call super.onAnimationStart();
20215     *
20216     * @see #setAnimation(android.view.animation.Animation)
20217     * @see #getAnimation()
20218     */
20219    @CallSuper
20220    protected void onAnimationStart() {
20221        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20222    }
20223
20224    /**
20225     * Invoked by a parent ViewGroup to notify the end of the animation
20226     * currently associated with this view. If you override this method,
20227     * always call super.onAnimationEnd();
20228     *
20229     * @see #setAnimation(android.view.animation.Animation)
20230     * @see #getAnimation()
20231     */
20232    @CallSuper
20233    protected void onAnimationEnd() {
20234        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20235    }
20236
20237    /**
20238     * Invoked if there is a Transform that involves alpha. Subclass that can
20239     * draw themselves with the specified alpha should return true, and then
20240     * respect that alpha when their onDraw() is called. If this returns false
20241     * then the view may be redirected to draw into an offscreen buffer to
20242     * fulfill the request, which will look fine, but may be slower than if the
20243     * subclass handles it internally. The default implementation returns false.
20244     *
20245     * @param alpha The alpha (0..255) to apply to the view's drawing
20246     * @return true if the view can draw with the specified alpha.
20247     */
20248    protected boolean onSetAlpha(int alpha) {
20249        return false;
20250    }
20251
20252    /**
20253     * This is used by the RootView to perform an optimization when
20254     * the view hierarchy contains one or several SurfaceView.
20255     * SurfaceView is always considered transparent, but its children are not,
20256     * therefore all View objects remove themselves from the global transparent
20257     * region (passed as a parameter to this function).
20258     *
20259     * @param region The transparent region for this ViewAncestor (window).
20260     *
20261     * @return Returns true if the effective visibility of the view at this
20262     * point is opaque, regardless of the transparent region; returns false
20263     * if it is possible for underlying windows to be seen behind the view.
20264     *
20265     * {@hide}
20266     */
20267    public boolean gatherTransparentRegion(Region region) {
20268        final AttachInfo attachInfo = mAttachInfo;
20269        if (region != null && attachInfo != null) {
20270            final int pflags = mPrivateFlags;
20271            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20272                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20273                // remove it from the transparent region.
20274                final int[] location = attachInfo.mTransparentLocation;
20275                getLocationInWindow(location);
20276                region.op(location[0], location[1], location[0] + mRight - mLeft,
20277                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
20278            } else {
20279                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20280                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20281                    // the background drawable's non-transparent parts from this transparent region.
20282                    applyDrawableToTransparentRegion(mBackground, region);
20283                }
20284                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20285                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20286                    // Similarly, we remove the foreground drawable's non-transparent parts.
20287                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20288                }
20289            }
20290        }
20291        return true;
20292    }
20293
20294    /**
20295     * Play a sound effect for this view.
20296     *
20297     * <p>The framework will play sound effects for some built in actions, such as
20298     * clicking, but you may wish to play these effects in your widget,
20299     * for instance, for internal navigation.
20300     *
20301     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20302     * {@link #isSoundEffectsEnabled()} is true.
20303     *
20304     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20305     */
20306    public void playSoundEffect(int soundConstant) {
20307        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20308            return;
20309        }
20310        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20311    }
20312
20313    /**
20314     * BZZZTT!!1!
20315     *
20316     * <p>Provide haptic feedback to the user for this view.
20317     *
20318     * <p>The framework will provide haptic feedback for some built in actions,
20319     * such as long presses, but you may wish to provide feedback for your
20320     * own widget.
20321     *
20322     * <p>The feedback will only be performed if
20323     * {@link #isHapticFeedbackEnabled()} is true.
20324     *
20325     * @param feedbackConstant One of the constants defined in
20326     * {@link HapticFeedbackConstants}
20327     */
20328    public boolean performHapticFeedback(int feedbackConstant) {
20329        return performHapticFeedback(feedbackConstant, 0);
20330    }
20331
20332    /**
20333     * BZZZTT!!1!
20334     *
20335     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20336     *
20337     * @param feedbackConstant One of the constants defined in
20338     * {@link HapticFeedbackConstants}
20339     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20340     */
20341    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20342        if (mAttachInfo == null) {
20343            return false;
20344        }
20345        //noinspection SimplifiableIfStatement
20346        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20347                && !isHapticFeedbackEnabled()) {
20348            return false;
20349        }
20350        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20351                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20352    }
20353
20354    /**
20355     * Request that the visibility of the status bar or other screen/window
20356     * decorations be changed.
20357     *
20358     * <p>This method is used to put the over device UI into temporary modes
20359     * where the user's attention is focused more on the application content,
20360     * by dimming or hiding surrounding system affordances.  This is typically
20361     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20362     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20363     * to be placed behind the action bar (and with these flags other system
20364     * affordances) so that smooth transitions between hiding and showing them
20365     * can be done.
20366     *
20367     * <p>Two representative examples of the use of system UI visibility is
20368     * implementing a content browsing application (like a magazine reader)
20369     * and a video playing application.
20370     *
20371     * <p>The first code shows a typical implementation of a View in a content
20372     * browsing application.  In this implementation, the application goes
20373     * into a content-oriented mode by hiding the status bar and action bar,
20374     * and putting the navigation elements into lights out mode.  The user can
20375     * then interact with content while in this mode.  Such an application should
20376     * provide an easy way for the user to toggle out of the mode (such as to
20377     * check information in the status bar or access notifications).  In the
20378     * implementation here, this is done simply by tapping on the content.
20379     *
20380     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20381     *      content}
20382     *
20383     * <p>This second code sample shows a typical implementation of a View
20384     * in a video playing application.  In this situation, while the video is
20385     * playing the application would like to go into a complete full-screen mode,
20386     * to use as much of the display as possible for the video.  When in this state
20387     * the user can not interact with the application; the system intercepts
20388     * touching on the screen to pop the UI out of full screen mode.  See
20389     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20390     *
20391     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20392     *      content}
20393     *
20394     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20395     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20396     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20397     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20398     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20399     */
20400    public void setSystemUiVisibility(int visibility) {
20401        if (visibility != mSystemUiVisibility) {
20402            mSystemUiVisibility = visibility;
20403            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20404                mParent.recomputeViewAttributes(this);
20405            }
20406        }
20407    }
20408
20409    /**
20410     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20411     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20412     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20413     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20414     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20415     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20416     */
20417    public int getSystemUiVisibility() {
20418        return mSystemUiVisibility;
20419    }
20420
20421    /**
20422     * Returns the current system UI visibility that is currently set for
20423     * the entire window.  This is the combination of the
20424     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20425     * views in the window.
20426     */
20427    public int getWindowSystemUiVisibility() {
20428        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20429    }
20430
20431    /**
20432     * Override to find out when the window's requested system UI visibility
20433     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20434     * This is different from the callbacks received through
20435     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20436     * in that this is only telling you about the local request of the window,
20437     * not the actual values applied by the system.
20438     */
20439    public void onWindowSystemUiVisibilityChanged(int visible) {
20440    }
20441
20442    /**
20443     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20444     * the view hierarchy.
20445     */
20446    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20447        onWindowSystemUiVisibilityChanged(visible);
20448    }
20449
20450    /**
20451     * Set a listener to receive callbacks when the visibility of the system bar changes.
20452     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20453     */
20454    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20455        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20456        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20457            mParent.recomputeViewAttributes(this);
20458        }
20459    }
20460
20461    /**
20462     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20463     * the view hierarchy.
20464     */
20465    public void dispatchSystemUiVisibilityChanged(int visibility) {
20466        ListenerInfo li = mListenerInfo;
20467        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20468            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20469                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20470        }
20471    }
20472
20473    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20474        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20475        if (val != mSystemUiVisibility) {
20476            setSystemUiVisibility(val);
20477            return true;
20478        }
20479        return false;
20480    }
20481
20482    /** @hide */
20483    public void setDisabledSystemUiVisibility(int flags) {
20484        if (mAttachInfo != null) {
20485            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20486                mAttachInfo.mDisabledSystemUiVisibility = flags;
20487                if (mParent != null) {
20488                    mParent.recomputeViewAttributes(this);
20489                }
20490            }
20491        }
20492    }
20493
20494    /**
20495     * Creates an image that the system displays during the drag and drop
20496     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20497     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20498     * appearance as the given View. The default also positions the center of the drag shadow
20499     * directly under the touch point. If no View is provided (the constructor with no parameters
20500     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20501     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20502     * default is an invisible drag shadow.
20503     * <p>
20504     * You are not required to use the View you provide to the constructor as the basis of the
20505     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20506     * anything you want as the drag shadow.
20507     * </p>
20508     * <p>
20509     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20510     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20511     *  size and position of the drag shadow. It uses this data to construct a
20512     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20513     *  so that your application can draw the shadow image in the Canvas.
20514     * </p>
20515     *
20516     * <div class="special reference">
20517     * <h3>Developer Guides</h3>
20518     * <p>For a guide to implementing drag and drop features, read the
20519     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20520     * </div>
20521     */
20522    public static class DragShadowBuilder {
20523        private final WeakReference<View> mView;
20524
20525        /**
20526         * Constructs a shadow image builder based on a View. By default, the resulting drag
20527         * shadow will have the same appearance and dimensions as the View, with the touch point
20528         * over the center of the View.
20529         * @param view A View. Any View in scope can be used.
20530         */
20531        public DragShadowBuilder(View view) {
20532            mView = new WeakReference<View>(view);
20533        }
20534
20535        /**
20536         * Construct a shadow builder object with no associated View.  This
20537         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20538         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20539         * to supply the drag shadow's dimensions and appearance without
20540         * reference to any View object. If they are not overridden, then the result is an
20541         * invisible drag shadow.
20542         */
20543        public DragShadowBuilder() {
20544            mView = new WeakReference<View>(null);
20545        }
20546
20547        /**
20548         * Returns the View object that had been passed to the
20549         * {@link #View.DragShadowBuilder(View)}
20550         * constructor.  If that View parameter was {@code null} or if the
20551         * {@link #View.DragShadowBuilder()}
20552         * constructor was used to instantiate the builder object, this method will return
20553         * null.
20554         *
20555         * @return The View object associate with this builder object.
20556         */
20557        @SuppressWarnings({"JavadocReference"})
20558        final public View getView() {
20559            return mView.get();
20560        }
20561
20562        /**
20563         * Provides the metrics for the shadow image. These include the dimensions of
20564         * the shadow image, and the point within that shadow that should
20565         * be centered under the touch location while dragging.
20566         * <p>
20567         * The default implementation sets the dimensions of the shadow to be the
20568         * same as the dimensions of the View itself and centers the shadow under
20569         * the touch point.
20570         * </p>
20571         *
20572         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
20573         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20574         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20575         * image.
20576         *
20577         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
20578         * shadow image that should be underneath the touch point during the drag and drop
20579         * operation. Your application must set {@link android.graphics.Point#x} to the
20580         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20581         */
20582        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
20583            final View view = mView.get();
20584            if (view != null) {
20585                outShadowSize.set(view.getWidth(), view.getHeight());
20586                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
20587            } else {
20588                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20589            }
20590        }
20591
20592        /**
20593         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
20594         * based on the dimensions it received from the
20595         * {@link #onProvideShadowMetrics(Point, Point)} callback.
20596         *
20597         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
20598         */
20599        public void onDrawShadow(Canvas canvas) {
20600            final View view = mView.get();
20601            if (view != null) {
20602                view.draw(canvas);
20603            } else {
20604                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
20605            }
20606        }
20607    }
20608
20609    /**
20610     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
20611     * startDragAndDrop()} for newer platform versions.
20612     */
20613    @Deprecated
20614    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
20615                                   Object myLocalState, int flags) {
20616        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
20617    }
20618
20619    /**
20620     * Starts a drag and drop operation. When your application calls this method, it passes a
20621     * {@link android.view.View.DragShadowBuilder} object to the system. The
20622     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
20623     * to get metrics for the drag shadow, and then calls the object's
20624     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
20625     * <p>
20626     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
20627     *  drag events to all the View objects in your application that are currently visible. It does
20628     *  this either by calling the View object's drag listener (an implementation of
20629     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
20630     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
20631     *  Both are passed a {@link android.view.DragEvent} object that has a
20632     *  {@link android.view.DragEvent#getAction()} value of
20633     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
20634     * </p>
20635     * <p>
20636     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
20637     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
20638     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
20639     * to the View the user selected for dragging.
20640     * </p>
20641     * @param data A {@link android.content.ClipData} object pointing to the data to be
20642     * transferred by the drag and drop operation.
20643     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20644     * drag shadow.
20645     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
20646     * drop operation. This Object is put into every DragEvent object sent by the system during the
20647     * current drag.
20648     * <p>
20649     * myLocalState is a lightweight mechanism for the sending information from the dragged View
20650     * to the target Views. For example, it can contain flags that differentiate between a
20651     * a copy operation and a move operation.
20652     * </p>
20653     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
20654     * flags, or any combination of the following:
20655     *     <ul>
20656     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
20657     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
20658     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
20659     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
20660     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
20661     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
20662     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
20663     *     </ul>
20664     * @return {@code true} if the method completes successfully, or
20665     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
20666     * do a drag, and so no drag operation is in progress.
20667     */
20668    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
20669            Object myLocalState, int flags) {
20670        if (ViewDebug.DEBUG_DRAG) {
20671            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
20672        }
20673        if (mAttachInfo == null) {
20674            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
20675            return false;
20676        }
20677
20678        data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
20679
20680        boolean okay = false;
20681
20682        Point shadowSize = new Point();
20683        Point shadowTouchPoint = new Point();
20684        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
20685
20686        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
20687                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
20688            throw new IllegalStateException("Drag shadow dimensions must not be negative");
20689        }
20690
20691        if (ViewDebug.DEBUG_DRAG) {
20692            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
20693                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
20694        }
20695        if (mAttachInfo.mDragSurface != null) {
20696            mAttachInfo.mDragSurface.release();
20697        }
20698        mAttachInfo.mDragSurface = new Surface();
20699        try {
20700            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
20701                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
20702            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
20703                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
20704            if (mAttachInfo.mDragToken != null) {
20705                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20706                try {
20707                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20708                    shadowBuilder.onDrawShadow(canvas);
20709                } finally {
20710                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20711                }
20712
20713                final ViewRootImpl root = getViewRootImpl();
20714
20715                // Cache the local state object for delivery with DragEvents
20716                root.setLocalDragState(myLocalState);
20717
20718                // repurpose 'shadowSize' for the last touch point
20719                root.getLastTouchPoint(shadowSize);
20720
20721                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
20722                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
20723                        shadowTouchPoint.x, shadowTouchPoint.y, data);
20724                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
20725            }
20726        } catch (Exception e) {
20727            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
20728            mAttachInfo.mDragSurface.destroy();
20729            mAttachInfo.mDragSurface = null;
20730        }
20731
20732        return okay;
20733    }
20734
20735    /**
20736     * Cancels an ongoing drag and drop operation.
20737     * <p>
20738     * A {@link android.view.DragEvent} object with
20739     * {@link android.view.DragEvent#getAction()} value of
20740     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
20741     * {@link android.view.DragEvent#getResult()} value of {@code false}
20742     * will be sent to every
20743     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
20744     * even if they are not currently visible.
20745     * </p>
20746     * <p>
20747     * This method can be called on any View in the same window as the View on which
20748     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
20749     * was called.
20750     * </p>
20751     */
20752    public final void cancelDragAndDrop() {
20753        if (ViewDebug.DEBUG_DRAG) {
20754            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
20755        }
20756        if (mAttachInfo == null) {
20757            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
20758            return;
20759        }
20760        if (mAttachInfo.mDragToken != null) {
20761            try {
20762                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
20763            } catch (Exception e) {
20764                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
20765            }
20766            mAttachInfo.mDragToken = null;
20767        } else {
20768            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
20769        }
20770    }
20771
20772    /**
20773     * Updates the drag shadow for the ongoing drag and drop operation.
20774     *
20775     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20776     * new drag shadow.
20777     */
20778    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
20779        if (ViewDebug.DEBUG_DRAG) {
20780            Log.d(VIEW_LOG_TAG, "updateDragShadow");
20781        }
20782        if (mAttachInfo == null) {
20783            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
20784            return;
20785        }
20786        if (mAttachInfo.mDragToken != null) {
20787            try {
20788                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20789                try {
20790                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20791                    shadowBuilder.onDrawShadow(canvas);
20792                } finally {
20793                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20794                }
20795            } catch (Exception e) {
20796                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
20797            }
20798        } else {
20799            Log.e(VIEW_LOG_TAG, "No active drag");
20800        }
20801    }
20802
20803    /**
20804     * Starts a move from {startX, startY}, the amount of the movement will be the offset
20805     * between {startX, startY} and the new cursor positon.
20806     * @param startX horizontal coordinate where the move started.
20807     * @param startY vertical coordinate where the move started.
20808     * @return whether moving was started successfully.
20809     * @hide
20810     */
20811    public final boolean startMovingTask(float startX, float startY) {
20812        if (ViewDebug.DEBUG_POSITIONING) {
20813            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
20814        }
20815        try {
20816            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
20817        } catch (RemoteException e) {
20818            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
20819        }
20820        return false;
20821    }
20822
20823    /**
20824     * Handles drag events sent by the system following a call to
20825     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
20826     * startDragAndDrop()}.
20827     *<p>
20828     * When the system calls this method, it passes a
20829     * {@link android.view.DragEvent} object. A call to
20830     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
20831     * in DragEvent. The method uses these to determine what is happening in the drag and drop
20832     * operation.
20833     * @param event The {@link android.view.DragEvent} sent by the system.
20834     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
20835     * in DragEvent, indicating the type of drag event represented by this object.
20836     * @return {@code true} if the method was successful, otherwise {@code false}.
20837     * <p>
20838     *  The method should return {@code true} in response to an action type of
20839     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
20840     *  operation.
20841     * </p>
20842     * <p>
20843     *  The method should also return {@code true} in response to an action type of
20844     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
20845     *  {@code false} if it didn't.
20846     * </p>
20847     */
20848    public boolean onDragEvent(DragEvent event) {
20849        return false;
20850    }
20851
20852    /**
20853     * Detects if this View is enabled and has a drag event listener.
20854     * If both are true, then it calls the drag event listener with the
20855     * {@link android.view.DragEvent} it received. If the drag event listener returns
20856     * {@code true}, then dispatchDragEvent() returns {@code true}.
20857     * <p>
20858     * For all other cases, the method calls the
20859     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
20860     * method and returns its result.
20861     * </p>
20862     * <p>
20863     * This ensures that a drag event is always consumed, even if the View does not have a drag
20864     * event listener. However, if the View has a listener and the listener returns true, then
20865     * onDragEvent() is not called.
20866     * </p>
20867     */
20868    public boolean dispatchDragEvent(DragEvent event) {
20869        ListenerInfo li = mListenerInfo;
20870        //noinspection SimplifiableIfStatement
20871        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
20872                && li.mOnDragListener.onDrag(this, event)) {
20873            return true;
20874        }
20875        return onDragEvent(event);
20876    }
20877
20878    boolean canAcceptDrag() {
20879        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
20880    }
20881
20882    /**
20883     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
20884     * it is ever exposed at all.
20885     * @hide
20886     */
20887    public void onCloseSystemDialogs(String reason) {
20888    }
20889
20890    /**
20891     * Given a Drawable whose bounds have been set to draw into this view,
20892     * update a Region being computed for
20893     * {@link #gatherTransparentRegion(android.graphics.Region)} so
20894     * that any non-transparent parts of the Drawable are removed from the
20895     * given transparent region.
20896     *
20897     * @param dr The Drawable whose transparency is to be applied to the region.
20898     * @param region A Region holding the current transparency information,
20899     * where any parts of the region that are set are considered to be
20900     * transparent.  On return, this region will be modified to have the
20901     * transparency information reduced by the corresponding parts of the
20902     * Drawable that are not transparent.
20903     * {@hide}
20904     */
20905    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
20906        if (DBG) {
20907            Log.i("View", "Getting transparent region for: " + this);
20908        }
20909        final Region r = dr.getTransparentRegion();
20910        final Rect db = dr.getBounds();
20911        final AttachInfo attachInfo = mAttachInfo;
20912        if (r != null && attachInfo != null) {
20913            final int w = getRight()-getLeft();
20914            final int h = getBottom()-getTop();
20915            if (db.left > 0) {
20916                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
20917                r.op(0, 0, db.left, h, Region.Op.UNION);
20918            }
20919            if (db.right < w) {
20920                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
20921                r.op(db.right, 0, w, h, Region.Op.UNION);
20922            }
20923            if (db.top > 0) {
20924                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
20925                r.op(0, 0, w, db.top, Region.Op.UNION);
20926            }
20927            if (db.bottom < h) {
20928                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
20929                r.op(0, db.bottom, w, h, Region.Op.UNION);
20930            }
20931            final int[] location = attachInfo.mTransparentLocation;
20932            getLocationInWindow(location);
20933            r.translate(location[0], location[1]);
20934            region.op(r, Region.Op.INTERSECT);
20935        } else {
20936            region.op(db, Region.Op.DIFFERENCE);
20937        }
20938    }
20939
20940    private void checkForLongClick(int delayOffset, float x, float y) {
20941        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
20942            mHasPerformedLongPress = false;
20943
20944            if (mPendingCheckForLongPress == null) {
20945                mPendingCheckForLongPress = new CheckForLongPress();
20946            }
20947            mPendingCheckForLongPress.setAnchor(x, y);
20948            mPendingCheckForLongPress.rememberWindowAttachCount();
20949            postDelayed(mPendingCheckForLongPress,
20950                    ViewConfiguration.getLongPressTimeout() - delayOffset);
20951        }
20952    }
20953
20954    /**
20955     * Inflate a view from an XML resource.  This convenience method wraps the {@link
20956     * LayoutInflater} class, which provides a full range of options for view inflation.
20957     *
20958     * @param context The Context object for your activity or application.
20959     * @param resource The resource ID to inflate
20960     * @param root A view group that will be the parent.  Used to properly inflate the
20961     * layout_* parameters.
20962     * @see LayoutInflater
20963     */
20964    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
20965        LayoutInflater factory = LayoutInflater.from(context);
20966        return factory.inflate(resource, root);
20967    }
20968
20969    /**
20970     * Scroll the view with standard behavior for scrolling beyond the normal
20971     * content boundaries. Views that call this method should override
20972     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
20973     * results of an over-scroll operation.
20974     *
20975     * Views can use this method to handle any touch or fling-based scrolling.
20976     *
20977     * @param deltaX Change in X in pixels
20978     * @param deltaY Change in Y in pixels
20979     * @param scrollX Current X scroll value in pixels before applying deltaX
20980     * @param scrollY Current Y scroll value in pixels before applying deltaY
20981     * @param scrollRangeX Maximum content scroll range along the X axis
20982     * @param scrollRangeY Maximum content scroll range along the Y axis
20983     * @param maxOverScrollX Number of pixels to overscroll by in either direction
20984     *          along the X axis.
20985     * @param maxOverScrollY Number of pixels to overscroll by in either direction
20986     *          along the Y axis.
20987     * @param isTouchEvent true if this scroll operation is the result of a touch event.
20988     * @return true if scrolling was clamped to an over-scroll boundary along either
20989     *          axis, false otherwise.
20990     */
20991    @SuppressWarnings({"UnusedParameters"})
20992    protected boolean overScrollBy(int deltaX, int deltaY,
20993            int scrollX, int scrollY,
20994            int scrollRangeX, int scrollRangeY,
20995            int maxOverScrollX, int maxOverScrollY,
20996            boolean isTouchEvent) {
20997        final int overScrollMode = mOverScrollMode;
20998        final boolean canScrollHorizontal =
20999                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
21000        final boolean canScrollVertical =
21001                computeVerticalScrollRange() > computeVerticalScrollExtent();
21002        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
21003                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
21004        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
21005                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
21006
21007        int newScrollX = scrollX + deltaX;
21008        if (!overScrollHorizontal) {
21009            maxOverScrollX = 0;
21010        }
21011
21012        int newScrollY = scrollY + deltaY;
21013        if (!overScrollVertical) {
21014            maxOverScrollY = 0;
21015        }
21016
21017        // Clamp values if at the limits and record
21018        final int left = -maxOverScrollX;
21019        final int right = maxOverScrollX + scrollRangeX;
21020        final int top = -maxOverScrollY;
21021        final int bottom = maxOverScrollY + scrollRangeY;
21022
21023        boolean clampedX = false;
21024        if (newScrollX > right) {
21025            newScrollX = right;
21026            clampedX = true;
21027        } else if (newScrollX < left) {
21028            newScrollX = left;
21029            clampedX = true;
21030        }
21031
21032        boolean clampedY = false;
21033        if (newScrollY > bottom) {
21034            newScrollY = bottom;
21035            clampedY = true;
21036        } else if (newScrollY < top) {
21037            newScrollY = top;
21038            clampedY = true;
21039        }
21040
21041        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
21042
21043        return clampedX || clampedY;
21044    }
21045
21046    /**
21047     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
21048     * respond to the results of an over-scroll operation.
21049     *
21050     * @param scrollX New X scroll value in pixels
21051     * @param scrollY New Y scroll value in pixels
21052     * @param clampedX True if scrollX was clamped to an over-scroll boundary
21053     * @param clampedY True if scrollY was clamped to an over-scroll boundary
21054     */
21055    protected void onOverScrolled(int scrollX, int scrollY,
21056            boolean clampedX, boolean clampedY) {
21057        // Intentionally empty.
21058    }
21059
21060    /**
21061     * Returns the over-scroll mode for this view. The result will be
21062     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21063     * (allow over-scrolling only if the view content is larger than the container),
21064     * or {@link #OVER_SCROLL_NEVER}.
21065     *
21066     * @return This view's over-scroll mode.
21067     */
21068    public int getOverScrollMode() {
21069        return mOverScrollMode;
21070    }
21071
21072    /**
21073     * Set the over-scroll mode for this view. Valid over-scroll modes are
21074     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
21075     * (allow over-scrolling only if the view content is larger than the container),
21076     * or {@link #OVER_SCROLL_NEVER}.
21077     *
21078     * Setting the over-scroll mode of a view will have an effect only if the
21079     * view is capable of scrolling.
21080     *
21081     * @param overScrollMode The new over-scroll mode for this view.
21082     */
21083    public void setOverScrollMode(int overScrollMode) {
21084        if (overScrollMode != OVER_SCROLL_ALWAYS &&
21085                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
21086                overScrollMode != OVER_SCROLL_NEVER) {
21087            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
21088        }
21089        mOverScrollMode = overScrollMode;
21090    }
21091
21092    /**
21093     * Enable or disable nested scrolling for this view.
21094     *
21095     * <p>If this property is set to true the view will be permitted to initiate nested
21096     * scrolling operations with a compatible parent view in the current hierarchy. If this
21097     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
21098     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
21099     * the nested scroll.</p>
21100     *
21101     * @param enabled true to enable nested scrolling, false to disable
21102     *
21103     * @see #isNestedScrollingEnabled()
21104     */
21105    public void setNestedScrollingEnabled(boolean enabled) {
21106        if (enabled) {
21107            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
21108        } else {
21109            stopNestedScroll();
21110            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
21111        }
21112    }
21113
21114    /**
21115     * Returns true if nested scrolling is enabled for this view.
21116     *
21117     * <p>If nested scrolling is enabled and this View class implementation supports it,
21118     * this view will act as a nested scrolling child view when applicable, forwarding data
21119     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21120     * parent.</p>
21121     *
21122     * @return true if nested scrolling is enabled
21123     *
21124     * @see #setNestedScrollingEnabled(boolean)
21125     */
21126    public boolean isNestedScrollingEnabled() {
21127        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21128                PFLAG3_NESTED_SCROLLING_ENABLED;
21129    }
21130
21131    /**
21132     * Begin a nestable scroll operation along the given axes.
21133     *
21134     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21135     *
21136     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21137     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21138     * In the case of touch scrolling the nested scroll will be terminated automatically in
21139     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21140     * In the event of programmatic scrolling the caller must explicitly call
21141     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21142     *
21143     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21144     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21145     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21146     *
21147     * <p>At each incremental step of the scroll the caller should invoke
21148     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21149     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21150     * parent at least partially consumed the scroll and the caller should adjust the amount it
21151     * scrolls by.</p>
21152     *
21153     * <p>After applying the remainder of the scroll delta the caller should invoke
21154     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21155     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21156     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21157     * </p>
21158     *
21159     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21160     *             {@link #SCROLL_AXIS_VERTICAL}.
21161     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21162     *         the current gesture.
21163     *
21164     * @see #stopNestedScroll()
21165     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21166     * @see #dispatchNestedScroll(int, int, int, int, int[])
21167     */
21168    public boolean startNestedScroll(int axes) {
21169        if (hasNestedScrollingParent()) {
21170            // Already in progress
21171            return true;
21172        }
21173        if (isNestedScrollingEnabled()) {
21174            ViewParent p = getParent();
21175            View child = this;
21176            while (p != null) {
21177                try {
21178                    if (p.onStartNestedScroll(child, this, axes)) {
21179                        mNestedScrollingParent = p;
21180                        p.onNestedScrollAccepted(child, this, axes);
21181                        return true;
21182                    }
21183                } catch (AbstractMethodError e) {
21184                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21185                            "method onStartNestedScroll", e);
21186                    // Allow the search upward to continue
21187                }
21188                if (p instanceof View) {
21189                    child = (View) p;
21190                }
21191                p = p.getParent();
21192            }
21193        }
21194        return false;
21195    }
21196
21197    /**
21198     * Stop a nested scroll in progress.
21199     *
21200     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21201     *
21202     * @see #startNestedScroll(int)
21203     */
21204    public void stopNestedScroll() {
21205        if (mNestedScrollingParent != null) {
21206            mNestedScrollingParent.onStopNestedScroll(this);
21207            mNestedScrollingParent = null;
21208        }
21209    }
21210
21211    /**
21212     * Returns true if this view has a nested scrolling parent.
21213     *
21214     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21215     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21216     *
21217     * @return whether this view has a nested scrolling parent
21218     */
21219    public boolean hasNestedScrollingParent() {
21220        return mNestedScrollingParent != null;
21221    }
21222
21223    /**
21224     * Dispatch one step of a nested scroll in progress.
21225     *
21226     * <p>Implementations of views that support nested scrolling should call this to report
21227     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21228     * is not currently in progress or nested scrolling is not
21229     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21230     *
21231     * <p>Compatible View implementations should also call
21232     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21233     * consuming a component of the scroll event themselves.</p>
21234     *
21235     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21236     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21237     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21238     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21239     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21240     *                       in local view coordinates of this view from before this operation
21241     *                       to after it completes. View implementations may use this to adjust
21242     *                       expected input coordinate tracking.
21243     * @return true if the event was dispatched, false if it could not be dispatched.
21244     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21245     */
21246    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21247            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21248        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21249            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21250                int startX = 0;
21251                int startY = 0;
21252                if (offsetInWindow != null) {
21253                    getLocationInWindow(offsetInWindow);
21254                    startX = offsetInWindow[0];
21255                    startY = offsetInWindow[1];
21256                }
21257
21258                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21259                        dxUnconsumed, dyUnconsumed);
21260
21261                if (offsetInWindow != null) {
21262                    getLocationInWindow(offsetInWindow);
21263                    offsetInWindow[0] -= startX;
21264                    offsetInWindow[1] -= startY;
21265                }
21266                return true;
21267            } else if (offsetInWindow != null) {
21268                // No motion, no dispatch. Keep offsetInWindow up to date.
21269                offsetInWindow[0] = 0;
21270                offsetInWindow[1] = 0;
21271            }
21272        }
21273        return false;
21274    }
21275
21276    /**
21277     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21278     *
21279     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21280     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21281     * scrolling operation to consume some or all of the scroll operation before the child view
21282     * consumes it.</p>
21283     *
21284     * @param dx Horizontal scroll distance in pixels
21285     * @param dy Vertical scroll distance in pixels
21286     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21287     *                 and consumed[1] the consumed dy.
21288     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21289     *                       in local view coordinates of this view from before this operation
21290     *                       to after it completes. View implementations may use this to adjust
21291     *                       expected input coordinate tracking.
21292     * @return true if the parent consumed some or all of the scroll delta
21293     * @see #dispatchNestedScroll(int, int, int, int, int[])
21294     */
21295    public boolean dispatchNestedPreScroll(int dx, int dy,
21296            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21297        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21298            if (dx != 0 || dy != 0) {
21299                int startX = 0;
21300                int startY = 0;
21301                if (offsetInWindow != null) {
21302                    getLocationInWindow(offsetInWindow);
21303                    startX = offsetInWindow[0];
21304                    startY = offsetInWindow[1];
21305                }
21306
21307                if (consumed == null) {
21308                    if (mTempNestedScrollConsumed == null) {
21309                        mTempNestedScrollConsumed = new int[2];
21310                    }
21311                    consumed = mTempNestedScrollConsumed;
21312                }
21313                consumed[0] = 0;
21314                consumed[1] = 0;
21315                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21316
21317                if (offsetInWindow != null) {
21318                    getLocationInWindow(offsetInWindow);
21319                    offsetInWindow[0] -= startX;
21320                    offsetInWindow[1] -= startY;
21321                }
21322                return consumed[0] != 0 || consumed[1] != 0;
21323            } else if (offsetInWindow != null) {
21324                offsetInWindow[0] = 0;
21325                offsetInWindow[1] = 0;
21326            }
21327        }
21328        return false;
21329    }
21330
21331    /**
21332     * Dispatch a fling to a nested scrolling parent.
21333     *
21334     * <p>This method should be used to indicate that a nested scrolling child has detected
21335     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21336     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21337     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21338     * along a scrollable axis.</p>
21339     *
21340     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21341     * its own content, it can use this method to delegate the fling to its nested scrolling
21342     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21343     *
21344     * @param velocityX Horizontal fling velocity in pixels per second
21345     * @param velocityY Vertical fling velocity in pixels per second
21346     * @param consumed true if the child consumed the fling, false otherwise
21347     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21348     */
21349    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21350        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21351            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21352        }
21353        return false;
21354    }
21355
21356    /**
21357     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21358     *
21359     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21360     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21361     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21362     * before the child view consumes it. If this method returns <code>true</code>, a nested
21363     * parent view consumed the fling and this view should not scroll as a result.</p>
21364     *
21365     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21366     * the fling at a time. If a parent view consumed the fling this method will return false.
21367     * Custom view implementations should account for this in two ways:</p>
21368     *
21369     * <ul>
21370     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21371     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21372     *     position regardless.</li>
21373     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21374     *     even to settle back to a valid idle position.</li>
21375     * </ul>
21376     *
21377     * <p>Views should also not offer fling velocities to nested parent views along an axis
21378     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21379     * should not offer a horizontal fling velocity to its parents since scrolling along that
21380     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21381     *
21382     * @param velocityX Horizontal fling velocity in pixels per second
21383     * @param velocityY Vertical fling velocity in pixels per second
21384     * @return true if a nested scrolling parent consumed the fling
21385     */
21386    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21387        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21388            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21389        }
21390        return false;
21391    }
21392
21393    /**
21394     * Gets a scale factor that determines the distance the view should scroll
21395     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21396     * @return The vertical scroll scale factor.
21397     * @hide
21398     */
21399    protected float getVerticalScrollFactor() {
21400        if (mVerticalScrollFactor == 0) {
21401            TypedValue outValue = new TypedValue();
21402            if (!mContext.getTheme().resolveAttribute(
21403                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21404                throw new IllegalStateException(
21405                        "Expected theme to define listPreferredItemHeight.");
21406            }
21407            mVerticalScrollFactor = outValue.getDimension(
21408                    mContext.getResources().getDisplayMetrics());
21409        }
21410        return mVerticalScrollFactor;
21411    }
21412
21413    /**
21414     * Gets a scale factor that determines the distance the view should scroll
21415     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21416     * @return The horizontal scroll scale factor.
21417     * @hide
21418     */
21419    protected float getHorizontalScrollFactor() {
21420        // TODO: Should use something else.
21421        return getVerticalScrollFactor();
21422    }
21423
21424    /**
21425     * Return the value specifying the text direction or policy that was set with
21426     * {@link #setTextDirection(int)}.
21427     *
21428     * @return the defined text direction. It can be one of:
21429     *
21430     * {@link #TEXT_DIRECTION_INHERIT},
21431     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21432     * {@link #TEXT_DIRECTION_ANY_RTL},
21433     * {@link #TEXT_DIRECTION_LTR},
21434     * {@link #TEXT_DIRECTION_RTL},
21435     * {@link #TEXT_DIRECTION_LOCALE},
21436     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21437     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21438     *
21439     * @attr ref android.R.styleable#View_textDirection
21440     *
21441     * @hide
21442     */
21443    @ViewDebug.ExportedProperty(category = "text", mapping = {
21444            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21445            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21446            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21447            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21448            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21449            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21450            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21451            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21452    })
21453    public int getRawTextDirection() {
21454        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21455    }
21456
21457    /**
21458     * Set the text direction.
21459     *
21460     * @param textDirection the direction to set. Should be one of:
21461     *
21462     * {@link #TEXT_DIRECTION_INHERIT},
21463     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21464     * {@link #TEXT_DIRECTION_ANY_RTL},
21465     * {@link #TEXT_DIRECTION_LTR},
21466     * {@link #TEXT_DIRECTION_RTL},
21467     * {@link #TEXT_DIRECTION_LOCALE}
21468     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21469     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21470     *
21471     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21472     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21473     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21474     *
21475     * @attr ref android.R.styleable#View_textDirection
21476     */
21477    public void setTextDirection(int textDirection) {
21478        if (getRawTextDirection() != textDirection) {
21479            // Reset the current text direction and the resolved one
21480            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21481            resetResolvedTextDirection();
21482            // Set the new text direction
21483            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21484            // Do resolution
21485            resolveTextDirection();
21486            // Notify change
21487            onRtlPropertiesChanged(getLayoutDirection());
21488            // Refresh
21489            requestLayout();
21490            invalidate(true);
21491        }
21492    }
21493
21494    /**
21495     * Return the resolved text direction.
21496     *
21497     * @return the resolved text direction. Returns one of:
21498     *
21499     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21500     * {@link #TEXT_DIRECTION_ANY_RTL},
21501     * {@link #TEXT_DIRECTION_LTR},
21502     * {@link #TEXT_DIRECTION_RTL},
21503     * {@link #TEXT_DIRECTION_LOCALE},
21504     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21505     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21506     *
21507     * @attr ref android.R.styleable#View_textDirection
21508     */
21509    @ViewDebug.ExportedProperty(category = "text", mapping = {
21510            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21511            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21512            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21513            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21514            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21515            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21516            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21517            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21518    })
21519    public int getTextDirection() {
21520        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21521    }
21522
21523    /**
21524     * Resolve the text direction.
21525     *
21526     * @return true if resolution has been done, false otherwise.
21527     *
21528     * @hide
21529     */
21530    public boolean resolveTextDirection() {
21531        // Reset any previous text direction resolution
21532        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21533
21534        if (hasRtlSupport()) {
21535            // Set resolved text direction flag depending on text direction flag
21536            final int textDirection = getRawTextDirection();
21537            switch(textDirection) {
21538                case TEXT_DIRECTION_INHERIT:
21539                    if (!canResolveTextDirection()) {
21540                        // We cannot do the resolution if there is no parent, so use the default one
21541                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21542                        // Resolution will need to happen again later
21543                        return false;
21544                    }
21545
21546                    // Parent has not yet resolved, so we still return the default
21547                    try {
21548                        if (!mParent.isTextDirectionResolved()) {
21549                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21550                            // Resolution will need to happen again later
21551                            return false;
21552                        }
21553                    } catch (AbstractMethodError e) {
21554                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21555                                " does not fully implement ViewParent", e);
21556                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
21557                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21558                        return true;
21559                    }
21560
21561                    // Set current resolved direction to the same value as the parent's one
21562                    int parentResolvedDirection;
21563                    try {
21564                        parentResolvedDirection = mParent.getTextDirection();
21565                    } catch (AbstractMethodError e) {
21566                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21567                                " does not fully implement ViewParent", e);
21568                        parentResolvedDirection = TEXT_DIRECTION_LTR;
21569                    }
21570                    switch (parentResolvedDirection) {
21571                        case TEXT_DIRECTION_FIRST_STRONG:
21572                        case TEXT_DIRECTION_ANY_RTL:
21573                        case TEXT_DIRECTION_LTR:
21574                        case TEXT_DIRECTION_RTL:
21575                        case TEXT_DIRECTION_LOCALE:
21576                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
21577                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
21578                            mPrivateFlags2 |=
21579                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21580                            break;
21581                        default:
21582                            // Default resolved direction is "first strong" heuristic
21583                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21584                    }
21585                    break;
21586                case TEXT_DIRECTION_FIRST_STRONG:
21587                case TEXT_DIRECTION_ANY_RTL:
21588                case TEXT_DIRECTION_LTR:
21589                case TEXT_DIRECTION_RTL:
21590                case TEXT_DIRECTION_LOCALE:
21591                case TEXT_DIRECTION_FIRST_STRONG_LTR:
21592                case TEXT_DIRECTION_FIRST_STRONG_RTL:
21593                    // Resolved direction is the same as text direction
21594                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21595                    break;
21596                default:
21597                    // Default resolved direction is "first strong" heuristic
21598                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21599            }
21600        } else {
21601            // Default resolved direction is "first strong" heuristic
21602            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21603        }
21604
21605        // Set to resolved
21606        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
21607        return true;
21608    }
21609
21610    /**
21611     * Check if text direction resolution can be done.
21612     *
21613     * @return true if text direction resolution can be done otherwise return false.
21614     */
21615    public boolean canResolveTextDirection() {
21616        switch (getRawTextDirection()) {
21617            case TEXT_DIRECTION_INHERIT:
21618                if (mParent != null) {
21619                    try {
21620                        return mParent.canResolveTextDirection();
21621                    } catch (AbstractMethodError e) {
21622                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21623                                " does not fully implement ViewParent", e);
21624                    }
21625                }
21626                return false;
21627
21628            default:
21629                return true;
21630        }
21631    }
21632
21633    /**
21634     * Reset resolved text direction. Text direction will be resolved during a call to
21635     * {@link #onMeasure(int, int)}.
21636     *
21637     * @hide
21638     */
21639    public void resetResolvedTextDirection() {
21640        // Reset any previous text direction resolution
21641        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21642        // Set to default value
21643        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21644    }
21645
21646    /**
21647     * @return true if text direction is inherited.
21648     *
21649     * @hide
21650     */
21651    public boolean isTextDirectionInherited() {
21652        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
21653    }
21654
21655    /**
21656     * @return true if text direction is resolved.
21657     */
21658    public boolean isTextDirectionResolved() {
21659        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
21660    }
21661
21662    /**
21663     * Return the value specifying the text alignment or policy that was set with
21664     * {@link #setTextAlignment(int)}.
21665     *
21666     * @return the defined text alignment. It can be one of:
21667     *
21668     * {@link #TEXT_ALIGNMENT_INHERIT},
21669     * {@link #TEXT_ALIGNMENT_GRAVITY},
21670     * {@link #TEXT_ALIGNMENT_CENTER},
21671     * {@link #TEXT_ALIGNMENT_TEXT_START},
21672     * {@link #TEXT_ALIGNMENT_TEXT_END},
21673     * {@link #TEXT_ALIGNMENT_VIEW_START},
21674     * {@link #TEXT_ALIGNMENT_VIEW_END}
21675     *
21676     * @attr ref android.R.styleable#View_textAlignment
21677     *
21678     * @hide
21679     */
21680    @ViewDebug.ExportedProperty(category = "text", mapping = {
21681            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21682            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21683            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21684            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21685            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21686            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21687            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21688    })
21689    @TextAlignment
21690    public int getRawTextAlignment() {
21691        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
21692    }
21693
21694    /**
21695     * Set the text alignment.
21696     *
21697     * @param textAlignment The text alignment to set. Should be one of
21698     *
21699     * {@link #TEXT_ALIGNMENT_INHERIT},
21700     * {@link #TEXT_ALIGNMENT_GRAVITY},
21701     * {@link #TEXT_ALIGNMENT_CENTER},
21702     * {@link #TEXT_ALIGNMENT_TEXT_START},
21703     * {@link #TEXT_ALIGNMENT_TEXT_END},
21704     * {@link #TEXT_ALIGNMENT_VIEW_START},
21705     * {@link #TEXT_ALIGNMENT_VIEW_END}
21706     *
21707     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
21708     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
21709     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
21710     *
21711     * @attr ref android.R.styleable#View_textAlignment
21712     */
21713    public void setTextAlignment(@TextAlignment int textAlignment) {
21714        if (textAlignment != getRawTextAlignment()) {
21715            // Reset the current and resolved text alignment
21716            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
21717            resetResolvedTextAlignment();
21718            // Set the new text alignment
21719            mPrivateFlags2 |=
21720                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
21721            // Do resolution
21722            resolveTextAlignment();
21723            // Notify change
21724            onRtlPropertiesChanged(getLayoutDirection());
21725            // Refresh
21726            requestLayout();
21727            invalidate(true);
21728        }
21729    }
21730
21731    /**
21732     * Return the resolved text alignment.
21733     *
21734     * @return the resolved text alignment. Returns one of:
21735     *
21736     * {@link #TEXT_ALIGNMENT_GRAVITY},
21737     * {@link #TEXT_ALIGNMENT_CENTER},
21738     * {@link #TEXT_ALIGNMENT_TEXT_START},
21739     * {@link #TEXT_ALIGNMENT_TEXT_END},
21740     * {@link #TEXT_ALIGNMENT_VIEW_START},
21741     * {@link #TEXT_ALIGNMENT_VIEW_END}
21742     *
21743     * @attr ref android.R.styleable#View_textAlignment
21744     */
21745    @ViewDebug.ExportedProperty(category = "text", mapping = {
21746            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21747            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21748            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21749            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21750            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21751            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21752            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21753    })
21754    @TextAlignment
21755    public int getTextAlignment() {
21756        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
21757                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
21758    }
21759
21760    /**
21761     * Resolve the text alignment.
21762     *
21763     * @return true if resolution has been done, false otherwise.
21764     *
21765     * @hide
21766     */
21767    public boolean resolveTextAlignment() {
21768        // Reset any previous text alignment resolution
21769        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21770
21771        if (hasRtlSupport()) {
21772            // Set resolved text alignment flag depending on text alignment flag
21773            final int textAlignment = getRawTextAlignment();
21774            switch (textAlignment) {
21775                case TEXT_ALIGNMENT_INHERIT:
21776                    // Check if we can resolve the text alignment
21777                    if (!canResolveTextAlignment()) {
21778                        // We cannot do the resolution if there is no parent so use the default
21779                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21780                        // Resolution will need to happen again later
21781                        return false;
21782                    }
21783
21784                    // Parent has not yet resolved, so we still return the default
21785                    try {
21786                        if (!mParent.isTextAlignmentResolved()) {
21787                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21788                            // Resolution will need to happen again later
21789                            return false;
21790                        }
21791                    } catch (AbstractMethodError e) {
21792                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21793                                " does not fully implement ViewParent", e);
21794                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
21795                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21796                        return true;
21797                    }
21798
21799                    int parentResolvedTextAlignment;
21800                    try {
21801                        parentResolvedTextAlignment = mParent.getTextAlignment();
21802                    } catch (AbstractMethodError e) {
21803                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21804                                " does not fully implement ViewParent", e);
21805                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
21806                    }
21807                    switch (parentResolvedTextAlignment) {
21808                        case TEXT_ALIGNMENT_GRAVITY:
21809                        case TEXT_ALIGNMENT_TEXT_START:
21810                        case TEXT_ALIGNMENT_TEXT_END:
21811                        case TEXT_ALIGNMENT_CENTER:
21812                        case TEXT_ALIGNMENT_VIEW_START:
21813                        case TEXT_ALIGNMENT_VIEW_END:
21814                            // Resolved text alignment is the same as the parent resolved
21815                            // text alignment
21816                            mPrivateFlags2 |=
21817                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21818                            break;
21819                        default:
21820                            // Use default resolved text alignment
21821                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21822                    }
21823                    break;
21824                case TEXT_ALIGNMENT_GRAVITY:
21825                case TEXT_ALIGNMENT_TEXT_START:
21826                case TEXT_ALIGNMENT_TEXT_END:
21827                case TEXT_ALIGNMENT_CENTER:
21828                case TEXT_ALIGNMENT_VIEW_START:
21829                case TEXT_ALIGNMENT_VIEW_END:
21830                    // Resolved text alignment is the same as text alignment
21831                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21832                    break;
21833                default:
21834                    // Use default resolved text alignment
21835                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21836            }
21837        } else {
21838            // Use default resolved text alignment
21839            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21840        }
21841
21842        // Set the resolved
21843        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21844        return true;
21845    }
21846
21847    /**
21848     * Check if text alignment resolution can be done.
21849     *
21850     * @return true if text alignment resolution can be done otherwise return false.
21851     */
21852    public boolean canResolveTextAlignment() {
21853        switch (getRawTextAlignment()) {
21854            case TEXT_DIRECTION_INHERIT:
21855                if (mParent != null) {
21856                    try {
21857                        return mParent.canResolveTextAlignment();
21858                    } catch (AbstractMethodError e) {
21859                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21860                                " does not fully implement ViewParent", e);
21861                    }
21862                }
21863                return false;
21864
21865            default:
21866                return true;
21867        }
21868    }
21869
21870    /**
21871     * Reset resolved text alignment. Text alignment will be resolved during a call to
21872     * {@link #onMeasure(int, int)}.
21873     *
21874     * @hide
21875     */
21876    public void resetResolvedTextAlignment() {
21877        // Reset any previous text alignment resolution
21878        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21879        // Set to default
21880        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21881    }
21882
21883    /**
21884     * @return true if text alignment is inherited.
21885     *
21886     * @hide
21887     */
21888    public boolean isTextAlignmentInherited() {
21889        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
21890    }
21891
21892    /**
21893     * @return true if text alignment is resolved.
21894     */
21895    public boolean isTextAlignmentResolved() {
21896        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21897    }
21898
21899    /**
21900     * Generate a value suitable for use in {@link #setId(int)}.
21901     * This value will not collide with ID values generated at build time by aapt for R.id.
21902     *
21903     * @return a generated ID value
21904     */
21905    public static int generateViewId() {
21906        for (;;) {
21907            final int result = sNextGeneratedId.get();
21908            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
21909            int newValue = result + 1;
21910            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
21911            if (sNextGeneratedId.compareAndSet(result, newValue)) {
21912                return result;
21913            }
21914        }
21915    }
21916
21917    /**
21918     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
21919     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
21920     *                           a normal View or a ViewGroup with
21921     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
21922     * @hide
21923     */
21924    public void captureTransitioningViews(List<View> transitioningViews) {
21925        if (getVisibility() == View.VISIBLE) {
21926            transitioningViews.add(this);
21927        }
21928    }
21929
21930    /**
21931     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
21932     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
21933     * @hide
21934     */
21935    public void findNamedViews(Map<String, View> namedElements) {
21936        if (getVisibility() == VISIBLE || mGhostView != null) {
21937            String transitionName = getTransitionName();
21938            if (transitionName != null) {
21939                namedElements.put(transitionName, this);
21940            }
21941        }
21942    }
21943
21944    /**
21945     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
21946     * The default implementation does not care the location or event types, but some subclasses
21947     * may use it (such as WebViews).
21948     * @param event The MotionEvent from a mouse
21949     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
21950     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
21951     * @see PointerIcon
21952     */
21953    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
21954        final float x = event.getX(pointerIndex);
21955        final float y = event.getY(pointerIndex);
21956        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
21957            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
21958        }
21959        return mPointerIcon;
21960    }
21961
21962    /**
21963     * Set the pointer icon for the current view.
21964     * Passing {@code null} will restore the pointer icon to its default value.
21965     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
21966     */
21967    public void setPointerIcon(PointerIcon pointerIcon) {
21968        mPointerIcon = pointerIcon;
21969        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
21970            return;
21971        }
21972        try {
21973            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
21974        } catch (RemoteException e) {
21975        }
21976    }
21977
21978    /**
21979     * Gets the pointer icon for the current view.
21980     */
21981    public PointerIcon getPointerIcon() {
21982        return mPointerIcon;
21983    }
21984
21985    //
21986    // Properties
21987    //
21988    /**
21989     * A Property wrapper around the <code>alpha</code> functionality handled by the
21990     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
21991     */
21992    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
21993        @Override
21994        public void setValue(View object, float value) {
21995            object.setAlpha(value);
21996        }
21997
21998        @Override
21999        public Float get(View object) {
22000            return object.getAlpha();
22001        }
22002    };
22003
22004    /**
22005     * A Property wrapper around the <code>translationX</code> functionality handled by the
22006     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
22007     */
22008    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
22009        @Override
22010        public void setValue(View object, float value) {
22011            object.setTranslationX(value);
22012        }
22013
22014                @Override
22015        public Float get(View object) {
22016            return object.getTranslationX();
22017        }
22018    };
22019
22020    /**
22021     * A Property wrapper around the <code>translationY</code> functionality handled by the
22022     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
22023     */
22024    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
22025        @Override
22026        public void setValue(View object, float value) {
22027            object.setTranslationY(value);
22028        }
22029
22030        @Override
22031        public Float get(View object) {
22032            return object.getTranslationY();
22033        }
22034    };
22035
22036    /**
22037     * A Property wrapper around the <code>translationZ</code> functionality handled by the
22038     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
22039     */
22040    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
22041        @Override
22042        public void setValue(View object, float value) {
22043            object.setTranslationZ(value);
22044        }
22045
22046        @Override
22047        public Float get(View object) {
22048            return object.getTranslationZ();
22049        }
22050    };
22051
22052    /**
22053     * A Property wrapper around the <code>x</code> functionality handled by the
22054     * {@link View#setX(float)} and {@link View#getX()} methods.
22055     */
22056    public static final Property<View, Float> X = new FloatProperty<View>("x") {
22057        @Override
22058        public void setValue(View object, float value) {
22059            object.setX(value);
22060        }
22061
22062        @Override
22063        public Float get(View object) {
22064            return object.getX();
22065        }
22066    };
22067
22068    /**
22069     * A Property wrapper around the <code>y</code> functionality handled by the
22070     * {@link View#setY(float)} and {@link View#getY()} methods.
22071     */
22072    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
22073        @Override
22074        public void setValue(View object, float value) {
22075            object.setY(value);
22076        }
22077
22078        @Override
22079        public Float get(View object) {
22080            return object.getY();
22081        }
22082    };
22083
22084    /**
22085     * A Property wrapper around the <code>z</code> functionality handled by the
22086     * {@link View#setZ(float)} and {@link View#getZ()} methods.
22087     */
22088    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
22089        @Override
22090        public void setValue(View object, float value) {
22091            object.setZ(value);
22092        }
22093
22094        @Override
22095        public Float get(View object) {
22096            return object.getZ();
22097        }
22098    };
22099
22100    /**
22101     * A Property wrapper around the <code>rotation</code> functionality handled by the
22102     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
22103     */
22104    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
22105        @Override
22106        public void setValue(View object, float value) {
22107            object.setRotation(value);
22108        }
22109
22110        @Override
22111        public Float get(View object) {
22112            return object.getRotation();
22113        }
22114    };
22115
22116    /**
22117     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22118     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22119     */
22120    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22121        @Override
22122        public void setValue(View object, float value) {
22123            object.setRotationX(value);
22124        }
22125
22126        @Override
22127        public Float get(View object) {
22128            return object.getRotationX();
22129        }
22130    };
22131
22132    /**
22133     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22134     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22135     */
22136    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22137        @Override
22138        public void setValue(View object, float value) {
22139            object.setRotationY(value);
22140        }
22141
22142        @Override
22143        public Float get(View object) {
22144            return object.getRotationY();
22145        }
22146    };
22147
22148    /**
22149     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22150     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22151     */
22152    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22153        @Override
22154        public void setValue(View object, float value) {
22155            object.setScaleX(value);
22156        }
22157
22158        @Override
22159        public Float get(View object) {
22160            return object.getScaleX();
22161        }
22162    };
22163
22164    /**
22165     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22166     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22167     */
22168    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22169        @Override
22170        public void setValue(View object, float value) {
22171            object.setScaleY(value);
22172        }
22173
22174        @Override
22175        public Float get(View object) {
22176            return object.getScaleY();
22177        }
22178    };
22179
22180    /**
22181     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22182     * Each MeasureSpec represents a requirement for either the width or the height.
22183     * A MeasureSpec is comprised of a size and a mode. There are three possible
22184     * modes:
22185     * <dl>
22186     * <dt>UNSPECIFIED</dt>
22187     * <dd>
22188     * The parent has not imposed any constraint on the child. It can be whatever size
22189     * it wants.
22190     * </dd>
22191     *
22192     * <dt>EXACTLY</dt>
22193     * <dd>
22194     * The parent has determined an exact size for the child. The child is going to be
22195     * given those bounds regardless of how big it wants to be.
22196     * </dd>
22197     *
22198     * <dt>AT_MOST</dt>
22199     * <dd>
22200     * The child can be as large as it wants up to the specified size.
22201     * </dd>
22202     * </dl>
22203     *
22204     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22205     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22206     */
22207    public static class MeasureSpec {
22208        private static final int MODE_SHIFT = 30;
22209        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22210
22211        /** @hide */
22212        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22213        @Retention(RetentionPolicy.SOURCE)
22214        public @interface MeasureSpecMode {}
22215
22216        /**
22217         * Measure specification mode: The parent has not imposed any constraint
22218         * on the child. It can be whatever size it wants.
22219         */
22220        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22221
22222        /**
22223         * Measure specification mode: The parent has determined an exact size
22224         * for the child. The child is going to be given those bounds regardless
22225         * of how big it wants to be.
22226         */
22227        public static final int EXACTLY     = 1 << MODE_SHIFT;
22228
22229        /**
22230         * Measure specification mode: The child can be as large as it wants up
22231         * to the specified size.
22232         */
22233        public static final int AT_MOST     = 2 << MODE_SHIFT;
22234
22235        /**
22236         * Creates a measure specification based on the supplied size and mode.
22237         *
22238         * The mode must always be one of the following:
22239         * <ul>
22240         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22241         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22242         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22243         * </ul>
22244         *
22245         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22246         * implementation was such that the order of arguments did not matter
22247         * and overflow in either value could impact the resulting MeasureSpec.
22248         * {@link android.widget.RelativeLayout} was affected by this bug.
22249         * Apps targeting API levels greater than 17 will get the fixed, more strict
22250         * behavior.</p>
22251         *
22252         * @param size the size of the measure specification
22253         * @param mode the mode of the measure specification
22254         * @return the measure specification based on size and mode
22255         */
22256        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22257                                          @MeasureSpecMode int mode) {
22258            if (sUseBrokenMakeMeasureSpec) {
22259                return size + mode;
22260            } else {
22261                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22262            }
22263        }
22264
22265        /**
22266         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22267         * will automatically get a size of 0. Older apps expect this.
22268         *
22269         * @hide internal use only for compatibility with system widgets and older apps
22270         */
22271        public static int makeSafeMeasureSpec(int size, int mode) {
22272            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22273                return 0;
22274            }
22275            return makeMeasureSpec(size, mode);
22276        }
22277
22278        /**
22279         * Extracts the mode from the supplied measure specification.
22280         *
22281         * @param measureSpec the measure specification to extract the mode from
22282         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22283         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22284         *         {@link android.view.View.MeasureSpec#EXACTLY}
22285         */
22286        @MeasureSpecMode
22287        public static int getMode(int measureSpec) {
22288            //noinspection ResourceType
22289            return (measureSpec & MODE_MASK);
22290        }
22291
22292        /**
22293         * Extracts the size from the supplied measure specification.
22294         *
22295         * @param measureSpec the measure specification to extract the size from
22296         * @return the size in pixels defined in the supplied measure specification
22297         */
22298        public static int getSize(int measureSpec) {
22299            return (measureSpec & ~MODE_MASK);
22300        }
22301
22302        static int adjust(int measureSpec, int delta) {
22303            final int mode = getMode(measureSpec);
22304            int size = getSize(measureSpec);
22305            if (mode == UNSPECIFIED) {
22306                // No need to adjust size for UNSPECIFIED mode.
22307                return makeMeasureSpec(size, UNSPECIFIED);
22308            }
22309            size += delta;
22310            if (size < 0) {
22311                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22312                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22313                size = 0;
22314            }
22315            return makeMeasureSpec(size, mode);
22316        }
22317
22318        /**
22319         * Returns a String representation of the specified measure
22320         * specification.
22321         *
22322         * @param measureSpec the measure specification to convert to a String
22323         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22324         */
22325        public static String toString(int measureSpec) {
22326            int mode = getMode(measureSpec);
22327            int size = getSize(measureSpec);
22328
22329            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22330
22331            if (mode == UNSPECIFIED)
22332                sb.append("UNSPECIFIED ");
22333            else if (mode == EXACTLY)
22334                sb.append("EXACTLY ");
22335            else if (mode == AT_MOST)
22336                sb.append("AT_MOST ");
22337            else
22338                sb.append(mode).append(" ");
22339
22340            sb.append(size);
22341            return sb.toString();
22342        }
22343    }
22344
22345    private final class CheckForLongPress implements Runnable {
22346        private int mOriginalWindowAttachCount;
22347        private float mX;
22348        private float mY;
22349
22350        @Override
22351        public void run() {
22352            if (isPressed() && (mParent != null)
22353                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22354                if (performLongClick(mX, mY)) {
22355                    mHasPerformedLongPress = true;
22356                }
22357            }
22358        }
22359
22360        public void setAnchor(float x, float y) {
22361            mX = x;
22362            mY = y;
22363        }
22364
22365        public void rememberWindowAttachCount() {
22366            mOriginalWindowAttachCount = mWindowAttachCount;
22367        }
22368    }
22369
22370    private final class CheckForTap implements Runnable {
22371        public float x;
22372        public float y;
22373
22374        @Override
22375        public void run() {
22376            mPrivateFlags &= ~PFLAG_PREPRESSED;
22377            setPressed(true, x, y);
22378            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22379        }
22380    }
22381
22382    private final class PerformClick implements Runnable {
22383        @Override
22384        public void run() {
22385            performClick();
22386        }
22387    }
22388
22389    /**
22390     * This method returns a ViewPropertyAnimator object, which can be used to animate
22391     * specific properties on this View.
22392     *
22393     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22394     */
22395    public ViewPropertyAnimator animate() {
22396        if (mAnimator == null) {
22397            mAnimator = new ViewPropertyAnimator(this);
22398        }
22399        return mAnimator;
22400    }
22401
22402    /**
22403     * Sets the name of the View to be used to identify Views in Transitions.
22404     * Names should be unique in the View hierarchy.
22405     *
22406     * @param transitionName The name of the View to uniquely identify it for Transitions.
22407     */
22408    public final void setTransitionName(String transitionName) {
22409        mTransitionName = transitionName;
22410    }
22411
22412    /**
22413     * Returns the name of the View to be used to identify Views in Transitions.
22414     * Names should be unique in the View hierarchy.
22415     *
22416     * <p>This returns null if the View has not been given a name.</p>
22417     *
22418     * @return The name used of the View to be used to identify Views in Transitions or null
22419     * if no name has been given.
22420     */
22421    @ViewDebug.ExportedProperty
22422    public String getTransitionName() {
22423        return mTransitionName;
22424    }
22425
22426    /**
22427     * @hide
22428     */
22429    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22430        // Do nothing.
22431    }
22432
22433    /**
22434     * Interface definition for a callback to be invoked when a hardware key event is
22435     * dispatched to this view. The callback will be invoked before the key event is
22436     * given to the view. This is only useful for hardware keyboards; a software input
22437     * method has no obligation to trigger this listener.
22438     */
22439    public interface OnKeyListener {
22440        /**
22441         * Called when a hardware key is dispatched to a view. This allows listeners to
22442         * get a chance to respond before the target view.
22443         * <p>Key presses in software keyboards will generally NOT trigger this method,
22444         * although some may elect to do so in some situations. Do not assume a
22445         * software input method has to be key-based; even if it is, it may use key presses
22446         * in a different way than you expect, so there is no way to reliably catch soft
22447         * input key presses.
22448         *
22449         * @param v The view the key has been dispatched to.
22450         * @param keyCode The code for the physical key that was pressed
22451         * @param event The KeyEvent object containing full information about
22452         *        the event.
22453         * @return True if the listener has consumed the event, false otherwise.
22454         */
22455        boolean onKey(View v, int keyCode, KeyEvent event);
22456    }
22457
22458    /**
22459     * Interface definition for a callback to be invoked when a touch event is
22460     * dispatched to this view. The callback will be invoked before the touch
22461     * event is given to the view.
22462     */
22463    public interface OnTouchListener {
22464        /**
22465         * Called when a touch event is dispatched to a view. This allows listeners to
22466         * get a chance to respond before the target view.
22467         *
22468         * @param v The view the touch event has been dispatched to.
22469         * @param event The MotionEvent object containing full information about
22470         *        the event.
22471         * @return True if the listener has consumed the event, false otherwise.
22472         */
22473        boolean onTouch(View v, MotionEvent event);
22474    }
22475
22476    /**
22477     * Interface definition for a callback to be invoked when a hover event is
22478     * dispatched to this view. The callback will be invoked before the hover
22479     * event is given to the view.
22480     */
22481    public interface OnHoverListener {
22482        /**
22483         * Called when a hover 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 hover 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 onHover(View v, MotionEvent event);
22492    }
22493
22494    /**
22495     * Interface definition for a callback to be invoked when a generic motion event is
22496     * dispatched to this view. The callback will be invoked before the generic motion
22497     * event is given to the view.
22498     */
22499    public interface OnGenericMotionListener {
22500        /**
22501         * Called when a generic motion 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 generic motion 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 onGenericMotion(View v, MotionEvent event);
22510    }
22511
22512    /**
22513     * Interface definition for a callback to be invoked when a view has been clicked and held.
22514     */
22515    public interface OnLongClickListener {
22516        /**
22517         * Called when a view has been clicked and held.
22518         *
22519         * @param v The view that was clicked and held.
22520         *
22521         * @return true if the callback consumed the long click, false otherwise.
22522         */
22523        boolean onLongClick(View v);
22524    }
22525
22526    /**
22527     * Interface definition for a callback to be invoked when a drag is being dispatched
22528     * to this view.  The callback will be invoked before the hosting view's own
22529     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22530     * onDrag(event) behavior, it should return 'false' from this callback.
22531     *
22532     * <div class="special reference">
22533     * <h3>Developer Guides</h3>
22534     * <p>For a guide to implementing drag and drop features, read the
22535     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22536     * </div>
22537     */
22538    public interface OnDragListener {
22539        /**
22540         * Called when a drag event is dispatched to a view. This allows listeners
22541         * to get a chance to override base View behavior.
22542         *
22543         * @param v The View that received the drag event.
22544         * @param event The {@link android.view.DragEvent} object for the drag event.
22545         * @return {@code true} if the drag event was handled successfully, or {@code false}
22546         * if the drag event was not handled. Note that {@code false} will trigger the View
22547         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
22548         */
22549        boolean onDrag(View v, DragEvent event);
22550    }
22551
22552    /**
22553     * Interface definition for a callback to be invoked when the focus state of
22554     * a view changed.
22555     */
22556    public interface OnFocusChangeListener {
22557        /**
22558         * Called when the focus state of a view has changed.
22559         *
22560         * @param v The view whose state has changed.
22561         * @param hasFocus The new focus state of v.
22562         */
22563        void onFocusChange(View v, boolean hasFocus);
22564    }
22565
22566    /**
22567     * Interface definition for a callback to be invoked when a view is clicked.
22568     */
22569    public interface OnClickListener {
22570        /**
22571         * Called when a view has been clicked.
22572         *
22573         * @param v The view that was clicked.
22574         */
22575        void onClick(View v);
22576    }
22577
22578    /**
22579     * Interface definition for a callback to be invoked when a view is context clicked.
22580     */
22581    public interface OnContextClickListener {
22582        /**
22583         * Called when a view is context clicked.
22584         *
22585         * @param v The view that has been context clicked.
22586         * @return true if the callback consumed the context click, false otherwise.
22587         */
22588        boolean onContextClick(View v);
22589    }
22590
22591    /**
22592     * Interface definition for a callback to be invoked when the context menu
22593     * for this view is being built.
22594     */
22595    public interface OnCreateContextMenuListener {
22596        /**
22597         * Called when the context menu for this view is being built. It is not
22598         * safe to hold onto the menu after this method returns.
22599         *
22600         * @param menu The context menu that is being built
22601         * @param v The view for which the context menu is being built
22602         * @param menuInfo Extra information about the item for which the
22603         *            context menu should be shown. This information will vary
22604         *            depending on the class of v.
22605         */
22606        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
22607    }
22608
22609    /**
22610     * Interface definition for a callback to be invoked when the status bar changes
22611     * visibility.  This reports <strong>global</strong> changes to the system UI
22612     * state, not what the application is requesting.
22613     *
22614     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
22615     */
22616    public interface OnSystemUiVisibilityChangeListener {
22617        /**
22618         * Called when the status bar changes visibility because of a call to
22619         * {@link View#setSystemUiVisibility(int)}.
22620         *
22621         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22622         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
22623         * This tells you the <strong>global</strong> state of these UI visibility
22624         * flags, not what your app is currently applying.
22625         */
22626        public void onSystemUiVisibilityChange(int visibility);
22627    }
22628
22629    /**
22630     * Interface definition for a callback to be invoked when this view is attached
22631     * or detached from its window.
22632     */
22633    public interface OnAttachStateChangeListener {
22634        /**
22635         * Called when the view is attached to a window.
22636         * @param v The view that was attached
22637         */
22638        public void onViewAttachedToWindow(View v);
22639        /**
22640         * Called when the view is detached from a window.
22641         * @param v The view that was detached
22642         */
22643        public void onViewDetachedFromWindow(View v);
22644    }
22645
22646    /**
22647     * Listener for applying window insets on a view in a custom way.
22648     *
22649     * <p>Apps may choose to implement this interface if they want to apply custom policy
22650     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
22651     * is set, its
22652     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
22653     * method will be called instead of the View's own
22654     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
22655     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
22656     * the View's normal behavior as part of its own.</p>
22657     */
22658    public interface OnApplyWindowInsetsListener {
22659        /**
22660         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
22661         * on a View, this listener method will be called instead of the view's own
22662         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
22663         *
22664         * @param v The view applying window insets
22665         * @param insets The insets to apply
22666         * @return The insets supplied, minus any insets that were consumed
22667         */
22668        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
22669    }
22670
22671    private final class UnsetPressedState implements Runnable {
22672        @Override
22673        public void run() {
22674            setPressed(false);
22675        }
22676    }
22677
22678    /**
22679     * Base class for derived classes that want to save and restore their own
22680     * state in {@link android.view.View#onSaveInstanceState()}.
22681     */
22682    public static class BaseSavedState extends AbsSavedState {
22683        String mStartActivityRequestWhoSaved;
22684
22685        /**
22686         * Constructor used when reading from a parcel. Reads the state of the superclass.
22687         *
22688         * @param source parcel to read from
22689         */
22690        public BaseSavedState(Parcel source) {
22691            this(source, null);
22692        }
22693
22694        /**
22695         * Constructor used when reading from a parcel using a given class loader.
22696         * Reads the state of the superclass.
22697         *
22698         * @param source parcel to read from
22699         * @param loader ClassLoader to use for reading
22700         */
22701        public BaseSavedState(Parcel source, ClassLoader loader) {
22702            super(source, loader);
22703            mStartActivityRequestWhoSaved = source.readString();
22704        }
22705
22706        /**
22707         * Constructor called by derived classes when creating their SavedState objects
22708         *
22709         * @param superState The state of the superclass of this view
22710         */
22711        public BaseSavedState(Parcelable superState) {
22712            super(superState);
22713        }
22714
22715        @Override
22716        public void writeToParcel(Parcel out, int flags) {
22717            super.writeToParcel(out, flags);
22718            out.writeString(mStartActivityRequestWhoSaved);
22719        }
22720
22721        public static final Parcelable.Creator<BaseSavedState> CREATOR
22722                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
22723            @Override
22724            public BaseSavedState createFromParcel(Parcel in) {
22725                return new BaseSavedState(in);
22726            }
22727
22728            @Override
22729            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
22730                return new BaseSavedState(in, loader);
22731            }
22732
22733            @Override
22734            public BaseSavedState[] newArray(int size) {
22735                return new BaseSavedState[size];
22736            }
22737        };
22738    }
22739
22740    /**
22741     * A set of information given to a view when it is attached to its parent
22742     * window.
22743     */
22744    final static class AttachInfo {
22745        interface Callbacks {
22746            void playSoundEffect(int effectId);
22747            boolean performHapticFeedback(int effectId, boolean always);
22748        }
22749
22750        /**
22751         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
22752         * to a Handler. This class contains the target (View) to invalidate and
22753         * the coordinates of the dirty rectangle.
22754         *
22755         * For performance purposes, this class also implements a pool of up to
22756         * POOL_LIMIT objects that get reused. This reduces memory allocations
22757         * whenever possible.
22758         */
22759        static class InvalidateInfo {
22760            private static final int POOL_LIMIT = 10;
22761
22762            private static final SynchronizedPool<InvalidateInfo> sPool =
22763                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
22764
22765            View target;
22766
22767            int left;
22768            int top;
22769            int right;
22770            int bottom;
22771
22772            public static InvalidateInfo obtain() {
22773                InvalidateInfo instance = sPool.acquire();
22774                return (instance != null) ? instance : new InvalidateInfo();
22775            }
22776
22777            public void recycle() {
22778                target = null;
22779                sPool.release(this);
22780            }
22781        }
22782
22783        final IWindowSession mSession;
22784
22785        final IWindow mWindow;
22786
22787        final IBinder mWindowToken;
22788
22789        final Display mDisplay;
22790
22791        final Callbacks mRootCallbacks;
22792
22793        IWindowId mIWindowId;
22794        WindowId mWindowId;
22795
22796        /**
22797         * The top view of the hierarchy.
22798         */
22799        View mRootView;
22800
22801        IBinder mPanelParentWindowToken;
22802
22803        boolean mHardwareAccelerated;
22804        boolean mHardwareAccelerationRequested;
22805        ThreadedRenderer mThreadedRenderer;
22806        List<RenderNode> mPendingAnimatingRenderNodes;
22807
22808        /**
22809         * The state of the display to which the window is attached, as reported
22810         * by {@link Display#getState()}.  Note that the display state constants
22811         * declared by {@link Display} do not exactly line up with the screen state
22812         * constants declared by {@link View} (there are more display states than
22813         * screen states).
22814         */
22815        int mDisplayState = Display.STATE_UNKNOWN;
22816
22817        /**
22818         * Scale factor used by the compatibility mode
22819         */
22820        float mApplicationScale;
22821
22822        /**
22823         * Indicates whether the application is in compatibility mode
22824         */
22825        boolean mScalingRequired;
22826
22827        /**
22828         * Left position of this view's window
22829         */
22830        int mWindowLeft;
22831
22832        /**
22833         * Top position of this view's window
22834         */
22835        int mWindowTop;
22836
22837        /**
22838         * Indicates whether views need to use 32-bit drawing caches
22839         */
22840        boolean mUse32BitDrawingCache;
22841
22842        /**
22843         * For windows that are full-screen but using insets to layout inside
22844         * of the screen areas, these are the current insets to appear inside
22845         * the overscan area of the display.
22846         */
22847        final Rect mOverscanInsets = new Rect();
22848
22849        /**
22850         * For windows that are full-screen but using insets to layout inside
22851         * of the screen decorations, these are the current insets for the
22852         * content of the window.
22853         */
22854        final Rect mContentInsets = new Rect();
22855
22856        /**
22857         * For windows that are full-screen but using insets to layout inside
22858         * of the screen decorations, these are the current insets for the
22859         * actual visible parts of the window.
22860         */
22861        final Rect mVisibleInsets = new Rect();
22862
22863        /**
22864         * For windows that are full-screen but using insets to layout inside
22865         * of the screen decorations, these are the current insets for the
22866         * stable system windows.
22867         */
22868        final Rect mStableInsets = new Rect();
22869
22870        /**
22871         * For windows that include areas that are not covered by real surface these are the outsets
22872         * for real surface.
22873         */
22874        final Rect mOutsets = new Rect();
22875
22876        /**
22877         * In multi-window we force show the navigation bar. Because we don't want that the surface
22878         * size changes in this mode, we instead have a flag whether the navigation bar size should
22879         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
22880         */
22881        boolean mAlwaysConsumeNavBar;
22882
22883        /**
22884         * The internal insets given by this window.  This value is
22885         * supplied by the client (through
22886         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
22887         * be given to the window manager when changed to be used in laying
22888         * out windows behind it.
22889         */
22890        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
22891                = new ViewTreeObserver.InternalInsetsInfo();
22892
22893        /**
22894         * Set to true when mGivenInternalInsets is non-empty.
22895         */
22896        boolean mHasNonEmptyGivenInternalInsets;
22897
22898        /**
22899         * All views in the window's hierarchy that serve as scroll containers,
22900         * used to determine if the window can be resized or must be panned
22901         * to adjust for a soft input area.
22902         */
22903        final ArrayList<View> mScrollContainers = new ArrayList<View>();
22904
22905        final KeyEvent.DispatcherState mKeyDispatchState
22906                = new KeyEvent.DispatcherState();
22907
22908        /**
22909         * Indicates whether the view's window currently has the focus.
22910         */
22911        boolean mHasWindowFocus;
22912
22913        /**
22914         * The current visibility of the window.
22915         */
22916        int mWindowVisibility;
22917
22918        /**
22919         * Indicates the time at which drawing started to occur.
22920         */
22921        long mDrawingTime;
22922
22923        /**
22924         * Indicates whether or not ignoring the DIRTY_MASK flags.
22925         */
22926        boolean mIgnoreDirtyState;
22927
22928        /**
22929         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
22930         * to avoid clearing that flag prematurely.
22931         */
22932        boolean mSetIgnoreDirtyState = false;
22933
22934        /**
22935         * Indicates whether the view's window is currently in touch mode.
22936         */
22937        boolean mInTouchMode;
22938
22939        /**
22940         * Indicates whether the view has requested unbuffered input dispatching for the current
22941         * event stream.
22942         */
22943        boolean mUnbufferedDispatchRequested;
22944
22945        /**
22946         * Indicates that ViewAncestor should trigger a global layout change
22947         * the next time it performs a traversal
22948         */
22949        boolean mRecomputeGlobalAttributes;
22950
22951        /**
22952         * Always report new attributes at next traversal.
22953         */
22954        boolean mForceReportNewAttributes;
22955
22956        /**
22957         * Set during a traveral if any views want to keep the screen on.
22958         */
22959        boolean mKeepScreenOn;
22960
22961        /**
22962         * Set during a traveral if the light center needs to be updated.
22963         */
22964        boolean mNeedsUpdateLightCenter;
22965
22966        /**
22967         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
22968         */
22969        int mSystemUiVisibility;
22970
22971        /**
22972         * Hack to force certain system UI visibility flags to be cleared.
22973         */
22974        int mDisabledSystemUiVisibility;
22975
22976        /**
22977         * Last global system UI visibility reported by the window manager.
22978         */
22979        int mGlobalSystemUiVisibility = -1;
22980
22981        /**
22982         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
22983         * attached.
22984         */
22985        boolean mHasSystemUiListeners;
22986
22987        /**
22988         * Set if the window has requested to extend into the overscan region
22989         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
22990         */
22991        boolean mOverscanRequested;
22992
22993        /**
22994         * Set if the visibility of any views has changed.
22995         */
22996        boolean mViewVisibilityChanged;
22997
22998        /**
22999         * Set to true if a view has been scrolled.
23000         */
23001        boolean mViewScrollChanged;
23002
23003        /**
23004         * Set to true if high contrast mode enabled
23005         */
23006        boolean mHighContrastText;
23007
23008        /**
23009         * Set to true if a pointer event is currently being handled.
23010         */
23011        boolean mHandlingPointerEvent;
23012
23013        /**
23014         * Global to the view hierarchy used as a temporary for dealing with
23015         * x/y points in the transparent region computations.
23016         */
23017        final int[] mTransparentLocation = new int[2];
23018
23019        /**
23020         * Global to the view hierarchy used as a temporary for dealing with
23021         * x/y points in the ViewGroup.invalidateChild implementation.
23022         */
23023        final int[] mInvalidateChildLocation = new int[2];
23024
23025        /**
23026         * Global to the view hierarchy used as a temporary for dealing with
23027         * computing absolute on-screen location.
23028         */
23029        final int[] mTmpLocation = new int[2];
23030
23031        /**
23032         * Global to the view hierarchy used as a temporary for dealing with
23033         * x/y location when view is transformed.
23034         */
23035        final float[] mTmpTransformLocation = new float[2];
23036
23037        /**
23038         * The view tree observer used to dispatch global events like
23039         * layout, pre-draw, touch mode change, etc.
23040         */
23041        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
23042
23043        /**
23044         * A Canvas used by the view hierarchy to perform bitmap caching.
23045         */
23046        Canvas mCanvas;
23047
23048        /**
23049         * The view root impl.
23050         */
23051        final ViewRootImpl mViewRootImpl;
23052
23053        /**
23054         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
23055         * handler can be used to pump events in the UI events queue.
23056         */
23057        final Handler mHandler;
23058
23059        /**
23060         * Temporary for use in computing invalidate rectangles while
23061         * calling up the hierarchy.
23062         */
23063        final Rect mTmpInvalRect = new Rect();
23064
23065        /**
23066         * Temporary for use in computing hit areas with transformed views
23067         */
23068        final RectF mTmpTransformRect = new RectF();
23069
23070        /**
23071         * Temporary for use in computing hit areas with transformed views
23072         */
23073        final RectF mTmpTransformRect1 = new RectF();
23074
23075        /**
23076         * Temporary list of rectanges.
23077         */
23078        final List<RectF> mTmpRectList = new ArrayList<>();
23079
23080        /**
23081         * Temporary for use in transforming invalidation rect
23082         */
23083        final Matrix mTmpMatrix = new Matrix();
23084
23085        /**
23086         * Temporary for use in transforming invalidation rect
23087         */
23088        final Transformation mTmpTransformation = new Transformation();
23089
23090        /**
23091         * Temporary for use in querying outlines from OutlineProviders
23092         */
23093        final Outline mTmpOutline = new Outline();
23094
23095        /**
23096         * Temporary list for use in collecting focusable descendents of a view.
23097         */
23098        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
23099
23100        /**
23101         * The id of the window for accessibility purposes.
23102         */
23103        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
23104
23105        /**
23106         * Flags related to accessibility processing.
23107         *
23108         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
23109         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
23110         */
23111        int mAccessibilityFetchFlags;
23112
23113        /**
23114         * The drawable for highlighting accessibility focus.
23115         */
23116        Drawable mAccessibilityFocusDrawable;
23117
23118        /**
23119         * Show where the margins, bounds and layout bounds are for each view.
23120         */
23121        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23122
23123        /**
23124         * Point used to compute visible regions.
23125         */
23126        final Point mPoint = new Point();
23127
23128        /**
23129         * Used to track which View originated a requestLayout() call, used when
23130         * requestLayout() is called during layout.
23131         */
23132        View mViewRequestingLayout;
23133
23134        /**
23135         * Used to track views that need (at least) a partial relayout at their current size
23136         * during the next traversal.
23137         */
23138        List<View> mPartialLayoutViews = new ArrayList<>();
23139
23140        /**
23141         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23142         * modification. Lazily assigned during ViewRootImpl layout.
23143         */
23144        List<View> mEmptyPartialLayoutViews;
23145
23146        /**
23147         * Used to track the identity of the current drag operation.
23148         */
23149        IBinder mDragToken;
23150
23151        /**
23152         * The drag shadow surface for the current drag operation.
23153         */
23154        public Surface mDragSurface;
23155
23156        /**
23157         * Creates a new set of attachment information with the specified
23158         * events handler and thread.
23159         *
23160         * @param handler the events handler the view must use
23161         */
23162        AttachInfo(IWindowSession session, IWindow window, Display display,
23163                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
23164            mSession = session;
23165            mWindow = window;
23166            mWindowToken = window.asBinder();
23167            mDisplay = display;
23168            mViewRootImpl = viewRootImpl;
23169            mHandler = handler;
23170            mRootCallbacks = effectPlayer;
23171        }
23172    }
23173
23174    /**
23175     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23176     * is supported. This avoids keeping too many unused fields in most
23177     * instances of View.</p>
23178     */
23179    private static class ScrollabilityCache implements Runnable {
23180
23181        /**
23182         * Scrollbars are not visible
23183         */
23184        public static final int OFF = 0;
23185
23186        /**
23187         * Scrollbars are visible
23188         */
23189        public static final int ON = 1;
23190
23191        /**
23192         * Scrollbars are fading away
23193         */
23194        public static final int FADING = 2;
23195
23196        public boolean fadeScrollBars;
23197
23198        public int fadingEdgeLength;
23199        public int scrollBarDefaultDelayBeforeFade;
23200        public int scrollBarFadeDuration;
23201
23202        public int scrollBarSize;
23203        public ScrollBarDrawable scrollBar;
23204        public float[] interpolatorValues;
23205        public View host;
23206
23207        public final Paint paint;
23208        public final Matrix matrix;
23209        public Shader shader;
23210
23211        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23212
23213        private static final float[] OPAQUE = { 255 };
23214        private static final float[] TRANSPARENT = { 0.0f };
23215
23216        /**
23217         * When fading should start. This time moves into the future every time
23218         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23219         */
23220        public long fadeStartTime;
23221
23222
23223        /**
23224         * The current state of the scrollbars: ON, OFF, or FADING
23225         */
23226        public int state = OFF;
23227
23228        private int mLastColor;
23229
23230        public final Rect mScrollBarBounds = new Rect();
23231
23232        public static final int NOT_DRAGGING = 0;
23233        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23234        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23235        public int mScrollBarDraggingState = NOT_DRAGGING;
23236
23237        public float mScrollBarDraggingPos = 0;
23238
23239        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23240            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23241            scrollBarSize = configuration.getScaledScrollBarSize();
23242            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23243            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23244
23245            paint = new Paint();
23246            matrix = new Matrix();
23247            // use use a height of 1, and then wack the matrix each time we
23248            // actually use it.
23249            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23250            paint.setShader(shader);
23251            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23252
23253            this.host = host;
23254        }
23255
23256        public void setFadeColor(int color) {
23257            if (color != mLastColor) {
23258                mLastColor = color;
23259
23260                if (color != 0) {
23261                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23262                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23263                    paint.setShader(shader);
23264                    // Restore the default transfer mode (src_over)
23265                    paint.setXfermode(null);
23266                } else {
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            }
23272        }
23273
23274        public void run() {
23275            long now = AnimationUtils.currentAnimationTimeMillis();
23276            if (now >= fadeStartTime) {
23277
23278                // the animation fades the scrollbars out by changing
23279                // the opacity (alpha) from fully opaque to fully
23280                // transparent
23281                int nextFrame = (int) now;
23282                int framesCount = 0;
23283
23284                Interpolator interpolator = scrollBarInterpolator;
23285
23286                // Start opaque
23287                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23288
23289                // End transparent
23290                nextFrame += scrollBarFadeDuration;
23291                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23292
23293                state = FADING;
23294
23295                // Kick off the fade animation
23296                host.invalidate(true);
23297            }
23298        }
23299    }
23300
23301    /**
23302     * Resuable callback for sending
23303     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23304     */
23305    private class SendViewScrolledAccessibilityEvent implements Runnable {
23306        public volatile boolean mIsPending;
23307
23308        public void run() {
23309            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23310            mIsPending = false;
23311        }
23312    }
23313
23314    /**
23315     * <p>
23316     * This class represents a delegate that can be registered in a {@link View}
23317     * to enhance accessibility support via composition rather via inheritance.
23318     * It is specifically targeted to widget developers that extend basic View
23319     * classes i.e. classes in package android.view, that would like their
23320     * applications to be backwards compatible.
23321     * </p>
23322     * <div class="special reference">
23323     * <h3>Developer Guides</h3>
23324     * <p>For more information about making applications accessible, read the
23325     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23326     * developer guide.</p>
23327     * </div>
23328     * <p>
23329     * A scenario in which a developer would like to use an accessibility delegate
23330     * is overriding a method introduced in a later API version than the minimal API
23331     * version supported by the application. For example, the method
23332     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23333     * in API version 4 when the accessibility APIs were first introduced. If a
23334     * developer would like his application to run on API version 4 devices (assuming
23335     * all other APIs used by the application are version 4 or lower) and take advantage
23336     * of this method, instead of overriding the method which would break the application's
23337     * backwards compatibility, he can override the corresponding method in this
23338     * delegate and register the delegate in the target View if the API version of
23339     * the system is high enough, i.e. the API version is the same as or higher than the API
23340     * version that introduced
23341     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23342     * </p>
23343     * <p>
23344     * Here is an example implementation:
23345     * </p>
23346     * <code><pre><p>
23347     * if (Build.VERSION.SDK_INT >= 14) {
23348     *     // If the API version is equal of higher than the version in
23349     *     // which onInitializeAccessibilityNodeInfo was introduced we
23350     *     // register a delegate with a customized implementation.
23351     *     View view = findViewById(R.id.view_id);
23352     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23353     *         public void onInitializeAccessibilityNodeInfo(View host,
23354     *                 AccessibilityNodeInfo info) {
23355     *             // Let the default implementation populate the info.
23356     *             super.onInitializeAccessibilityNodeInfo(host, info);
23357     *             // Set some other information.
23358     *             info.setEnabled(host.isEnabled());
23359     *         }
23360     *     });
23361     * }
23362     * </code></pre></p>
23363     * <p>
23364     * This delegate contains methods that correspond to the accessibility methods
23365     * in View. If a delegate has been specified the implementation in View hands
23366     * off handling to the corresponding method in this delegate. The default
23367     * implementation the delegate methods behaves exactly as the corresponding
23368     * method in View for the case of no accessibility delegate been set. Hence,
23369     * to customize the behavior of a View method, clients can override only the
23370     * corresponding delegate method without altering the behavior of the rest
23371     * accessibility related methods of the host view.
23372     * </p>
23373     * <p>
23374     * <strong>Note:</strong> On platform versions prior to
23375     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23376     * views in the {@code android.widget.*} package are called <i>before</i>
23377     * host methods. This prevents certain properties such as class name from
23378     * being modified by overriding
23379     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23380     * as any changes will be overwritten by the host class.
23381     * <p>
23382     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23383     * methods are called <i>after</i> host methods, which all properties to be
23384     * modified without being overwritten by the host class.
23385     */
23386    public static class AccessibilityDelegate {
23387
23388        /**
23389         * Sends an accessibility event of the given type. If accessibility is not
23390         * enabled this method has no effect.
23391         * <p>
23392         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23393         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23394         * been set.
23395         * </p>
23396         *
23397         * @param host The View hosting the delegate.
23398         * @param eventType The type of the event to send.
23399         *
23400         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23401         */
23402        public void sendAccessibilityEvent(View host, int eventType) {
23403            host.sendAccessibilityEventInternal(eventType);
23404        }
23405
23406        /**
23407         * Performs the specified accessibility action on the view. For
23408         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23409         * <p>
23410         * The default implementation behaves as
23411         * {@link View#performAccessibilityAction(int, Bundle)
23412         *  View#performAccessibilityAction(int, Bundle)} for the case of
23413         *  no accessibility delegate been set.
23414         * </p>
23415         *
23416         * @param action The action to perform.
23417         * @return Whether the action was performed.
23418         *
23419         * @see View#performAccessibilityAction(int, Bundle)
23420         *      View#performAccessibilityAction(int, Bundle)
23421         */
23422        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23423            return host.performAccessibilityActionInternal(action, args);
23424        }
23425
23426        /**
23427         * Sends an accessibility event. This method behaves exactly as
23428         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23429         * empty {@link AccessibilityEvent} and does not perform a check whether
23430         * accessibility is enabled.
23431         * <p>
23432         * The default implementation behaves as
23433         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23434         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23435         * the case of no accessibility delegate been set.
23436         * </p>
23437         *
23438         * @param host The View hosting the delegate.
23439         * @param event The event to send.
23440         *
23441         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23442         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23443         */
23444        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23445            host.sendAccessibilityEventUncheckedInternal(event);
23446        }
23447
23448        /**
23449         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23450         * to its children for adding their text content to the event.
23451         * <p>
23452         * The default implementation behaves as
23453         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23454         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23455         * the case of no accessibility delegate been set.
23456         * </p>
23457         *
23458         * @param host The View hosting the delegate.
23459         * @param event The event.
23460         * @return True if the event population was completed.
23461         *
23462         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23463         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23464         */
23465        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23466            return host.dispatchPopulateAccessibilityEventInternal(event);
23467        }
23468
23469        /**
23470         * Gives a chance to the host View to populate the accessibility event with its
23471         * text content.
23472         * <p>
23473         * The default implementation behaves as
23474         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23475         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23476         * the case of no accessibility delegate been set.
23477         * </p>
23478         *
23479         * @param host The View hosting the delegate.
23480         * @param event The accessibility event which to populate.
23481         *
23482         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23483         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23484         */
23485        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23486            host.onPopulateAccessibilityEventInternal(event);
23487        }
23488
23489        /**
23490         * Initializes an {@link AccessibilityEvent} with information about the
23491         * the host View which is the event source.
23492         * <p>
23493         * The default implementation behaves as
23494         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23495         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23496         * the case of no accessibility delegate been set.
23497         * </p>
23498         *
23499         * @param host The View hosting the delegate.
23500         * @param event The event to initialize.
23501         *
23502         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23503         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23504         */
23505        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23506            host.onInitializeAccessibilityEventInternal(event);
23507        }
23508
23509        /**
23510         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23511         * <p>
23512         * The default implementation behaves as
23513         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23514         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23515         * the case of no accessibility delegate been set.
23516         * </p>
23517         *
23518         * @param host The View hosting the delegate.
23519         * @param info The instance to initialize.
23520         *
23521         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23522         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23523         */
23524        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23525            host.onInitializeAccessibilityNodeInfoInternal(info);
23526        }
23527
23528        /**
23529         * Called when a child of the host View has requested sending an
23530         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23531         * to augment the event.
23532         * <p>
23533         * The default implementation behaves as
23534         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23535         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
23536         * the case of no accessibility delegate been set.
23537         * </p>
23538         *
23539         * @param host The View hosting the delegate.
23540         * @param child The child which requests sending the event.
23541         * @param event The event to be sent.
23542         * @return True if the event should be sent
23543         *
23544         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23545         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23546         */
23547        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
23548                AccessibilityEvent event) {
23549            return host.onRequestSendAccessibilityEventInternal(child, event);
23550        }
23551
23552        /**
23553         * Gets the provider for managing a virtual view hierarchy rooted at this View
23554         * and reported to {@link android.accessibilityservice.AccessibilityService}s
23555         * that explore the window content.
23556         * <p>
23557         * The default implementation behaves as
23558         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
23559         * the case of no accessibility delegate been set.
23560         * </p>
23561         *
23562         * @return The provider.
23563         *
23564         * @see AccessibilityNodeProvider
23565         */
23566        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
23567            return null;
23568        }
23569
23570        /**
23571         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
23572         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
23573         * This method is responsible for obtaining an accessibility node info from a
23574         * pool of reusable instances and calling
23575         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
23576         * view to initialize the former.
23577         * <p>
23578         * <strong>Note:</strong> The client is responsible for recycling the obtained
23579         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
23580         * creation.
23581         * </p>
23582         * <p>
23583         * The default implementation behaves as
23584         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
23585         * the case of no accessibility delegate been set.
23586         * </p>
23587         * @return A populated {@link AccessibilityNodeInfo}.
23588         *
23589         * @see AccessibilityNodeInfo
23590         *
23591         * @hide
23592         */
23593        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
23594            return host.createAccessibilityNodeInfoInternal();
23595        }
23596    }
23597
23598    private class MatchIdPredicate implements Predicate<View> {
23599        public int mId;
23600
23601        @Override
23602        public boolean apply(View view) {
23603            return (view.mID == mId);
23604        }
23605    }
23606
23607    private class MatchLabelForPredicate implements Predicate<View> {
23608        private int mLabeledId;
23609
23610        @Override
23611        public boolean apply(View view) {
23612            return (view.mLabelForId == mLabeledId);
23613        }
23614    }
23615
23616    private class SendViewStateChangedAccessibilityEvent implements Runnable {
23617        private int mChangeTypes = 0;
23618        private boolean mPosted;
23619        private boolean mPostedWithDelay;
23620        private long mLastEventTimeMillis;
23621
23622        @Override
23623        public void run() {
23624            mPosted = false;
23625            mPostedWithDelay = false;
23626            mLastEventTimeMillis = SystemClock.uptimeMillis();
23627            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
23628                final AccessibilityEvent event = AccessibilityEvent.obtain();
23629                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
23630                event.setContentChangeTypes(mChangeTypes);
23631                sendAccessibilityEventUnchecked(event);
23632            }
23633            mChangeTypes = 0;
23634        }
23635
23636        public void runOrPost(int changeType) {
23637            mChangeTypes |= changeType;
23638
23639            // If this is a live region or the child of a live region, collect
23640            // all events from this frame and send them on the next frame.
23641            if (inLiveRegion()) {
23642                // If we're already posted with a delay, remove that.
23643                if (mPostedWithDelay) {
23644                    removeCallbacks(this);
23645                    mPostedWithDelay = false;
23646                }
23647                // Only post if we're not already posted.
23648                if (!mPosted) {
23649                    post(this);
23650                    mPosted = true;
23651                }
23652                return;
23653            }
23654
23655            if (mPosted) {
23656                return;
23657            }
23658
23659            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
23660            final long minEventIntevalMillis =
23661                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
23662            if (timeSinceLastMillis >= minEventIntevalMillis) {
23663                removeCallbacks(this);
23664                run();
23665            } else {
23666                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
23667                mPostedWithDelay = true;
23668            }
23669        }
23670    }
23671
23672    private boolean inLiveRegion() {
23673        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23674            return true;
23675        }
23676
23677        ViewParent parent = getParent();
23678        while (parent instanceof View) {
23679            if (((View) parent).getAccessibilityLiveRegion()
23680                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23681                return true;
23682            }
23683            parent = parent.getParent();
23684        }
23685
23686        return false;
23687    }
23688
23689    /**
23690     * Dump all private flags in readable format, useful for documentation and
23691     * sanity checking.
23692     */
23693    private static void dumpFlags() {
23694        final HashMap<String, String> found = Maps.newHashMap();
23695        try {
23696            for (Field field : View.class.getDeclaredFields()) {
23697                final int modifiers = field.getModifiers();
23698                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
23699                    if (field.getType().equals(int.class)) {
23700                        final int value = field.getInt(null);
23701                        dumpFlag(found, field.getName(), value);
23702                    } else if (field.getType().equals(int[].class)) {
23703                        final int[] values = (int[]) field.get(null);
23704                        for (int i = 0; i < values.length; i++) {
23705                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
23706                        }
23707                    }
23708                }
23709            }
23710        } catch (IllegalAccessException e) {
23711            throw new RuntimeException(e);
23712        }
23713
23714        final ArrayList<String> keys = Lists.newArrayList();
23715        keys.addAll(found.keySet());
23716        Collections.sort(keys);
23717        for (String key : keys) {
23718            Log.d(VIEW_LOG_TAG, found.get(key));
23719        }
23720    }
23721
23722    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
23723        // Sort flags by prefix, then by bits, always keeping unique keys
23724        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
23725        final int prefix = name.indexOf('_');
23726        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
23727        final String output = bits + " " + name;
23728        found.put(key, output);
23729    }
23730
23731    /** {@hide} */
23732    public void encode(@NonNull ViewHierarchyEncoder stream) {
23733        stream.beginObject(this);
23734        encodeProperties(stream);
23735        stream.endObject();
23736    }
23737
23738    /** {@hide} */
23739    @CallSuper
23740    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
23741        Object resolveId = ViewDebug.resolveId(getContext(), mID);
23742        if (resolveId instanceof String) {
23743            stream.addProperty("id", (String) resolveId);
23744        } else {
23745            stream.addProperty("id", mID);
23746        }
23747
23748        stream.addProperty("misc:transformation.alpha",
23749                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
23750        stream.addProperty("misc:transitionName", getTransitionName());
23751
23752        // layout
23753        stream.addProperty("layout:left", mLeft);
23754        stream.addProperty("layout:right", mRight);
23755        stream.addProperty("layout:top", mTop);
23756        stream.addProperty("layout:bottom", mBottom);
23757        stream.addProperty("layout:width", getWidth());
23758        stream.addProperty("layout:height", getHeight());
23759        stream.addProperty("layout:layoutDirection", getLayoutDirection());
23760        stream.addProperty("layout:layoutRtl", isLayoutRtl());
23761        stream.addProperty("layout:hasTransientState", hasTransientState());
23762        stream.addProperty("layout:baseline", getBaseline());
23763
23764        // layout params
23765        ViewGroup.LayoutParams layoutParams = getLayoutParams();
23766        if (layoutParams != null) {
23767            stream.addPropertyKey("layoutParams");
23768            layoutParams.encode(stream);
23769        }
23770
23771        // scrolling
23772        stream.addProperty("scrolling:scrollX", mScrollX);
23773        stream.addProperty("scrolling:scrollY", mScrollY);
23774
23775        // padding
23776        stream.addProperty("padding:paddingLeft", mPaddingLeft);
23777        stream.addProperty("padding:paddingRight", mPaddingRight);
23778        stream.addProperty("padding:paddingTop", mPaddingTop);
23779        stream.addProperty("padding:paddingBottom", mPaddingBottom);
23780        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
23781        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
23782        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
23783        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
23784        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
23785
23786        // measurement
23787        stream.addProperty("measurement:minHeight", mMinHeight);
23788        stream.addProperty("measurement:minWidth", mMinWidth);
23789        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
23790        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
23791
23792        // drawing
23793        stream.addProperty("drawing:elevation", getElevation());
23794        stream.addProperty("drawing:translationX", getTranslationX());
23795        stream.addProperty("drawing:translationY", getTranslationY());
23796        stream.addProperty("drawing:translationZ", getTranslationZ());
23797        stream.addProperty("drawing:rotation", getRotation());
23798        stream.addProperty("drawing:rotationX", getRotationX());
23799        stream.addProperty("drawing:rotationY", getRotationY());
23800        stream.addProperty("drawing:scaleX", getScaleX());
23801        stream.addProperty("drawing:scaleY", getScaleY());
23802        stream.addProperty("drawing:pivotX", getPivotX());
23803        stream.addProperty("drawing:pivotY", getPivotY());
23804        stream.addProperty("drawing:opaque", isOpaque());
23805        stream.addProperty("drawing:alpha", getAlpha());
23806        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
23807        stream.addProperty("drawing:shadow", hasShadow());
23808        stream.addProperty("drawing:solidColor", getSolidColor());
23809        stream.addProperty("drawing:layerType", mLayerType);
23810        stream.addProperty("drawing:willNotDraw", willNotDraw());
23811        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
23812        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
23813        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
23814        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
23815
23816        // focus
23817        stream.addProperty("focus:hasFocus", hasFocus());
23818        stream.addProperty("focus:isFocused", isFocused());
23819        stream.addProperty("focus:isFocusable", isFocusable());
23820        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
23821
23822        stream.addProperty("misc:clickable", isClickable());
23823        stream.addProperty("misc:pressed", isPressed());
23824        stream.addProperty("misc:selected", isSelected());
23825        stream.addProperty("misc:touchMode", isInTouchMode());
23826        stream.addProperty("misc:hovered", isHovered());
23827        stream.addProperty("misc:activated", isActivated());
23828
23829        stream.addProperty("misc:visibility", getVisibility());
23830        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
23831        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
23832
23833        stream.addProperty("misc:enabled", isEnabled());
23834        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
23835        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
23836
23837        // theme attributes
23838        Resources.Theme theme = getContext().getTheme();
23839        if (theme != null) {
23840            stream.addPropertyKey("theme");
23841            theme.encode(stream);
23842        }
23843
23844        // view attribute information
23845        int n = mAttributes != null ? mAttributes.length : 0;
23846        stream.addProperty("meta:__attrCount__", n/2);
23847        for (int i = 0; i < n; i += 2) {
23848            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
23849        }
23850
23851        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
23852
23853        // text
23854        stream.addProperty("text:textDirection", getTextDirection());
23855        stream.addProperty("text:textAlignment", getTextAlignment());
23856
23857        // accessibility
23858        CharSequence contentDescription = getContentDescription();
23859        stream.addProperty("accessibility:contentDescription",
23860                contentDescription == null ? "" : contentDescription.toString());
23861        stream.addProperty("accessibility:labelFor", getLabelFor());
23862        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
23863    }
23864
23865    /**
23866     * Determine if this view is rendered on a round wearable device and is the main view
23867     * on the screen.
23868     */
23869    private boolean shouldDrawRoundScrollbar() {
23870        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
23871            return false;
23872        }
23873
23874        final View rootView = getRootView();
23875        final WindowInsets insets = getRootWindowInsets();
23876
23877        int height = getHeight();
23878        int width = getWidth();
23879        int displayHeight = rootView.getHeight();
23880        int displayWidth = rootView.getWidth();
23881
23882        if (height != displayHeight || width != displayWidth) {
23883            return false;
23884        }
23885
23886        getLocationOnScreen(mAttachInfo.mTmpLocation);
23887        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
23888                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
23889    }
23890}
23891